package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.bu;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnRepairService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu.IOuterPackageSnService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu3.ISxEsopCenterRemainCfgService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesOuterPackageDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnRepair;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu.RepairOuterPackageModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkOrderExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseModuleService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.mes.pcn.util.PojoAttrUtil;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesStateMachineStatus;
import cn.estsh.i3plus.pojo.mes.model.AttrBean;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description : 展示组件：新返工工位
 * @Reference :
 * @Author :steven.peng
 * @CreateDate : 2023-01-25
 * @Modify:
 **/
@Slf4j
@Service("sxOuterPackageRepairModuleService")
public class SxOuterPackageRepairModuleService extends BaseModuleService {

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

    @Autowired
    private IProduceSnRepairService produceSnRepairService;

    @Autowired
    private IOuterPackageSnService iOuterPackageSnService;

    @Autowired
    private ISxEsopCenterRemainCfgService esopCenterRemainCfgService;

    @Override
    public void init(StationRequestBean reqBean) {
        StationResultBean resultBean = new StationResultBean();
        String err;

        resultBean.setBusiType(MesPcnEnumUtil.STATION_BUSI_TYPE.MODULE_CONTENT.getValue());
        resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.CUSTOM.getValue());
        resultBean.setCustomPageName(MesPcnExtConstWords.NOUMENON_REPAIR_MODULE);
        resultBean.setDataAttrList(packDataAttrList(reqBean));
        resultBean.setSpecialDisplayData(getStepColIndent(reqBean));

        List<MesWorkOrderExt> workOrderExtList = getWorkOrderExtList(reqBean);
        if (!CollectionUtils.isEmpty(workOrderExtList)) {
            for (MesWorkOrderExt workOrderExt : workOrderExtList) {
                if (null == workOrderExt) {
                    continue;
                }
                if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() != workOrderExt.getWorkOrderType()) {
                    continue;
                }
                if (MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.CREATED.getValue() == workOrderExt.getSnCreateStatus()) {
                    continue;
                }
                List<MesProduceSnRepair> produceSnRepairList = produceSnRepairService.getProduceSnRepairListByOrderNo(reqBean.getOrganizeCode(), workOrderExt.getOrderNo());
                if (!CollectionUtils.isEmpty(produceSnRepairList) && produceSnRepairList.size() == workOrderExt.getQty().intValue()) {
                    continue;
                }

                if (!CollectionUtils.isEmpty(produceSnRepairList)) {
                    produceSnRepairList = produceSnRepairList.stream().sorted(Comparator.comparing(MesProduceSnRepair::getCreateDatetime).reversed()).collect(Collectors.toList());
                }

                esopCenterRemainCfgService.doCachedOrderByEsopCenterRemainCfg(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), workOrderExt);
                reqBean.setWorkOrderNo(workOrderExt.getOrderNo());
                List<MesOuterPackageDetail> mesOuterPackageDetails = iOuterPackageSnService.getOuterPackageDetailListByWorkOrderNo(reqBean.getOrganizeCode(),reqBean.getWorkOrderNo());
                if(CollectionUtils.isEmpty(mesOuterPackageDetails)){
                    resultBean.setResultMap(packResultMap(workOrderExt, 0));
                    reqBean.setWorkOrderNo(workOrderExt.getOrderNo());
                    this.sendMessage(reqBean, resultBean);
                    return;
                } else {
                    List<RepairOuterPackageModel> repairOuterPackageModelList = new ArrayList<>();
                    for (MesOuterPackageDetail ms : mesOuterPackageDetails) {
                        MesProduceSnRepair mesProduceSnRepair = produceSnRepairService.getProduceSnRepairBySnAndOrderNo(reqBean.getOrganizeCode(), ms.getSerialNumber(), ms.getWorkOrderNo());
                        RepairOuterPackageModel repairOuterPackageModel = new RepairOuterPackageModel();
                        BeanUtils.copyProperties(ms, repairOuterPackageModel, MesPcnExtConstWords.ID);
                        repairOuterPackageModel.setInitWorkOrderNo(mesProduceSnRepair.getInitWorkOrderNo());
                        repairOuterPackageModelList.add(repairOuterPackageModel);
                    }

                    if (!CollectionUtils.isEmpty(repairOuterPackageModelList)) {

                        resultBean.setResultList(repairOuterPackageModelList);
                        resultBean.setResultMap(packResultMap(workOrderExt, CollectionUtils.isEmpty(repairOuterPackageModelList) ? 0 : repairOuterPackageModelList.size()));
                        //reqBean.setWorkOrderNo(workOrderExt.getOrderNo());
                        this.sendMessage(reqBean, resultBean);
                        return;

                    }
                }
/*              resultBean.setResultList(produceSnRepairList);
                resultBean.setResultMap(packResultMap(workOrderExt, CollectionUtils.isEmpty(produceSnRepairList) ? 0 : produceSnRepairList.size()));
                reqBean.setWorkOrderNo(workOrderExt.getOrderNo());

                this.sendMessage(reqBean, resultBean);
                return;*/
            }
        }
        this.sendMessage(reqBean, resultBean);
        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]暂无可解绑条码的启动状态的返工工单"), reqBean.getWorkCenterCode());
        this.sendMessage(reqBean,  resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        throw ImppExceptionBuilder.newInstance()
                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION.getCode())
                .setErrorDetail("生产线[%s]暂无可解绑条码的启动状态的返工工单", reqBean.getWorkCenterCode())
                .build();
    }

    private Map<String, Object> packResultMap(MesWorkOrderExt workOrderExt, int amount) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put(MesPcnExtConstWords.WORK_ORDER_NO, workOrderExt.getOrderNo());
        resultMap.put(MesPcnExtConstWords.PART_NO, workOrderExt.getPartNo());
        resultMap.put(MesPcnExtConstWords.PART_NAME, workOrderExt.getPartNameRdd());
        resultMap.put(MesPcnExtConstWords.COMPLETE_QTY, amount);
        resultMap.put(MesPcnExtConstWords.QTY, workOrderExt.getQty());
        return resultMap;
    }


    private List<MesWorkOrderExt> getWorkOrderExtList(StationRequestBean reqBean) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(reqBean.getWorkCenterCode(), MesPcnExtConstWords.WORK_CENTER_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(reqBean.getAreaCode(), MesPcnExtConstWords.AREA_CODE, packBean);
        DdlPreparedPack.getNumEqualPack(MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue(), MesPcnExtConstWords.WORK_ORDER_STATUS, packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{MesPcnExtConstWords.SEQ}, packBean);
        return workOrderExtRepository.findByHqlWhere(packBean);
    }

    private List<AttrBean> packDataAttrList(StationRequestBean reqBean) {
        List<AttrBean> attrBeanList = new ArrayList<>();
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.OUTER_PACKAGE_NO, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "大包装条码"));
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.INNER_PACKAGE_NO, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "小包装条码"));
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.INIT_WORK_ORDER_NO, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "初始工单号"));
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.CREATE_DATE_TIME, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "绑定时间"));
        return attrBeanList;
    }

    @Override
    public boolean execute(StationRequestBean reqBean) {
        return true;
    }

    @Override
    public boolean execStateModule(StationRequestBean reqBean, List<MesStateMachineStatus> states, Map<String, String> wcpcMap) {
        init(reqBean);
        return true;
    }

}
