package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.step;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.actor.shipping.dispatch.IFsmRouteDataService;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
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.*;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkOrderCutRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description : 保存加工结果工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesWorkOrderCutWorkOrderSaveStepService")
public class MesWorkOrderCutWorkOrderSaveStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private MesWorkOrderCutRepository workOrderCutRepository;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private IFsmRouteDataService fsmRouteDataService;

    @Autowired
    private IMesWorkOrderExtService workOrderExtService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        //获取上下文信息
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.dispatchCurCellEquipment(reqBean);

        //配置错误 抛出异常
        if (!productionProcessContext.getSuccess()) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), productionProcessContext.getMessage());

        //存储生产过程上下文对象
        productionProcessContextStepService.dispatchProductionProcessContext(reqBean, productionProcessContext);

        //获取上下文产出零件数据信息集合
        List<MesProductionPartContext> productionPartContextList = productionDispatchContextStepService.getProductionPartContext(reqBean);

        String cutWorkOrderNo = productionPartContextList.get(0).getCutWorkOrderNo();

        //从上下文中取出工位对象
        MesWorkCell workCell = productionProcessContext.getWorkCell();

        // 为最后一个工位则将工单更新为完成 并 新增裁片工单包装条码
        if (workCell.getIsEndWorkCell() != null && workCell.getIsEndWorkCell() ==  CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) {

            updateWorkOrderCutStatus(reqBean, cutWorkOrderNo, MesExtEnumUtil.CUT_ORDER_STATUS.COMPLETE.getValue());

            for (MesProductionPartContext mesProductionPartContext : productionPartContextList) {
                MesWorkOrder workOrder = workOrderExtService.getWorkOrder(reqBean.getOrganizeCode(), mesProductionPartContext.getWorkOrderNo());
                workOrder.setCompleteQty(MathOperation.add(workOrder.getCompleteQty(), mesProductionPartContext.getCutQty()));
                if (MathOperation.compareTo(workOrder.getCompleteQty(), workOrder.getQty()) >= 0 && workOrder.getWorkOrderStatus().compareTo(MesExtEnumUtil.ORDER_STATUS.COMPLETE.getValue()) != 0)
                    workOrder.setWorkOrderStatus(MesExtEnumUtil.ORDER_STATUS.COMPLETE.getValue());
                else
                    workOrder.setWorkOrderStatus(MesExtEnumUtil.ORDER_STATUS.PROCESS.getValue());
                ConvertBean.serviceModelUpdate(workOrder, reqBean.getUserInfo());
                workOrder.setModifyDatetime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format(new Date()));
                workOrderExtService.update(workOrder);
            }

        } else {

            updateWorkOrderCutStatus(reqBean, cutWorkOrderNo, MesExtEnumUtil.CUT_ORDER_STATUS.PROCESS.getValue());

        }

        return stepSuccessCompleteAndSendMsgReturn(reqBean, new StationResultBean().writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), "保存裁片工单成功!");

    }

    private void updateWorkOrderCutStatus(StationRequestBean reqBean, String cutWorkOrderNo, Integer status) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(cutWorkOrderNo, MesPcnExtConstWords.CUT_WORK_ORDER_NO, packBean);
        workOrderCutRepository.updateByProperties(new String[]{MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME, MesPcnExtConstWords.WORK_ORDER_STATUS},
                new Object[]{reqBean.getUserInfo(), TimeTool.getNowTime(true), status},
                packBean);
    }

    private String doGenerateSerialNo(StationRequestBean reqBean, StationResultBean resultBean, String ruleCode, MesPart part) {
        try {
            return syncFuncService.syncSerialNo(
                    new GenSerialNoModel(ruleCode).prodLocation(reqBean.getWorkCenterCode()).partNo(part.getPartNo()).putDataMap(MesPart.class.getSimpleName(), part).organizeCode(reqBean.getOrganizeCode()),
                    reqBean.getUserInfo(), reqBean.getOrganizeCode(), 1).getResultList().get(0).toString();
        } catch (ImppBusiException e) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), e.getErrorDetail());
        } catch (Exception e) {
            String webMsg = String.format("零件编码[%s]编码规则代码[%s]生成零件条码%s", part.getPartNo(), ruleCode, fsmRouteDataService.handleFsmCfgOrDefault(reqBean, MesPcnEnumUtil.FSM_CFG.FSM_EXCEPTION_MSG.getCode()));
            this.sendMessage(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.ERROR.getValue()), webMsg, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            this.cacheException(reqBean, reqBean.getStepName(), webMsg, e, true);
            foundExThrowNoShowMsg();
        }
        return null;
    }

}
