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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IPartExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IProdPackExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnTravelExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesPartExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProdPackExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProduceSnExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
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.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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description : 工步业务-工单绑定条码并校验绑定数是否达标工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("sxWorkOrderBindSnAndCheckCompleteStepService")
public class SxWorkOrderBindSnAndCheckCompleteStepService extends BaseStepService {

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private IProduceSnTravelExtService produceSnTravelExtService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    @Autowired
    private MesProduceSnExtRepository produceSnExtRepository;

    @Autowired
    private IPartExtService partExtService;

    @Autowired
    private IProdPackExtService prodPackExtService;

    private static Lock lock = new ReentrantLock(true);

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        try {
            lock.lock();

            log.info("SxWorkOrderBindSnAndCheckCompleteStepService[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);
                return StepResult.getNonComplete(err);
            }

            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);
                return StepResult.getNonComplete(err);
            }

            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);
                return StepResult.getNonComplete(err);
            }

            MesWorkOrderExt workOrderExt = workOrderExtService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), reqBean.getWorkOrderNo());
            if (null == workOrderExt) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单号[%s]无效"), reqBean.getWorkOrderNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            List<MesProduceSnExt> produceSnExtList = produceSnExtService.getProduceSnExtListByOrderNo(reqBean.getOrganizeCode(), reqBean.getWorkOrderNo());
            if (!CollectionUtils.isEmpty(produceSnExtList) && produceSnExtList.size() == workOrderExt.getQty().intValue()) {
                if (MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.CREATED.getValue() != workOrderExt.getSnCreateStatus()) {
                    workOrderExtService.saveSnCreateStatus(workOrderExt, reqBean.getUserInfo(), MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.CREATED.getValue());
                }
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]条码绑定数量[%s]已达标,操作失败"), reqBean.getWorkOrderNo(), workOrderExt.getQty());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getSuccessComplete();
            }

            MesProduceSnExt produceSnExtDb = produceSnExtService.getProduceSnExtBySn(reqBean.getOrganizeCode(), reqBean.getSerialNumber());
            if (null != produceSnExtDb) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码[%s]已存在数据库,操作失败"), reqBean.getSerialNumber());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            MesPartExt partDb = partExtService.getPartExt(reqBean.getOrganizeCode(), workOrderExt.getPartNo());
            if (null == partDb) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]关联的物料[%s]无效"), reqBean.getWorkOrderNo(), workOrderExt.getPartNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            MesProdPackExt prodPackDb = prodPackExtService.getProdPackExt(reqBean.getOrganizeCode(), partDb.getPartNo(), partDb.getPptCode());

            MesProduceSnExt invalidProduceSnExtDb = produceSnExtService.getInvalidProduceSnExtBySn(reqBean.getOrganizeCode(), reqBean.getSerialNumber());

            MesProduceSnExt produceSnExt = new MesProduceSnExt();

            if(invalidProduceSnExtDb != null){
                produceSnExt.setId(invalidProduceSnExtDb.getId());
            }

            produceSnExt.setSerialNumber(reqBean.getSerialNumber());
            produceSnExt.setProductSn(reqBean.getSerialNumber());
            produceSnExt.setWorkOrderNo(reqBean.getWorkOrderNo());
            produceSnExt.setPartNo(workOrderExt.getPartNo());
            produceSnExt.setPartNameRdd(workOrderExt.getPartNameRdd());
            if (null != prodPackDb) {
                produceSnExt.setProcessLabelTemplate(prodPackDb.getProcessLabelTemplate());
                produceSnExt.setQualityAssureTemplate(prodPackDb.getQualityAssureTemplate());
                produceSnExt.setBigProcessLabelTemplate(prodPackDb.getBigProcessLabelTemplate());
            }
            produceSnExt.setCustCode(workOrderExt.getCustCode());
            produceSnExt.setPrintStatus(MesPcnExtEnumUtil.PRODUCE_SN_PRINT_STATUS.UNPRINT.getValue());
            produceSnExt.setPrintCount(0);
            produceSnExt.setSnStatus(MesPcnExtEnumUtil.PRODUCE_SN_STATUS.CREATE.getValue());
            produceSnExt.setQcStatus(MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.QUALIFIED.getValue());
            if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() != workOrderExt.getWorkOrderType()) {
                produceSnExt.setSnType(workOrderExt.getWorkOrderType());
            } else {
                produceSnExt.setSnType(MesPcnExtEnumUtil.PRODUCE_SN_TYPE.REWORK_SN.getValue());
            }
            produceSnExt.setQty(1d);
            produceSnExt.setOrganizeCode(reqBean.getOrganizeCode());
            ConvertBean.serviceModelInitialize(produceSnExt, reqBean.getUserInfo());
            produceSnExt.setLastWorkOrderNo(reqBean.getWorkOrderNo());
            produceSnExtService.packSnExtProcess(produceSnExt, reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode());
            produceSnExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(produceSnExt).convertBean(produceSnExt);
            produceSnExtRepository.insert(produceSnExt);
            produceSnTravelExtService.insertProduceSnTravelExt(produceSnExt);
            int completeQty = CollectionUtils.isEmpty(produceSnExtList) ? 1 : produceSnExtList.size() + 1;
            if (completeQty == workOrderExt.getQty().intValue()) {
                workOrderExtService.saveSnCreateStatus(workOrderExt, reqBean.getUserInfo(), MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.CREATED.getValue());
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码[%s]绑定工单[%s]成功,工单绑定条码总数量[%s]已达标"), reqBean.getSerialNumber(), reqBean.getWorkOrderNo(), completeQty);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                return StepResult.getSuccessComplete();
            } else {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码[%s]绑定工单[%s]成功,工单已绑定条码总数量[%s]还未达标"), reqBean.getSerialNumber(), reqBean.getWorkOrderNo(), completeQty);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            }

            return StepResult.getNonComplete();
        } finally {
            lock.unlock();
        }
    }

}
