package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base;

import cn.estsh.i3plus.ext.mes.api.base.IFileManageService;
import cn.estsh.i3plus.ext.mes.api.base.IModuleExcelManageService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.IModuleExcelManageDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesModuleExcelManage;
import cn.estsh.i3plus.ext.mes.pojo.model.ModuleExcelManageModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesModuleExcelManageRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesFile;
import cn.estsh.i3plus.pojo.mes.repository.MesFileRepository;
import cn.estsh.i3plus.pojo.platform.bean.SysFile;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class ModuleExcelManageService implements IModuleExcelManageService {

    @Autowired
    private IModuleExcelManageDao moduleExcelManageDao;

    @Autowired
    private IFileManageService fileManageService;

    @Autowired
    private MesModuleExcelManageRepository moduleExcelManageRepository;

    @Autowired
    private MesFileRepository fileRepository;

    @Override
    public ListPager<ModuleExcelManageModel> queryModuleExcelManageByPager(MesModuleExcelManage mduleExcelManage, Pager pager) {
        pager = PagerHelper.getPager(pager, moduleExcelManageDao.queryModuleExcelManageByPagerCount(mduleExcelManage));
        List<ModuleExcelManageModel> moduleExcelManageModelList = moduleExcelManageDao.queryModuleExcelManageByPager(mduleExcelManage , pager);
        return new ListPager(moduleExcelManageModelList, pager);
    }

    @Override
    public void insertModuleExcelManage(MultipartFile file, MesModuleExcelManage moduleExcelManage) {
        DdlPackBean packBean = MesExtHqlPack.getAllBaseData(moduleExcelManage.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(moduleExcelManage.getModuleCode(), MesExtConstWords.MODULE_CODE, packBean);
        MesModuleExcelManage moduleExcelManageDb = moduleExcelManageRepository.getByProperty(packBean);
        if (null != moduleExcelManageDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("模块代码[%s]记录已存在", moduleExcelManage.getModuleCode())
                    .build();
        }

        SysFile sysFile = fileManageService.uploadFile(file);
        if (sysFile.getFileTypeId() == null) {
            log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                    .build();
        }

        MesFile f = new MesFile();
        f.setOrganizeCode(moduleExcelManage.getOrganizeCode());
        f.setFileName(sysFile.getDfsFileName());
        f.setFileUrl(sysFile.getFilePath());
        f.setFileSize(String.valueOf(sysFile.getFileSize()));
        f.setFileType(String.valueOf(sysFile.getFileTypeName()));
        f.setFileOriginName(sysFile.getFileOriginalName());
        f.setGroupName(sysFile.getDfsGroupName());
        f.setSyncTag(0);
        ConvertBean.serviceModelInitialize(f, moduleExcelManage.getCreateUser());
        moduleExcelManage.setFileId(fileRepository.insert(f).getId());
        ConvertBean.serviceModelInitialize(moduleExcelManage, moduleExcelManage.getCreateUser());
        moduleExcelManageRepository.insert(moduleExcelManage);
    }

    @Override
    public void updateModuleExcelManage(MultipartFile file, MesModuleExcelManage moduleExcelManage) {
        MesModuleExcelManage moduleExcelManageDb = moduleExcelManageRepository.getById(moduleExcelManage.getId());
        if (moduleExcelManageDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", moduleExcelManage.getId())
                    .build();
        }

        if (file == null && StringUtils.isEmpty(moduleExcelManage.getFileId())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("上传的文件为null，后台未能接收到")
                    .build();
        }

        //改变文件时清除fileUrl
        if (StringUtils.isEmpty(moduleExcelManage.getFileUrl())) {
            SysFile sysFile = fileManageService.uploadFile(file);
            MesFile f = new MesFile();
            f.setOrganizeCode(moduleExcelManage.getOrganizeCode());
            f.setFileName(sysFile.getDfsFileName());
            f.setFileUrl(sysFile.getFilePath());
            f.setFileSize(String.valueOf(sysFile.getFileSize()));
            f.setFileType(String.valueOf(sysFile.getFileTypeName()));
            f.setFileOriginName(sysFile.getFileOriginalName());
            f.setGroupName(sysFile.getDfsGroupName());
            f.setSyncTag(0);
            ConvertBean.serviceModelInitialize(f, moduleExcelManage.getModifyUser());
            moduleExcelManageDb.setFileId(fileRepository.insert(f).getId());
        }
        moduleExcelManageDb.setModuleName(moduleExcelManage.getModuleName());
        ConvertBean.serviceModelUpdate(moduleExcelManageDb, moduleExcelManage.getModifyUser());
        moduleExcelManageRepository.save(moduleExcelManageDb);
    }

    @Override
    public int updateModuleExcelManageValidById(Long id, Integer status, String userName) {
        if (status != CommonEnumUtil.IS_VAILD.INVAILD.getValue() && status != CommonEnumUtil.IS_VAILD.VAILD.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("启用，禁用枚举状态值【%s】未被定义", status)
                    .build();
        }
        return moduleExcelManageRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{status, userName, TimeTool.getNowTime(true)});
    }

    @Override
    public void doDownLoadModuleExcelManage(HttpServletResponse resp, String fileUrl) {
        fileManageService.getFileByUrl(resp, fileUrl);
    }

    @Override
    public MesFile getTemplateFile(String organizeCode, String templateCode) {
        MesModuleExcelManage moduleExcelManageDb = moduleExcelManageRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.MODULE_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), templateCode});
        if(null == moduleExcelManageDb || StringUtils.isEmpty(moduleExcelManageDb.getFileId())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("模板代码为[%s]数据信息不存在", templateCode)
                    .build();
        }
        MesFile fileDb = fileRepository.getById(moduleExcelManageDb.getFileId());
        if(null == fileDb || StringUtils.isEmpty(fileDb.getFileUrl())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("模板代码为[%s]对应文件信息不存在", templateCode)
                    .build();
        }
        return fileDb;
    }

}
