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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IConsistencyAffirmRecordService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WorkOrderInfoModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.*;
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.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
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.base.tool.HqlPack;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.sqlpack.MesPcnHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/02/07 15:46
 * @Description:
 **/
@Service
public class ConsistencyAffirmRecordService implements IConsistencyAffirmRecordService {

    @Autowired
    private MesConsistencyAffirmRecordRepository consistencyAffirmRecordRepository;
    @Autowired
    private MesConsistencyAffirmPartRepository consistencyAffirmPartRepository;
    @Autowired
    private MesConsistencyAffirmProjectRepository consistencyAffirmProjectRepository;
    @Autowired
    private ISyncFuncService syncFuncService;
    @Autowired
    private MesOrderJobRepository mesOrderJobRDao;
    @Autowired
    private MesWorkCenterExtRepository mesWorkCenterExtRDao;

    @Override
    public void insertConsistencyAffirmRecord(WorkOrderInfoModel workOrderInfoModel) {
        MesConsistencyAffirmPart consistencyAffirmPart = consistencyAffirmPartRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PART_NO},
                new Object[]{workOrderInfoModel.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue(), workOrderInfoModel.getPartNo()});
        if (null != consistencyAffirmPart) {
            if (MathOperation.compareTo(consistencyAffirmPart.getEssences(), new Double(0)) > 0) {
                //是否达到一致性确认物料配置中生成规律的倍数
                if (workOrderInfoModel.getCompleteQty() % consistencyAffirmPart.getEssences() == 0 || MathOperation.compareTo(workOrderInfoModel.getQty(), workOrderInfoModel.getCompleteQty()) == 0) {
                    doCreateConsistencyAffirmRecord(workOrderInfoModel);
                }
            }
        }
    }

    @Override
    public List<MesConsistencyAffirmRecord> queryConsistencyAffirmRecord(String orderNo, String organizeCode) {
        DdlPackBean packBean = MesPcnHqlPack.getAllBaseData(organizeCode);
        DdlPreparedPack.getStringEqualPack(orderNo, MesPcnExtConstWords.ORDER_NO, packBean);
        return consistencyAffirmRecordRepository.findByHqlWhere(packBean);
    }

    @Override
    public void updateConsistencyAffirmRecord(MesConsistencyAffirmRecord consistencyAffirmRecord) {
        MesConsistencyAffirmRecord detailById = consistencyAffirmRecordRepository.getById(consistencyAffirmRecord.getId());
        if (null == detailById) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("该条数据不存在")
                    .build();
        }
        //修改单据主表状态为点检中
        StringBuffer wheres = new StringBuffer();
        HqlPack.getStringEqualPack(consistencyAffirmRecord.getOrderNo(), MesPcnExtConstWords.ORDER_NO, wheres);
        mesOrderJobRDao.updateByHqlWhere(
                wheres.toString(),
                new String[]{MesPcnExtConstWords.ORDER_STATUS, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
                new Object[]{MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue(), consistencyAffirmRecord.getModifyUser(), TimeTool.getNowTime(true)}
        );
        //修改单据明细状态
        /*consistencyAffirmRecord.setCheckTime(TimeTool.getNowTime(true));
        consistencyAffirmRecord.setCheckUser(consistencyAffirmRecord.getModifyUser());
        ConvertBean.serviceModelUpdate(consistencyAffirmRecord, consistencyAffirmRecord.getModifyUser());
        consistencyAffirmRecordRepository.save(consistencyAffirmRecord);*/
        consistencyAffirmRecordRepository.updateByProperties(new String[]{MesPcnExtConstWords.ID}, new Object[]{consistencyAffirmRecord.getId()},
                new String[]{MesPcnExtConstWords.CHECK_RESULT, MesPcnExtConstWords.CHECK_USER, MesPcnExtConstWords.CHECK_TIME, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
                new Object[]{consistencyAffirmRecord.getCheckResult(), consistencyAffirmRecord.getModifyUser(), TimeTool.getNowTime(true), consistencyAffirmRecord.getModifyUser(), TimeTool.getNowTime(true)});

    }

    @Override
    public void updateConsistencyAffirmRecordMemo(MesConsistencyAffirmRecord consistencyAffirmRecord) {
        ConvertBean.saveOrUpdate(consistencyAffirmRecord,consistencyAffirmRecord.getModifyUser());
        consistencyAffirmRecordRepository.save(consistencyAffirmRecord);
    }

    /**
     * 创建一致性确认记录
     * @param workOrderInfoModel
     */
    public Boolean doCreateConsistencyAffirmRecord(WorkOrderInfoModel workOrderInfoModel) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(workOrderInfoModel.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(workOrderInfoModel.getPartNo(), MesPcnExtConstWords.PART_NO, packBean);
        List<MesConsistencyAffirmProject> affirmProjectList = consistencyAffirmProjectRepository.findByHqlWhere(packBean);
        //根据产线获取产线信息
        MesWorkCenterExt mesWorkCenterExt = mesWorkCenterExtRDao.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.WORK_CENTER_CODE},
                new Object[]{workOrderInfoModel.getOrganizeCode(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                        CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), workOrderInfoModel.getWorkCenterCode()});

        //生成单据明细
        if (!CollectionUtils.isEmpty(affirmProjectList)) {
            //生成单据主表
            String orderNo = insertMesOrderJob(workOrderInfoModel, mesWorkCenterExt);
            List<MesConsistencyAffirmRecord> consistencyAffirmRecordList = new ArrayList<>();
            for (MesConsistencyAffirmProject consistencyAffirmProject : affirmProjectList) {
                MesConsistencyAffirmRecord consistencyAffirmRecord = new MesConsistencyAffirmRecord();
                consistencyAffirmRecord.setWorkOrderNo(workOrderInfoModel.getWorkOrderNo());
                consistencyAffirmRecord.setPartNo(workOrderInfoModel.getPartNo());
                consistencyAffirmRecord.setShiftGroupCheck(MesPcnExtEnumUtil.SHIFT_GROUP_CHECK.NO.getValue());
                consistencyAffirmRecord.setQualityCheck(MesPcnExtEnumUtil.QUALITY_CHECK.NO.getValue());
                consistencyAffirmRecord.setPartNameRdd(consistencyAffirmProject.getPartNameRdd());
                consistencyAffirmRecord.setOrderNo(orderNo);
                consistencyAffirmRecord.setOrderTime(TimeTool.getNowTime(true));
                consistencyAffirmRecord.setCompleteQty(workOrderInfoModel.getCompleteQty());
                consistencyAffirmRecord.setItemDescription(consistencyAffirmProject.getItemDescription());
                consistencyAffirmRecord.setCreateUser(workOrderInfoModel.getCreateUser());
                consistencyAffirmRecord.setOrganizeCode(workOrderInfoModel.getOrganizeCode());
                consistencyAffirmRecordList.add(consistencyAffirmRecord);
            }
            consistencyAffirmRecordRepository.saveAll(consistencyAffirmRecordList);
        }
        return true;
    }

    private String insertMesOrderJob(WorkOrderInfoModel workOrderInfoModel, MesWorkCenterExt mesWorkCenterExt) {
        // 调用平台生成条码的方法
        List<String> orderNoList = getOrderNoByRuleCode(1,
                MesPcnExtConstWords.ORDER_NO_RULE, new GenSerialNoModel(), workOrderInfoModel.getCreateUser(), workOrderInfoModel.getOrganizeCode());

        MesOrderJob mesOrderJob = new MesOrderJob();
        mesOrderJob.setOrganizeCode(workOrderInfoModel.getOrganizeCode());
        mesOrderJob.setOrderType(MesPcnExtEnumUtil.MES_OR_ORDER_TYPE.NAMEPLATE_GUARANTEE_CONSISTENCY.getValue());
        mesOrderJob.setTaskType(MesPcnExtEnumUtil.MES_OR_TASK_TYPE.PREPARE_TASK.getValue());
        mesOrderJob.setOrderNo(orderNoList.get(0));
        mesOrderJob.setWorkCenterCode(workOrderInfoModel.getWorkCenterCode());
        mesOrderJob.setGenerateTime(TimeTool.getNowTime(true));
        mesOrderJob.setShiftCode(mesWorkCenterExt.getShiftCode());
        mesOrderJob.setWorkOrderNo(workOrderInfoModel.getWorkOrderNo());
        mesOrderJob.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue());
        mesOrderJob.setWorkTime(mesWorkCenterExt.getWorkTime());
        mesOrderJob.setOrderDate(TimeTool.getToday());

        ConvertBean.serviceModelInitialize(mesOrderJob, workOrderInfoModel.getCreateUser());
        mesOrderJobRDao.insert(mesOrderJob);

        return orderNoList.get(0);

    }

    public List<String> getOrderNoByRuleCode(int number, String ruleCode, GenSerialNoModel genSerialNoModel, String userName, String org) {
        genSerialNoModel.setRuleCode(ruleCode);
        BaseResultBean<String> serialNumberBean = syncFuncService.syncSerialNo(genSerialNoModel, userName, org, Integer.valueOf(number));
        if (serialNumberBean != null && serialNumberBean.isSuccess()) {
            return serialNumberBean.getResultList();
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION.getCode())
                    .setErrorDetail(serialNumberBean == null ? "条码未生成成功" : serialNumberBean.getErrorMsg())
                    .build();
        }
    }
}
