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

import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxPcnHttpService;
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.pojo.bean.MesPackageExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnRepair;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ProduceSnExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesPackageExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProduceSnExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProduceSnRepairRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.ConvertBeanExt;
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.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.mes.pcn.util.PcnHttpUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPackageDetail;
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.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description : 工步业务-BU本体返工绑定条码工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("sxBuNoumenonRepairBindSnStepService")
public class SxBuNoumenonRepairBindSnStepService extends BaseStepService {

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private MesProduceSnExtRepository produceSnExtRepository;

    @Autowired
    private MesProduceSnRepairRepository produceSnRepairRepository;

    @Autowired
    private IPackageExtService packageExtService;

    @Autowired
    private MesPackageExtRepository packageExtRepository;

    @Autowired
    private ISxPcnHttpService pcnHttpService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("sxBuNoumenonRepairBindSnStepService[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);
        }

        MesProduceSnExt produceSnExt = produceSnExtService.getProduceSnExtBySn(reqBean.getOrganizeCode(), reqBean.getSerialNumber());
        if (null == produceSnExt) {
            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);
        }

        String lastWorkOrder = produceSnExt.getLastWorkOrderNo();
        //获取上一个返工条码
        //MesProduceSnRepair lastProduceSnRepairDb = produceSnRepairRepository.getByProperty(
        //        new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.SERIAL_NUMBER, MesPcnExtConstWords.WORK_ORDER_NO},
        //        new Object[]{reqBean.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), reqBean.getSerialNumber(), lastWorkOrder});


        MesProduceSnRepair produceSnRepair = new MesProduceSnRepair();
        produceSnRepair.setSerialNumber(reqBean.getSerialNumber());
        produceSnRepair.setProductSn(reqBean.getProductSn());
        produceSnRepair.setPartNo(produceSnExt.getPartNo());
        produceSnRepair.setPartNameRdd(produceSnExt.getPartNameRdd());
        produceSnRepair.setWorkCenterCode(reqBean.getWorkCenterCode());
        produceSnRepair.setWorkCellCode(reqBean.getWorkCellCode());
        produceSnRepair.setWorkOrderNo(reqBean.getWorkOrderNo());
        produceSnRepair.setInitWorkOrderNo(produceSnExt.getLastWorkOrderNo());
        produceSnRepair.setSnType(MesPcnExtEnumUtil.PRODUCE_SN_TYPE.REWORK_SN.getValue());
        produceSnRepair.setOrganizeCode(reqBean.getOrganizeCode());
        ConvertBean.serviceModelInitialize(produceSnRepair, reqBean.getUserInfo());
        produceSnRepair.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        produceSnRepairRepository.insert(produceSnRepair);

        produceSnExt.setSnStatus(MesPcnExtEnumUtil.PRODUCE_SN_STATUS.REPAIR.getValue());
        produceSnExt.setLastWorkOrderNo(reqBean.getWorkOrderNo());
        produceSnExtService.packSnExtProcess(produceSnExt, reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode());
        ConvertBean.serviceModelUpdate(produceSnExt, reqBean.getUserInfo());
        produceSnExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        new ConvertBeanExt(produceSnExt).convertBean(produceSnExt);
        produceSnExtRepository.save(produceSnExt);

        MesPackageDetail packageDetail = packageExtService.getPackageDetailBySn(reqBean.getOrganizeCode(), reqBean.getSerialNumber());
        if (null != packageDetail) {
            MesPackageExt packageExt = packageExtService.getPackageByPackNo(reqBean.getOrganizeCode(), packageDetail.getPackageNo());
            if (null != packageExt) {
                packageExt.setLastWorkOrderNo(reqBean.getWorkOrderNo());
                ConvertBean.serviceModelUpdate(packageExt, reqBean.getUserInfo());
                packageExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                new ConvertBeanExt(packageExt).convertBean(packageExt);
                packageExtRepository.save(packageExt);
            }
        }

        log.info("返工绑定条码 --- 解绑返工范围 --- 工单号:{},返工工单号:{},包装条码:{},工厂代码:{},用户名:{}", lastWorkOrder, reqBean.getWorkOrderNo(), packageDetail.getPackageNo(), reqBean.getOrganizeCode(), reqBean.getUserInfo());

        // 更新返工范围信息
        Map<String, String> params = new HashMap<>();
        params.put(MesPcnExtConstWords.WORK_ORDER_NO, lastWorkOrder);
        params.put(MesPcnExtConstWords.REWORK_ORDER_NO, reqBean.getWorkOrderNo());
        params.put(MesPcnExtConstWords.PACKAGENO, packageDetail.getPackageNo());
        params.put(MesPcnExtConstWords.ORGANIZE_CODE, reqBean.getOrganizeCode());
        params.put(MesPcnExtConstWords.USER_NAME, reqBean.getUserInfo());
        String requestUrl = pcnHttpService.getRequestUrl(reqBean.getOrganizeCode(), MesPcnExtConstWords.UPDATE_REWORK_RANGE_ORDER_NO_URL);
        String data = PcnHttpUtil.doPost(requestUrl, params);
        BaseResultBean baseResultBean = null;
        if (!StringUtils.isEmpty(data)) {
            baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
        } else {
            log.error("返工条码 修改返工范围数据 HTTP[{}]调用主接口失败", requestUrl);
        }
        if (null == baseResultBean || !baseResultBean.success) {
            log.error("返工条码 修改返工范围数据 HTTP[{}]调用主接口失败", requestUrl);
        }

        ProduceSnExtModel snModel = new ProduceSnExtModel();
        BeanUtils.copyProperties(produceSnExt, snModel, MesPcnExtConstWords.ID);
        snModel.setWorkCenterCode(reqBean.getWorkCenterCode());
        snModel.setWorkCellCode(reqBean.getWorkCellCode());
        reqBean.getDataMap().put(MesPcnExtConstWords.PRODUCE_SN, snModel);

        return StepResult.getSuccessComplete();
    }

}
