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

import cn.estsh.i3plus.ext.mes.api.base.bu.IBuProcessBomService;
import cn.estsh.i3plus.ext.mes.api.busi.bu.IBuRecordChangeDataService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesProcessBom;
import cn.estsh.i3plus.ext.mes.pojo.model.SxProcessBomModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesProcessBomRepository;
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.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.sqlpack.MesHqlPack;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
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 java.util.ArrayList;
import java.util.List;

/**
 * @Author: xinwang.yi
 * @CreateDate: 2022/09/30 14:19
 * @Description:
 **/
@Service
public class BuProcessBomService implements IBuProcessBomService {

    @Autowired
    private MesProcessBomRepository mesProcessBomRDao;

    @Autowired
    private IBuRecordChangeDataService recordChangeDataService;

    @Override
    public MesProcessBom insertProcessBom(MesProcessBom processBom) {
        ConvertBean.saveOrUpdate(processBom, AuthUtil.getSessionUser().getUserName());
        processBom.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
        MesProcessBom processBomDb;
        processBomDb = mesProcessBomRDao.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.PROCESS_CODE, MesExtConstWords.PART_NO, MesExtConstWords.ITEM_PART_NO, MesExtConstWords.IS_BIND_KEY},
                new Object[]{processBom.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), processBom.getProcessCode(), processBom.getPartNo(), processBom.getItemPartNo(), processBom.getIsBindKey()});
        if(processBomDb != null){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("已存在成品物料【%s】、原材料【%s】、工序【%s】、是否绑定关键件【%s】的记录",
                            processBom.getPartNo(), processBom.getItemPartNo(), processBom.getProcessCode(), MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(processBom.getIsBindKey()))
                    .build();
        }
        if(processBom.getIsBindKey() != null && processBom.getIsBindKey() == MesExtEnumUtil.IS_BIND_KEY.YES.getValue()){
            checkSeqIsScan(processBom);
            processBomDb = mesProcessBomRDao.getByProperty(
                    new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.PROCESS_CODE, MesExtConstWords.PART_NO, MesExtConstWords.IS_BIND_KEY, MesExtConstWords.SEQ},
                    new Object[]{processBom.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), processBom.getProcessCode(), processBom.getPartNo(), processBom.getIsBindKey(), processBom.getSeq()});
            if(processBomDb != null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("已存在成品物料【%s】、工序【%s】、是否绑定关键件【%s】、序号【%s】的记录",
                                processBom.getPartNo(), processBom.getItemPartNo(), processBom.getProcessCode(), MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(processBom.getIsBindKey()), processBom.getSeq())
                        .build();
            }
        }

        return mesProcessBomRDao.insert(processBom);
    }

    @Override
    public MesProcessBom updateProcessBom(MesProcessBom processBom) {
        MesProcessBom processBomDbIsExist;

        processBomDbIsExist = mesProcessBomRDao.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.PROCESS_CODE, MesExtConstWords.PART_NO, MesExtConstWords.ITEM_PART_NO, MesExtConstWords.IS_BIND_KEY},
                new Object[]{processBom.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), processBom.getProcessCode(), processBom.getPartNo(), processBom.getItemPartNo(), processBom.getIsBindKey()});

        if(null != processBomDbIsExist && processBomDbIsExist.getId().compareTo(processBom.getId()) != 0){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("已存在成品物料【%s】、原材料【%s】、工序【%s】、是否绑定关键件【%s】的记录",
                            processBom.getPartNo(), processBom.getItemPartNo(), processBom.getProcessCode(), MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(processBom.getIsBindKey()))
                    .build();
        }

        if(processBom.getIsBindKey() != null && processBom.getIsBindKey() == MesExtEnumUtil.IS_BIND_KEY.YES.getValue()){
            checkSeqIsScan(processBom);

            processBomDbIsExist = mesProcessBomRDao.getByProperty(
                    new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.PROCESS_CODE, MesExtConstWords.PART_NO, MesExtConstWords.IS_BIND_KEY, MesExtConstWords.SEQ},
                    new Object[]{processBom.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), processBom.getProcessCode(), processBom.getPartNo(), processBom.getIsBindKey(), processBom.getSeq()});

            if(null != processBomDbIsExist && processBomDbIsExist.getId().compareTo(processBom.getId()) != 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("已存在成品物料【%s】、工序【%s】、是否绑定关键件【%s】、序号【%s】的记录",
                                processBom.getPartNo(), processBom.getProcessCode(), MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(processBom.getIsBindKey()), processBom.getSeq())
                        .build();
            }
        }

        MesProcessBom processBomDb = mesProcessBomRDao.getById(processBom.getId());
        if(null == processBomDb){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("ID【%s】数据不存在", processBom.getId())
                    .build();
        }

        ConvertBean.serviceModelUpdate(processBomDb, AuthUtil.getSessionUser().getUserName());
        //新增工序BOM字段变更履历
        doRecordChangeData(getModel(processBomDb), getModel(processBom), SxProcessBomModel.class);

        processBomDb.setProcessCode(processBom.getProcessCode());
        processBomDb.setProcessName(processBom.getProcessName());
        processBomDb.setQty(processBom.getQty());
        processBomDb.setIsBindKey(processBom.getIsBindKey());
        processBomDb.setIsCheck(processBom.getIsCheck());
        processBomDb.setIsRepeat(processBom.getIsRepeat());
        processBomDb.setMatchRule(processBom.getMatchRule());
        processBomDb.setSeq(processBom.getSeq());
        processBomDb.setItemPartNo(processBom.getItemPartNo());
        processBomDb.setItemPartName(processBom.getItemPartName());
        return mesProcessBomRDao.save(processBomDb);
    }

    private SxProcessBomModel getModel(MesProcessBom processBom){
        SxProcessBomModel processBomModel = new SxProcessBomModel();
        BeanUtils.copyProperties(processBom, processBomModel);
        processBomModel.setIsBindKeyName(MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(processBomModel.getIsBindKey()));
        processBomModel.setIsCheckName(MesExtEnumUtil.IS_CHECK.valueOfDescription(processBomModel.getIsCheck()));
        processBomModel.setIsDeletedName(CommonEnumUtil.TRUE_OR_FALSE.valueOf(processBomModel.getIsDeleted()));
        processBomModel.setIsValidName(MesExtEnumUtil.IS_VAILD.valueOfDescription(processBomModel.getIsValid()));
        processBomModel.setIsRepeatName(MesExtEnumUtil.IS_REPEAT.valueOfDescription(processBomModel.getIsRepeat()));
        return processBomModel;
    }

    private void doRecordChangeData(SxProcessBomModel sourceData, SxProcessBomModel newData, Class clazz){
        recordChangeDataService.doRecordChangeData(MesExtEnumUtil.FIELD_MENU_TYPE.PROCESS_BOM.getValue(), sourceData, newData, clazz, sourceData.getPartNo(), sourceData.getPartNameRdd(), newData.getItemPartNo(), newData.getItemPartName(), newData.getProcessCode(), newData.getProcessName(), sourceData.getOrganizeCode(), sourceData.getModifyDatetime());
        //List<MesTravelMenuFieldConfig> travelMenuFieldConfigList = travelMenuFieldConfigService.getTravelMenuFieldConfigList(sourceData.getOrganizeCode(), MesExtEnumUtil.FIELD_MENU_TYPE.PROCESS_BOM.getValue());
        //if(!CollectionUtils.isEmpty(travelMenuFieldConfigList)){
        //    List<String> fields = travelMenuFieldConfigList.stream().map(MesTravelMenuFieldConfig::getFieldCode).distinct().collect(Collectors.toList());
        //    Map<String, List<String>> fieldCompareResultMap = BusiExtUtil.checkParamValue(sourceData, newData, clazz, fields);
        //    for (String field : fieldCompareResultMap.keySet()){
        //        List<String> compareResultList = fieldCompareResultMap.get(field);
        //        SxMesDataTravel dataTravel = new SxMesDataTravel();
        //        dataTravel.setMenuCode(MesExtEnumUtil.FIELD_MENU_TYPE.PROCESS_BOM.getValue());
        //        dataTravel.setPartNo(sourceData.getPartNo());
        //        dataTravel.setPartNameRdd(sourceData.getPartNameRdd());
        //        dataTravel.setFieldCode(field);
        //        dataTravel.setBeforeChange(compareResultList.get(0));
        //        dataTravel.setAfterChange(compareResultList.get(1));
        //        ConvertBean.serviceModelInitialize(dataTravel, AuthUtil.getSessionUser().getUserName());
        //        dataTravel.setOrganizeCode(sourceData.getOrganizeCode());
        //        dataTravelRepository.insert(dataTravel);
        //    }
        //}
    }

    private void checkSeqIsScan(MesProcessBom processBom) {
        if (processBom.getSeq() == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("当是否绑定关键件维护为【是】时，需要填写关键件序号")
                    .build();
        }else if(processBom.getSeq() <= 0){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("当是否绑定关键件维护为【是】时，关键件序号需为正整数")
                    .build();
        }
    }

    @Override
    public void updateStatusBatchProcessBom(String[] ids, 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();
        }
        for (String id : ids) {
            if (StringUtils.isEmpty(id)) {
                continue;
            }

            if(status == CommonEnumUtil.IS_VAILD.VAILD.getValue()){
                MesProcessBom processBom = mesProcessBomRDao.getById(Long.parseLong(id));

                MesProcessBom processBomDbIsExist;

                processBomDbIsExist = mesProcessBomRDao.getByProperty(
                        new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.PROCESS_CODE, MesExtConstWords.PART_NO, MesExtConstWords.ITEM_PART_NO, MesExtConstWords.IS_BIND_KEY},
                        new Object[]{processBom.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), processBom.getProcessCode(), processBom.getPartNo(), processBom.getItemPartNo(), processBom.getIsBindKey()});

                if(null != processBomDbIsExist && processBomDbIsExist.getId().compareTo(processBom.getId()) != 0){
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                            .setErrorDetail("已存在成品物料【%s】、原材料【%s】、工序【%s】、是否绑定关键件【%s】的记录",
                                    processBom.getPartNo(), processBom.getItemPartNo(), processBom.getProcessCode(), MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(processBom.getIsBindKey()))
                            .build();
                }

                if(processBom.getIsBindKey() == MesExtEnumUtil.IS_BIND_KEY.YES.getValue() && processBom.getSeqVal() != 0){
                    processBomDbIsExist = mesProcessBomRDao.getByProperty(
                            new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.PROCESS_CODE, MesExtConstWords.PART_NO, MesExtConstWords.IS_BIND_KEY, MesExtConstWords.SEQ},
                            new Object[]{processBom.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), processBom.getProcessCode(), processBom.getPartNo(), processBom.getIsBindKey(), processBom.getSeq()});

                    if(null != processBomDbIsExist && processBomDbIsExist.getId().compareTo(processBom.getId()) != 0){
                        throw ImppExceptionBuilder.newInstance()
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                                .setErrorDetail("已存在成品物料【%s】、工序【%s】、是否绑定关键件【%s】、序号【%s】的记录",
                                        processBom.getPartNo(), processBom.getProcessCode(), MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(processBom.getIsBindKey()), processBom.getSeq())
                                .build();
                    }
                }
            }

            mesProcessBomRDao.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{Long.parseLong(id)},
                    new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                    new Object[]{status, userName, TimeTool.getNowTime(true)});
        }

    }

    @Override
    public ListPager<SxProcessBomModel> queryProcessBomByPager(MesProcessBom processBom, Pager pager) {
        List<SxProcessBomModel> resultList = new ArrayList<>();
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganize().getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(processBom.getIsValid(), MesExtConstWords.IS_VALID, packBean);
        DdlPreparedPack.getStringEqualPack(processBom.getPartNo(), MesExtConstWords.PART_NO, packBean);
        DdlPreparedPack.getStringEqualPack(processBom.getItemPartNo(), MesExtConstWords.ITEM_PART_NO, packBean);
        DdlPreparedPack.getStringLikerPack(processBom.getProcessCode(), MesExtConstWords.PROCESS_CODE, packBean);
        DdlPreparedPack.getNumEqualPack(processBom.getIsBindKey(), MesExtConstWords.IS_BIND_KEY, packBean);
        pager = PagerHelper.getPager(pager, mesProcessBomRDao.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(processBom.orderBy());
        List<MesProcessBom> processBomList = mesProcessBomRDao.findByHqlWherePage(packBean, pager);
        if (!CollectionUtils.isEmpty(processBomList)) {
            for (MesProcessBom item : processBomList) {
                if (null == item) {
                    continue;
                }
                SxProcessBomModel result = new SxProcessBomModel();
                BeanUtils.copyProperties(item, result);
                result.setIsCheckName(
                        (!StringUtils.isEmpty(result.getIsCheck()) && !StringUtils.isEmpty(MesExtEnumUtil.IS_CHECK.valueOfDescription(result.getIsCheck())))
                                ? MesExtEnumUtil.IS_CHECK.valueOfDescription(result.getIsCheck()) : null);
                result.setIsRepeatName(
                        (!StringUtils.isEmpty(result.getIsRepeat()) && !StringUtils.isEmpty(MesExtEnumUtil.IS_REPEAT.valueOfDescription(result.getIsRepeat())))
                                ? MesExtEnumUtil.IS_REPEAT.valueOfDescription(result.getIsRepeat()) : null);
                result.setIsBindKeyName(
                        (!StringUtils.isEmpty(result.getIsBindKey()) && !StringUtils.isEmpty(MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(result.getIsBindKey())))
                                ? MesExtEnumUtil.IS_BIND_KEY.valueOfDescription(result.getIsBindKey()) : null);
                resultList.add(result);
            }
        }
        return new ListPager(resultList, pager);
    }


}
