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.IPartExtDataService;
import cn.estsh.i3plus.ext.mes.api.busi.bu.IBuRecordChangeDataService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.IPartExtDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.model.MesPartExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.SxBatchUploadFileModel;
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.base.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesFile;
import cn.estsh.i3plus.pojo.mes.bean.MesPartCategory;
import cn.estsh.i3plus.pojo.mes.repository.MesFileRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesPartCategoryRepository;
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.BeanUtils;
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.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    private MesPartExtRepository partExtRepository;
    @Autowired
    private IFileManageService fileManageService;
    @Autowired
    private MesFileRepository fileRepository;
    @Autowired
    private IPartExtDao partExtDao;
    @Autowired
    private IBuRecordChangeDataService recordChangeDataService;
    @Autowired
    private MesPartCategoryRepository partCategoryRepository;

    @Override
    public ListPager<MesPartExtModel> queryMesPartExtByPager(MesPartExt partExt, Pager pager) {
        pager = PagerHelper.getPager(pager, partExtDao.queryPartByPagerCount(partExt));
        List<MesPartExtModel> partExtModelList = partExtDao.queryPartByPager(partExt , pager);
        if (!CollectionUtils.isEmpty(partExtModelList)) {
            for (MesPartExtModel 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.setBigProcessMatchTypeName((item.getBigProcessMatchType() == null) || (item.getBigProcessMatchType() == 0) ? null : MesExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(item.getBigProcessMatchType()));
                    item.setIsPrintQualityAssureIndiaName((item.getIsPrintQualityAssureIndia() == null) || (item.getIsPrintQualityAssureIndia() == 0) ? null : MesExtEnumUtil.IS_PRINT_QUALITY_ASSURE_INDIA.valueOfDescription(item.getIsPrintQualityAssureIndia()));
                    item.setSalesToName((StringUtils.isEmpty(item.getSalesTo()) ? "" : MesExtEnumUtil.SALES_TO_STR.valueOfDescription(item.getSalesTo())));
                    item.setBigPackageMatchTypeName(StringUtils.isEmpty(item.getBigPackageMatchType()) ? null : MesExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(item.getBigPackageMatchType()));
                }
            }
        }
        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(partExt.getSnPrintTimes() != null){
            if(partExt.getSnPrintTimes() <= 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("条码次数在不为空的情况下必须为正整数，不输入默认打印次数为1次")
                        .build();
            }
        }

        if(partExt.getPackNoPrintTimes() != null){
            if(partExt.getPackNoPrintTimes() <= 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("条码次数在不为空的情况下必须为正整数，不输入默认打印次数为1次")
                        .build();
            }
        }

        if(partExt.getSnPrintColumnNumber() != null){
            if(partExt.getPackNoPrintTimes() <= 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("条码次数在不为空的情况下必须为正整数，不输入默认打印次数为1次")
                        .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.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(partExt.getSnPrintTimes() != null){
            if(partExt.getSnPrintTimes() <= 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("条码次数在不为空的情况下必须为正整数，不输入默认打印次数为1次")
                        .build();
            }
        }

        if(partExt.getPackNoPrintTimes() != null){
            if(partExt.getPackNoPrintTimes() <= 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("条码次数在不为空的情况下必须为正整数，不输入默认打印次数为1次")
                        .build();
            }
        }

        if(partExt.getSnPrintColumnNumber() != null){
            if(partExt.getPackNoPrintTimes() <= 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("条码次数在不为空的情况下必须为正整数，不输入默认打印次数为1次")
                        .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());
            partExt.setFileId(fileRepository.insert(f).getId());
            partExt.setFileOriginName(sysFile.getFileOriginalName());
            partExt.setUploadDatetime(f.getCreateDatetime());
        }

        ConvertBean.serviceModelUpdate(partExtDb, partExt.getModifyUser());
        //新增物料字段变更履历
        doRecordChangeData(getModel(partExtDb), getModel(partExt), MesPartExtModel.class);

        partExtDb.setFileId(partExt.getFileId());
        partExtDb.setFileOriginName(partExt.getFileOriginName());
        partExtDb.setUploadDatetime(partExt.getUploadDatetime());
        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.setPartSpecQty(partExt.getPartSpecQty());
        partExtDb.setQty2(partExt.getQty2());
        partExtDb.setBigProcessMatchType(partExt.getBigProcessMatchType());
        partExtDb.setPackNoPrintTimes(partExt.getPackNoPrintTimes());
        partExtDb.setSnPrintTimes(partExt.getSnPrintTimes());
        partExtDb.setSnPrintColumnNumber(partExt.getSnPrintColumnNumber());
        partExtDb.setIsPrintQualityAssureIndia(partExt.getIsPrintQualityAssureIndia());
        partExtDb.setShiXiangDiCode(partExt.getShiXiangDiCode());
        partExtDb.setModel(partExt.getModel());
        partExtDb.setProductNumber(partExt.getProductNumber());
        partExtDb.setSnPackagePrintColumnNumber(partExt.getSnPackagePrintColumnNumber());
        partExtDb.setBigPackageMatchType(partExt.getBigPackageMatchType());
        partExtDb.setIsRepairWorkReport(partExt.getIsRepairWorkReport());
        partExtDb.setIsManualReport(partExt.getIsManualReport());
        new ConvertBeanExt(partExtDb).convertBean(partExtDb);
        MesPartExt mesPartExt = partExtRepository.save(partExtDb);

        //StringBuffer updateLogContent = createUpdateLogContent(partExt, partExtDb);
        //if(updateLogContent.toString().length() != 0){
        //    MesPartRecord partRecord = new MesPartRecord();
        //    partRecord.setUpdateContent(updateLogContent.toString());
        //    partRecord.setPartNo(partExt.getPartNo());
        //    ConvertBean.serviceModelInitialize(partRecord, partExt.getModifyUser());
        //    partRecordRepository.insert(partRecord);
        //}
        return mesPartExt;
    }

    public MesPartExtModel getModel(MesPartExt partExt){
        MesPartExtModel partExtModel = new MesPartExtModel();
        BeanUtils.copyProperties(partExt, partExtModel);
        partExtModel.setProcessMatchTypeName(StringUtils.isEmpty(partExtModel.getProcessMatchType()) ? null : MesExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(partExtModel.getProcessMatchType()));
        partExtModel.setPackageMatchTypeName(StringUtils.isEmpty(partExtModel.getPackageMatchType()) ? null : MesExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(partExtModel.getPackageMatchType()));
        partExtModel.setIsOqcName(StringUtils.isEmpty(partExtModel.getIsOqc()) ? null : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(partExtModel.getIsOqc()));
        partExtModel.setIsCreateSnName(StringUtils.isEmpty(partExtModel.getIsCreateSn()) ? null : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(partExtModel.getIsCreateSn()));
        partExtModel.setIsPSPartsName(StringUtils.isEmpty(partExtModel.getIsPSParts()) ? null : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(partExtModel.getIsPSParts()));
        partExtModel.setBigProcessMatchTypeName( (partExtModel.getBigProcessMatchType() == null) || (partExtModel.getBigProcessMatchType() == 0) ? null : MesExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(partExtModel.getBigProcessMatchType()));
        partExtModel.setIsPrintQualityAssureIndiaName( (partExtModel.getIsPrintQualityAssureIndia() == null) || (partExtModel.getIsPrintQualityAssureIndia() == 0) ? null : MesExtEnumUtil.IS_PRINT_QUALITY_ASSURE_INDIA.valueOfDescription(partExtModel.getIsPrintQualityAssureIndia()));
        partExtModel.setSalesToName((StringUtils.isEmpty(partExtModel.getSalesTo()) ? "" : MesExtEnumUtil.SALES_TO_STR.valueOfDescription(partExtModel.getSalesTo())));
        Map<String, List<MesPartCategory>> partCategoryMap = queryMesPartCategoryList(partExt.getOrganizeCode());
        if(!CollectionUtils.isEmpty(partCategoryMap)){

            String category1Key = new StringJoiner(MesExtConstWords.AND)
                    .add(MesEnumUtil.PART_CATEGORY_TYPE.CATEGORY_ONE.getValue())
                    .add(partExtModel.getCategoryCode1()).toString();

            String category2Key = new StringJoiner(MesExtConstWords.AND)
                    .add(MesEnumUtil.PART_CATEGORY_TYPE.CATEGORY_TWO.getValue())
                    .add(partExtModel.getCategoryCode2()).toString();

            String category3Key = new StringJoiner(MesExtConstWords.AND)
                    .add(MesEnumUtil.PART_CATEGORY_TYPE.CATEGORY_THREE.getValue())
                    .add(partExtModel.getCategoryCode3()).toString();

            partExtModel.setCategoryCode1(!StringUtils.isEmpty(partExtModel.getCategoryCode1()) &&
                    partCategoryMap.containsKey(category1Key) ?
                    partCategoryMap.get(category1Key).stream().iterator().next().getCategoryName() : ""
            );

            partExtModel.setCategoryCode2(!StringUtils.isEmpty(partExtModel.getCategoryCode2()) &&
                    partCategoryMap.containsKey(category2Key) ?
                    partCategoryMap.get(category2Key).stream().iterator().next().getCategoryName() : ""
            );

            partExtModel.setCategoryCode3(!StringUtils.isEmpty(partExtModel.getCategoryCode3()) &&
                    partCategoryMap.containsKey(category3Key) ?
                    partCategoryMap.get(category3Key).stream().iterator().next().getCategoryName() : ""
            );


        }

        return partExtModel;
    }

    public void doRecordChangeData(MesPartExtModel sourceData, MesPartExtModel newData, Class clazz){
        recordChangeDataService.doRecordChangeData(MesExtEnumUtil.FIELD_MENU_TYPE.PART.getValue(), sourceData, newData, clazz, sourceData.getPartNo(), sourceData.getPartName(), sourceData.getOrganizeCode(), sourceData.getModifyDatetime());
    }

    public void doRecordChangeData(MesPartExtModel sourceData, MesPartExtModel newData, Class clazz, List<String> fields){
        recordChangeDataService.doRecordChangeData(MesExtEnumUtil.FIELD_MENU_TYPE.PART.getValue(), sourceData, newData, clazz, sourceData.getPartNo(), sourceData.getPartName(), sourceData.getOrganizeCode(), fields, sourceData.getModifyDatetime());
    }

    @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);
    }

    private Map<String, List<MesPartCategory>> queryMesPartCategoryList(String organizeCode){
        List<MesPartCategory> partCategoryList = partCategoryRepository.findByProperty(new String[]{"organizeCode", "isDeleted", "isValid"}, new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesPartCategory>> partCategoryMap = partCategoryList.stream().collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getCategoryType()).add(o.getCategoryCode()).toString()));
        return partCategoryMap;
    }

    @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;
    }

    public StringBuffer createUpdateLogContent(Object dbData, Object newData) {
        try {
            StringBuffer buffer = new StringBuffer();
            // 将对象赋值到新的实体中，减少字段的使用
            Object dbE = new Object();
            BeanUtils.copyProperties(dbData, dbE);
            Object newDataE = new Object();
            //拷贝对象
            BeanUtils.copyProperties(newData, newDataE);
            // 获取所有数据库属性
            Field[] dbFields = dbE.getClass().getDeclaredFields();
            //存储key:属性名，value:属性值
            Map<String, String> dbNameAndValueMap = new LinkedHashMap<String, String>();
            //遍历所有属性，生成Map
            for (Field field : dbFields) {
                // 解除私有限定
                field.setAccessible(true);
                dbNameAndValueMap.put(field.getName(), field.get(dbE).toString());
            }
            // 遍历页面新的属性值
            Field[] pageFields = newDataE.getClass().getDeclaredFields();
            for (Field field : pageFields) {
                // 解除私有限定
                field.setAccessible(true);
                if (dbNameAndValueMap.containsKey(field.getName())) {
                    // 判断值是否修改
                    if (!dbNameAndValueMap.get(field.getName()).equals(field.get(newDataE).toString())) {
                        buffer.append("属性【" + field.getName() + "】由【" + dbNameAndValueMap.get(field.getName()) + "】修改为【" + field.get(newDataE).toString() + "】");
                    }
                }
            }
            return buffer;
        } catch (Exception e) {
            return new StringBuffer();
        }
    }

}
