package com.qmth.paper.library.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.paper.library.common.config.DictionaryConfig;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.BasicAttachment;
import com.qmth.paper.library.common.mapper.BasicAttachmentMapper;
import com.qmth.paper.library.common.service.BasicAttachmentService;
import com.qmth.paper.library.common.util.FileStoreUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Objects;

/**
 * <p>
 * 所有附件记录表 服务实现类
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Service
public class BasicAttachmentServiceImpl extends ServiceImpl<BasicAttachmentMapper, BasicAttachment> implements BasicAttachmentService {
    private final static Logger log = LoggerFactory.getLogger(BasicAttachmentServiceImpl.class);

    @Resource
    private FileStoreUtil fileStoreUtil;

    @Autowired
    private DictionaryConfig dictionaryConfig;

    /**
     * 删除附件
     *
     * @param basicAttachment
     */
    @Override
    public void deleteAttachment(BasicAttachment basicAttachment) {
        deleteAttachmentCommon(basicAttachment);
    }

    /**
     * 删除附件公用
     *
     * @param basicAttachment
     */
    public void deleteAttachmentCommon(BasicAttachment basicAttachment) {
        if (Objects.nonNull(basicAttachment) && Objects.nonNull(basicAttachment.getPath())) {
            JSONObject jsonObject = JSONObject.parseObject(basicAttachment.getPath());
            String type = String.valueOf(jsonObject.get(SystemConstant.TYPE));
            if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.OSS)) {//删除阿里云附件
//                ossUtil.ossDelete(jsonObject.get(SystemConstant.PATH).toString());
//                if (Objects.nonNull(jsonObject.get(SystemConstant.PDF_PATH))) {
//                    ossUtil.ossDelete(jsonObject.get(SystemConstant.PDF_PATH).toString());
//                }
            } else {//删除服务器附件
                if (fileStoreUtil.isOssStore()) {
                    File file = new File(jsonObject.get(SystemConstant.PATH).toString());
                    file.delete();
                    if (Objects.nonNull(jsonObject.get(SystemConstant.PDF_PATH))) {
                        file = new File(jsonObject.get(SystemConstant.PDF_PATH).toString());
                        file.delete();
                    }
                }
            }
        }
    }
}
