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

import cn.estsh.i3plus.ext.mes.api.base.IFileManageService;
import cn.estsh.i3plus.ext.mes.api.base.ep.IEpPartExtDataService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.ep.IEpPartExtDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.model.SxBatchUploadFileModel;
import cn.estsh.i3plus.ext.mes.pojo.model.ep.EpPartExtModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
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.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description : MES物料服务
 * @Reference :
 * @Author : xiangming.liao
 * @CreateDate : 2020-02-21
 * @Modify:
 **/
@Slf4j
@Service
public class EpPartExtDataService implements IEpPartExtDataService {
    public static final Logger LOGGER = LoggerFactory.getLogger(EpPartExtDataService.class);

    @Autowired
    private MesPartExtRepository partExtRepository;
    @Autowired
    private IFileManageService fileManageService;
    @Autowired
    private MesFileRepository fileRepository;
    @Autowired
    private IEpPartExtDao partExtDao;

    @Override
    public ListPager<EpPartExtModel> queryMesPartExtByPager(MesPartExt partExt, Pager pager) {
        pager = PagerHelper.getPager(pager, partExtDao.queryPartByPagerCount(partExt));
        List<EpPartExtModel> partExtModelList = partExtDao.queryPartByPager(partExt , pager);
        if (!CollectionUtils.isEmpty(partExtModelList)) {
            for (EpPartExtModel item : partExtModelList) {
                if (null != item) {
                    item.setProcessMatchTypeName(StringUtils.isEmpty(item.getProcessMatchType()) ? null : MesExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(item.getProcessMatchType()));
                    item.setPackageMatchTypeName(StringUtils.isEmpty(item.getPackageMatchType()) ? null : MesExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(item.getPackageMatchType()));
                    item.setIsOqcName(StringUtils.isEmpty(item.getIsOqc()) ? null : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(item.getIsOqc()));
                    item.setIsCreateSnName(StringUtils.isEmpty(item.getIsCreateSn()) ? null : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(item.getIsCreateSn()));
                    item.setIsPSPartsName(StringUtils.isEmpty(item.getIsPSParts()) ? null : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(item.getIsPSParts()));
                    item.setSalesToName((item.getSalesTo() == null ? null : MesExtEnumUtil.SALES_TO_STR.valueOfDescription(item.getSalesTo())));
                }
            }
        }
        return new ListPager(partExtModelList, pager);
    }

    @Override
    public MesPartExt insertMesPartExt(MultipartFile file, MesPartExt partExt) {

        //唯一性校验
        MesPartExt partExtDb = partExtRepository.getByProperty(
                new String[]{MesExtConstWords.PART_NO, MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{partExt.getPartNo(), partExt.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});

        if (null != partExtDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("物料号为【%s】的记录已存在", partExt.getPartNo())
                    .build();
        }

        if(file != null){
            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(partExt.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, partExt.getCreateUser());
            partExt.setFileId(fileRepository.insert(f).getId());
            partExt.setFileOriginName(sysFile.getFileOriginalName());
            partExt.setUploadDatetime(partExt.getCreateDatetime());
        }

        //增加成品批次号
//        partExt.setPartLotNo(partExt.getPartLotNo());
        partExt.setPartNoExt(partExt.getPartNo());
        new ConvertBeanExt(partExt).convertBean(partExt);
        return partExtRepository.insert(partExt);
    }

    @Override
    public MesPartExt updateMesPartExt(MultipartFile file, MesPartExt partExt) {

        //对id做有效性校验
        MesPartExt partExtDb = partExtRepository.getById(partExt.getId());
        if (partExtDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("物料号为【%s】的记录不存在", partExt.getPartNo())
                    .build();
        }
        if (file != null) {
            SysFile sysFile = fileManageService.uploadFile(file);
            MesFile f = new MesFile();
            f.setOrganizeCode(partExt.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, partExt.getModifyUser());
            partExtDb.setFileId(fileRepository.insert(f).getId());
            partExtDb.setFileOriginName(sysFile.getFileOriginalName());
            partExtDb.setUploadDatetime(f.getCreateDatetime());
        }

        partExtDb.setPartName(partExt.getPartName());
        partExtDb.setBriefText(partExt.getBriefText());
        partExtDb.setUnit(partExt.getUnit());
        partExtDb.setCategoryCode1(partExt.getCategoryCode1());
        partExtDb.setCategoryCode2(partExt.getCategoryCode2());
        partExtDb.setCategoryCode3(partExt.getCategoryCode3());
        partExtDb.setProcessMatchType(partExt.getProcessMatchType());
        partExtDb.setPackageMatchType(partExt.getPackageMatchType());
        partExtDb.setPackSpecCode(partExt.getPackSpecCode());
        partExtDb.setPptCode(partExt.getPptCode());
        partExtDb.setColorCode(partExt.getColorCode());
        partExtDb.setColorName(partExt.getColorName());
        partExtDb.setSalesTo(partExt.getSalesTo());
        partExtDb.setIsOqc(partExt.getIsOqc());
        partExtDb.setIsCreateSn(partExt.getIsCreateSn());
        partExtDb.setIsPSParts(partExt.getIsPSParts());
        partExtDb.setStandardWork(partExt.getStandardWork());
        partExtDb.setJapanDesc(partExt.getJapanDesc());
        partExtDb.setGoodsCode(partExt.getGoodsCode());
        partExtDb.setPrefix(partExt.getPrefix());
        partExtDb.setQualityAssureCode(partExt.getQualityAssureCode());
        partExtDb.setIdentifyCode(partExt.getIdentifyCode());
        partExtDb.setSnLastCode(partExt.getSnLastCode());
        //增加成品批次号
        partExtDb.setPartLotNoLength(partExt.getPartLotNoLength());
        //partExtDb.setPartSpecQty(partExt.getPartSpecQty());
        partExtDb.setQty2(partExt.getQty2());
        ConvertBean.serviceModelUpdate(partExtDb, partExt.getModifyUser());
        new ConvertBeanExt(partExtDb).convertBean(partExtDb);
        return partExtRepository.save(partExtDb);
    }

    @Override
    public void updateMesPartExtStatusById(Long id, int status, String userName) {
        MesPartExt partExt = partExtRepository.getById(id);
        if (null == partExt || partExt.getIsValid() == status) return;
        partExt.setIsValid(status);
        partExt.setSystemSyncStatusExt(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(partExt, userName);
        new ConvertBeanExt(partExt).convertBean(partExt);
        partExtRepository.save(partExt);
    }

    @Override
    public SxBatchUploadFileModel doBatchUploadPartFile(MultipartFile[] files, String lotNo, String organizeCode, String userName) {
        List<MesPartExt> partExtList = partExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.LOT_NO},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), lotNo});
        if (CollectionUtils.isEmpty(partExtList)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("未查询到关联导入批次号[%s]的物料信息", lotNo)
                    .build();
        }
        Map<String, List<MesPartExt>> fileNameMap = partExtList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getFileOriginName())))
                .collect(Collectors.groupingBy(MesPartExt::getFileOriginName));
        if (CollectionUtils.isEmpty(fileNameMap)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("关联导入批次号[%s]的物料信息均未维护文件名称", lotNo)
                    .build();
        }
        Integer successCount = 0;
        Integer failureCount = 0;
        List<String> unUploadFileList = null;
        for (MultipartFile file : files) {
            if (null == file) {
                continue;
            }
            if (!fileNameMap.containsKey(file.getOriginalFilename())) {
                if (CollectionUtils.isEmpty(unUploadFileList)) {
                    unUploadFileList = new ArrayList<>();
                }
                unUploadFileList.add(file.getOriginalFilename());
                failureCount ++;
                continue;
            }

            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(organizeCode);
            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, userName);
            Long fileId = fileRepository.insert(f).getId();
            for (MesPartExt partExt : fileNameMap.get(file.getOriginalFilename())) {
                if (null == partExt) {
                    continue;
                }
                partExt.setFileId(fileId);
                partExt.setUploadDatetime(f.getCreateDatetime());
                ConvertBean.serviceModelUpdate(partExt, userName);
                new ConvertBeanExt(partExt).convertBean(partExt);
                partExtRepository.save(partExt);
            }
            successCount ++;
        }
        if (successCount.compareTo(0) == 0) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("关联导入批次号[%s]的物料信息的文件名称均未与此次批量上传的文件匹配", lotNo)
                    .build();
        }

        SxBatchUploadFileModel model = new SxBatchUploadFileModel();
        model.setSuccessCount(successCount);
        model.setFailureCount(failureCount);
        model.setUnUploadFileList(unUploadFileList);
        return model;
    }

}
