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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IPartExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IPackageExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.base.WorkCenterExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.PackageExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WorkCenterExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WorkOrderExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ep.EpProduceSnExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.SxProductOffLineRepository;
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.actor.shipping.dispatch.IFsmCommonService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
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 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 org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description : 工步业务-EP打包下线报工工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("epSnLineOffReportWorkStepService")
public class EpSnLineOffReportWorkStepService extends BaseStepService {

    @Autowired
    private IPartExtService partExtService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    @Autowired
    private IPackageExtService packageExtService;

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private SxProductOffLineRepository productOffLineRepository;

    @Autowired
    private WorkCenterExtService workCenterExtService;

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("EpSnLineOffReportWorkStepService[execute] 参数：{}", reqBean);

        StationResultBean resultBean = new StationResultBean();
        String err;

        if (StringUtils.isEmpty(reqBean.getOrganizeCode())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工厂代码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (StringUtils.isEmpty(reqBean.getWorkOrderNo())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少生产工单号");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (StringUtils.isEmpty(reqBean.getSerialNumber())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少产品条码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (StringUtils.isEmpty(reqBean.getPackageNo())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少包装条码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        EpProduceSnExtModel snModel = (EpProduceSnExtModel) reqBean.getDataMap().get(MesPcnExtConstWords.PRODUCE_SN);
        if (null == snModel || !snModel.getSerialNumber().equals(reqBean.getSerialNumber())) {
            snModel = getEpProduceSnExtModel(reqBean);
        }
        if (null == snModel) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "条码[%s]无效"), reqBean.getSerialNumber());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        WorkOrderExtModel orderModel = (WorkOrderExtModel) reqBean.getDataMap().get(MesPcnExtConstWords.WORK_ORDER);
        if (null == orderModel) {
            orderModel = getWorkOrderExtModel(reqBean);
        }
        if (null == orderModel) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产工单号[%s]无效"), reqBean.getWorkOrderNo());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        PackageExtModel packModel = (PackageExtModel) reqBean.getDataMap().get(MesPcnExtConstWords.PACK_SN);
        if (null == packModel || !packModel.getPackageNo().equals(reqBean.getPackageNo())) {
            packModel = getPackageExtModel(reqBean);
        }
        if (null == packModel) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]无效"), reqBean.getPackageNo());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        MesPartExt partExt = partExtService.getPartExt(reqBean.getOrganizeCode(), reqBean.getPartNo());

        WorkCenterExtModel centerModel = (WorkCenterExtModel) reqBean.getDataMap().get(MesPcnExtConstWords.WORK_CENTER);
        if (null == centerModel || (StringUtils.isEmpty(centerModel.getShiftCode()) || StringUtils.isEmpty(centerModel.getWorkTime()))) {
            MesWorkCenterExt workCenterExt = workCenterExtService.getWorkCenterExtByWorkCenterCode(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode());
            if (null == workCenterExt) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线代码[%s]无效"), reqBean.getWorkCenterCode());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }
            if (StringUtils.isEmpty(workCenterExt.getShiftCode()) || StringUtils.isEmpty(workCenterExt.getWorkTime())) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线代码[%s]未启动班次"), reqBean.getWorkCenterCode());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }
            centerModel = new WorkCenterExtModel();
            BeanUtils.copyProperties(workCenterExt, centerModel, MesPcnExtConstWords.ID);
        }

        SxProductOffLine productOffLine = new SxProductOffLine();
        productOffLine.setWorkOrderNo(reqBean.getWorkOrderNo());
        productOffLine.setPackageNo(reqBean.getPackageNo());
        productOffLine.setSerialNumber(reqBean.getSerialNumber());
        productOffLine.setPartNo(reqBean.getPartNo());
        productOffLine.setPartName(reqBean.getPartName());
        productOffLine.setQty(new Double(1));
        productOffLine.setLotNo(centerModel.getWorkTime());
        productOffLine.setShiftCode(centerModel.getShiftCode());
        productOffLine.setWorkCenterCode(reqBean.getWorkCenterCode());
        productOffLine.setErpWarehouse(orderModel.getErpWarehouse());
        productOffLine.setPartLotNo(snModel.getPartLotNo());
        productOffLine.setCustomsPartNo(partExt.getCustomsPartNo());

        if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() != orderModel.getWorkOrderType()) {
            productOffLine.setSnType(snModel.getSnType());
        } else {
            productOffLine.setSnType(MesPcnExtEnumUtil.PRODUCE_SN_TYPE.REWORK_SN.getValue());
        }

        if (null != partExt) {
            productOffLine.setUnit(partExt.getUnit());

            Map<String, String> wcpcMap = fsmCommonService.getCachedWorkCellParam(reqBean);
            List<String> trolleyPartNoList =
                    (!CollectionUtils.isEmpty(wcpcMap) && wcpcMap.containsKey(MesPcnExtConstWords.TROLLEY_PARTS) &&
                            !StringUtils.isEmpty(wcpcMap.get(MesPcnExtConstWords.TROLLEY_PARTS)))
                            ? Arrays.asList(wcpcMap.get(MesPcnExtConstWords.TROLLEY_PARTS).split(MesPcnExtConstWords.COMMA)) : null;
            if (CollectionUtils.isEmpty(trolleyPartNoList) || !trolleyPartNoList.contains(partExt.getPartNo())) {
                productOffLine.setProdType(getProdType(partExt.getCategoryCode1()));
            } else {
                //与wms约定99代表台车
                productOffLine.setProdType(99);
            }
        }
        productOffLine.setSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        productOffLine.setOrganizeCode(reqBean.getOrganizeCode());
        ConvertBean.serviceModelInitialize(productOffLine, reqBean.getUserInfo());
        productOffLineRepository.insert(productOffLine);

        if (reqBean.getDataMap().containsKey(MesPcnExtConstWords.INFO)) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码[%s]关联包装条码[%s]已报工!【%s】"),
                    reqBean.getSerialNumber(), reqBean.getPackageNo(), reqBean.getDataMap().get(MesPcnExtConstWords.INFO));
            if (reqBean.getDataMap().containsKey(MesPcnExtConstWords.ERROR)) {
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                reqBean.getDataMap().remove(MesPcnExtConstWords.ERROR);
            } else {
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            }
        } else {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码[%s]关联包装条码[%s]已报工"),
                    reqBean.getSerialNumber(), reqBean.getPackageNo());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        }

        if (MathOperation.compareTo(orderModel.getCompleteQty(), orderModel.getQty()) == 0) {
            this.sendMessage(reqBean, resultBean, "", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            return StepResult.getSuccessComplete();
        } else {
            return StepResult.getNonComplete();
        }
    }

    private Integer getProdType(String categoryCode1) {
        if (StringUtils.isEmpty(categoryCode1)) {
            return null;
        } else {
            try {
                return Integer.valueOf(categoryCode1);
            } catch (NumberFormatException e) {
                return null;
            }
        }
    }

    private WorkOrderExtModel getWorkOrderExtModel(StationRequestBean reqBean) {
        WorkOrderExtModel orderModel = null;
        MesWorkOrderExt workOrderExt = workOrderExtService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), reqBean.getWorkOrderNo());
        if (null != workOrderExt) {
            orderModel = new WorkOrderExtModel();
            BeanUtils.copyProperties(workOrderExt, orderModel, MesPcnExtConstWords.ID);
        }
        return orderModel;
    }

    private EpProduceSnExtModel getEpProduceSnExtModel(StationRequestBean reqBean) {
        EpProduceSnExtModel snModel = null;
        MesProduceSnExt produceSnExt = produceSnExtService.getProduceSnExtBySn(reqBean.getOrganizeCode(), reqBean.getSerialNumber());
        if (null != produceSnExt) {
            snModel = new EpProduceSnExtModel();
            BeanUtils.copyProperties(produceSnExt, snModel, MesPcnExtConstWords.ID);
        }
        return snModel;
    }

    private PackageExtModel getPackageExtModel(StationRequestBean reqBean) {
        PackageExtModel packModel = null;
        MesPackageExt pack = packageExtService.getPackageByPackNo(reqBean.getOrganizeCode(), reqBean.getPackageNo());
        if (null != pack) {
            packModel = new PackageExtModel();
            BeanUtils.copyProperties(pack, packModel, MesPcnExtConstWords.ID);
        }
        return packModel;
    }

}
