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

import cn.estsh.i3plus.ext.mes.pcn.api.base.ICheckErrorLogService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IWorkOrderStartService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesCheckErrorLog;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWeigh;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWeighManager;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWeighManagerRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWeighRepository;
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.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.util.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author yumingxing
 * @version 1.0
 * @date 2021/2/19 16:06
 **/
@Slf4j
@Service
public class WeighCheckService implements IWorkOrderStartService {

    @Autowired
    private ICheckErrorLogService checkErrorLogService;

    @Autowired
    private MesWeighRepository weighRepository;

    @Autowired
    private MesWeighManagerRepository weighManagerRepository;

    @Autowired
    private ISyncFuncService syncFuncService;

    /**
     * 工单启动后方法执行
     *
     * @param workOrderExt 工单
     * @return {@link ResultBean}
     */
    @Override
    public void doGenCheckOrder(MesWorkOrderExt workOrderExt, String userInfo) {
        MesCheckErrorLog checkErrorLog = new MesCheckErrorLog();
        checkErrorLog.setGenerationMethod(MesPcnExtEnumUtil.GENERATION_METHOD.FROM_WORK_ORDER_START.getValue());
        checkErrorLog.setGeneratingModule(MesPcnExtEnumUtil.MES_OR_ORDER_TYPE.WEIGHING_MANAGEMENT_TABLE.getDescription());

        String msg;
        try {
            String partNo = workOrderExt.getPartNo();
            String workCenterCode = workOrderExt.getWorkCenterCode();
            String partNameRdd = workOrderExt.getPartNameRdd();
            String orderNo = workOrderExt.getOrderNo();
            String organizeCode = workOrderExt.getOrganizeCode();

            MesWeigh weigh = weighRepository.getByProperty(
                    new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PART_NO},
                    new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), partNo});

            DdlPackBean forWeigh = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(orderNo, MesPcnExtConstWords.ORDER_NO, forWeigh);
            List<MesWeighManager> weighManagers = weighManagerRepository.findByHqlWhere(forWeigh);
            if (!CollectionUtils.isEmpty(weighManagers)) {
                msg = String.format("称重点检生成单据:工单[%s]已经生成过失败事例点检单", workOrderExt.getOrderNo());
                log.info(msg);
                checkErrorLogService.insertCheckErrorLog(checkErrorLog, msg, userInfo);
                return;
            }
            List<String> orderNoList = getOrderNoByRuleCode(1,
                    MesPcnExtEnumUtil.COMMON_SN.CZ_NO.getCode(), new GenSerialNoModel(), userInfo, workOrderExt.getOrganizeCode());
            if (CollectionUtils.isEmpty(orderNoList)) {
                msg = String.format("称重点检生成单据:工单[%s]单据编号未生成成功", workOrderExt.getOrderNo());
                log.info(msg);
                checkErrorLogService.insertCheckErrorLog(checkErrorLog, msg, userInfo);
                return;
            }

            MesWeighManager mesWeighManager = new MesWeighManager();
            mesWeighManager.setOrderNo(orderNo);
            mesWeighManager.setOrderJobNo(orderNoList.get(0));
            mesWeighManager.setPartNo(partNo);
            mesWeighManager.setPartName(partNameRdd);
            mesWeighManager.setFinishWeighNum(new Double(0));
            mesWeighManager.setAvgWeight(new Double(0));
            mesWeighManager.setCartonConfirmCheck(MesPcnExtEnumUtil.CONFIRM_TYPE.NO.getValue());
            mesWeighManager.setIsQualityConfirm(MesPcnExtEnumUtil.QUALITY_CHECK.NO.getValue());
            mesWeighManager.setIsTeamConfirm(MesPcnExtEnumUtil.SHIFT_GROUP_CHECK.NO.getValue());
            mesWeighManager.setRealDownLimit(new Double(0));
            mesWeighManager.setRealUpLimit(new Double(0));
            mesWeighManager.setStandardWeight(weigh.getStandardWeight());
            mesWeighManager.setWeighNum(weigh.getWeighNum());
            mesWeighManager.setUpLimit(weigh.getUpLimit());
            mesWeighManager.setDownLimit(weigh.getDownLimit());
            mesWeighManager.setOrganizeCode(organizeCode);
            mesWeighManager.setWorkCenterCode(workCenterCode);
            ConvertBean.serviceModelInitialize(mesWeighManager, AuthUtil.getSessionUser().getUserName());
            weighManagerRepository.insert(mesWeighManager);
        } catch (Exception e) {
            checkErrorLogService.insertCheckErrorLog(checkErrorLog, e.getMessage(), userInfo);
            log.info(e.getMessage());
        }
    }

    private List<String> getOrderNoByRuleCode(int number, String ruleCode, GenSerialNoModel genSerialNoModel, String userName, String org) {
        genSerialNoModel.setRuleCode(ruleCode);
        BaseResultBean<String> serialNumberBean;
        try {
            serialNumberBean = syncFuncService.syncSerialNo(genSerialNoModel, userName, org, Integer.valueOf(number));
        } catch (Exception e) {
            return null;
        }
        if (serialNumberBean != null && serialNumberBean.isSuccess()) {
            return serialNumberBean.getResultList();
        } else {
            return null;
        }
    }
}
