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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionDispatchContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionProcessContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionPartContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionProcessContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.StringUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
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.MesWorkOrderRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description : 保存加工单信息工步 【排序】
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2024/6/11 18:50
 * @Modify:
 **/
@Slf4j
@Service("mesWorkOrderSaveSortStepService")
public class MesWorkOrderSaveSortStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesWorkOrderExtService workOrderExtService;

    @Autowired
    private MesWorkOrderRepository workOrderRepository;

    @Autowired
    private EntityManager entityManager;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

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

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

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

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

        //没有产出零件或者没有工单
        if (CollectionUtils.isEmpty(productionPartContextList) || StringUtils.isEmpty(
                productionPartContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getForeignKey()))).findFirst().get().getWorkOrderNo())) return stepResult;

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

        //保存生产工单数据
        doHandleWorkOrderData(reqBean, resultBean, productionPartContextList, workCell);

        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), stepResult, "保存加工单信息成功!");

    }

    private void doHandleWorkOrderData(StationRequestBean reqBean, StationResultBean resultBean, List<MesProductionPartContext> productionPartContextList, MesWorkCell workCell) {

        //获取上下文加工结果
        String productResult = productionDispatchContextStepService.getProductResultContext(reqBean);

        Map<String, Object> propertyMap;

        for (MesProductionPartContext productionPartContext : productionPartContextList) {

            if (null == productionPartContext || StringUtils.isEmpty(productionPartContext.getForeignKey())) continue;

            //判断是否末道工位
            Boolean isEndWorkCell = (!StringUtils.isEmpty(workCell.getIsEndWorkCell()) && workCell.getIsEndWorkCell().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0) ? true : false;

            propertyMap = new HashMap<>();

            //质量非合格
            if (!StringUtils.isEmpty(productResult) && !productResult.equals(MesExtEnumUtil.PRODUCE_QC_STATUS.QUALIFIED.getValue() + MesPcnExtConstWords.EMPTY)) {
                propertyMap.put(MesPcnExtConstWords.QC_STATUS, Integer.valueOf(productResult));
            }

            //加工中
            if (!isEndWorkCell && productionPartContext.getWorkOrderStatus().compareTo(MesExtEnumUtil.ORDER_STATUS.PROCESS.getValue()) < 0) {
                propertyMap.put(MesPcnExtConstWords.WORK_ORDER_STATUS, MesExtEnumUtil.ORDER_STATUS.PROCESS.getValue());
                propertyMap.put(MesPcnExtConstWords.START_TIME, productionPartContext.getOnlineTime());
                propertyMap.put(MesPcnExtConstWords.ONLINE_TIME, productionPartContext.getOnlineTime());
            }

            //末工位
            if (isEndWorkCell && productionPartContext.getWorkOrderStatus().compareTo(MesExtEnumUtil.ORDER_STATUS.PROCESS.getValue()) <= 0) {
                productionPartContext.setOfflineTime(TimeTool.getNowTime(true));
                propertyMap.put(MesPcnExtConstWords.WORK_ORDER_STATUS, MesExtEnumUtil.ORDER_STATUS.COMPLETE.getValue());
                propertyMap.put(MesPcnExtConstWords.START_TIME, productionPartContext.getOnlineTime());
                propertyMap.put(MesPcnExtConstWords.ONLINE_TIME, productionPartContext.getOnlineTime());
                propertyMap.put(MesPcnExtConstWords.END_TIME, productionPartContext.getOfflineTime());
                propertyMap.put(MesPcnExtConstWords.OFFLINE_TIME, productionPartContext.getOfflineTime());
                propertyMap.put(MesPcnExtConstWords.COMPLETE_QTY, new Double(1));
                propertyMap.put(MesPcnExtConstWords.UN_COMPLETE_QTY, new Double(0));
            }

            //当存在修改字段的情况下进行修改工单信息
            if (!CollectionUtils.isEmpty(propertyMap) && propertyMap.size() > 0) {
                propertyMap.put(MesPcnExtConstWords.MODIFY_USER, reqBean.getUserInfo());
                propertyMap.put(MesPcnExtConstWords.MODIFY_DATE_TIME, (new SimpleDateFormat(MesPcnExtConstWords.DATE_FORMAT_SSS)).format(new Date()));
                propertyMap.put(MesPcnExtConstWords.SYSTEM_SYNC_STATUS, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                propertyMap.put(MesPcnExtConstWords.SYSTEM_SYNC_DATE_TIME, MesPcnExtConstWords.EMPTY);

                String[] propertyName = new String[propertyMap.size()];
                Object[] propertyValue = new Object[propertyMap.size()];

                Integer index = 0;
                for (Map.Entry<String, Object> innerEntry : propertyMap.entrySet()) {
                    if (null == innerEntry) continue;
                    propertyName[index] = innerEntry.getKey();
                    propertyValue[index] = innerEntry.getValue();
                    index ++;
                }

                workOrderRepository.updateByPropertiesNoSync(new String[]{MesPcnExtConstWords.ID, MesPcnExtConstWords.ORGANIZE_CODE}, new Object[]{productionPartContext.getId(), reqBean.getOrganizeCode()}, propertyName, propertyValue);

                log.info("工厂{}生产线{}工位{}:FSM STATE DISPATCHER --- DO STEP --- {} EXEC --- ORDER:{} --- UPDATE:{}",
                        reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(),
                        StringUtil.toLowerCaseFirst(this.getClass().getSimpleName()), productionPartContext.getWorkOrderNo(), JSONObject.toJSONString(propertyMap));

            }

        }
    }

}
