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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IWorkCenterExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.ep.IEpQualityDecisionService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnRepairService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.RepairRequestModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesBadCellDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesBadCellRepository;
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.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
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.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesProcess;
import cn.estsh.i3plus.pojo.mes.repository.MesProcessRepository;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
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.List;

/**
 * @Author: Wynne.Lu
 * @CreateDate: 2019/8/30 1:39 PM
 * @Description:
 **/
@Service
public class EpQualityDecisionService implements IEpQualityDecisionService {

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private IProduceSnRepairService produceSnRepairService;

    @Autowired
    private MesProduceSnExtRepository produceSnExtRepository;

    @Autowired
    private MesBadCellRepository badCellRepository;

    @Autowired
    private MesBadCellDetailRepository mesBadCellDetailRDao;

    @Autowired
    private MesProcessRepository mesProcessRDao;

    @Autowired
    private IWorkCenterExtService workCenterExtService;

    @Override
    public void insertMesBadCellAndDetail(RepairRequestModel repairRequestModel) {
        List<MesBadCellDetail> badCellDetailList = repairRequestModel.getMesDefectRecordList();
        if (CollectionUtils.isEmpty(badCellDetailList)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("入参缺少不良明细数据")
                    .build();
        }

        badCellDetailList.stream().forEach(mesBadCellDetail -> {
            if(StringUtils.isEmpty(mesBadCellDetail.getItemPartName()) || StringUtils.isEmpty(mesBadCellDetail.getItemPartNo()) || StringUtils.isEmpty(mesBadCellDetail.getHappenStation())){
                throwImppException(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(),"原材料物料号,原材料物料名称,发生岗位参数不全");
            }
        });

        String workOrderNo;
        MesProduceSnExt produceSnExt = produceSnExtService.getProduceSnExtBySn(repairRequestModel.getOrganizeCode(), repairRequestModel.getSerialNumber());
        if (null == produceSnExt) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("产品条码[%s]不存在", repairRequestModel.getSerialNumber())
                    .build();
        }

        if (!StringUtils.isEmpty(produceSnExt.getLastWorkOrderNo()) && !produceSnExt.getLastWorkOrderNo().equals(produceSnExt.getWorkOrderNo())) {
            MesProduceSnRepair produceSnRepair = produceSnRepairService.getProduceSnRepairBySn(repairRequestModel.getOrganizeCode(), repairRequestModel.getSerialNumber());
            if (null == produceSnRepair) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("产品条码[%s]与返工工单[%s]的关联关系不存在", repairRequestModel.getSerialNumber(), produceSnExt.getLastWorkOrderNo())
                        .build();
            }
            workOrderNo = produceSnRepair.getWorkOrderNo();
        } else {
            workOrderNo = produceSnExt.getWorkOrderNo();
        }

        MesWorkCenterExt workCenterExt = workCenterExtService.getWorkCenterExtByWorkCenterCode(repairRequestModel.getOrganizeCode(), repairRequestModel.getWorkCenterCode());
        if (null == workCenterExt) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("生产线代码[%s]无效", repairRequestModel.getWorkCenterCode())
                    .build();
        }
        if (StringUtils.isEmpty(workCenterExt.getShiftCode()) || StringUtils.isEmpty(workCenterExt.getWorkTime())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("生产线[%s]未启动班次", repairRequestModel.getWorkCenterCode())
                    .build();
        }

        MesBadCell mesBadCell = badCellRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID,
                        MesPcnExtConstWords.WORK_ORDER_NO, MesPcnExtConstWords.WORK_TIME, MesPcnExtConstWords.SHIFT_CODE, MesPcnExtConstWords.WORK_CELL_CODE},
                new Object[]{repairRequestModel.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                        workOrderNo, workCenterExt.getWorkTime(), workCenterExt.getShiftCode(), repairRequestModel.getWorkCellCode()});

        if(mesBadCell == null){
            MesProcess processDb = mesProcessRDao.getByProperty(
                    new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PROCESS_CODE},
                    new Object[]{repairRequestModel.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), repairRequestModel.getProcessCode()});
            mesBadCell = new MesBadCell();
            mesBadCell.setOrganizeCode(repairRequestModel.getOrganizeCode());
            mesBadCell.setPartNo(produceSnExt.getPartNo());
            mesBadCell.setPartNameRdd(produceSnExt.getPartNameRdd());
            mesBadCell.setWorkCenterCode(repairRequestModel.getWorkCenterCode());
            mesBadCell.setWorkCellCode(repairRequestModel.getWorkCellCode());
            mesBadCell.setProcessCode(repairRequestModel.getProcessCode());
            mesBadCell.setProcessNameRdd(null != processDb ? processDb.getProcessName() : null);
            mesBadCell.setQty(new Double(badCellDetailList.size()));
            mesBadCell.setWorkOrderNo(workOrderNo);
            mesBadCell.setWorkTime(workCenterExt.getWorkTime());
            mesBadCell.setShiftCode(workCenterExt.getShiftCode());
            ConvertBean.serviceModelInitialize(mesBadCell, repairRequestModel.getModifyUser());
            badCellRepository.insert(mesBadCell);
        }else {
            mesBadCell.setQty(MathOperation.add(mesBadCell.getQty(), new Double(badCellDetailList.size())));
            ConvertBean.serviceModelUpdate(mesBadCell, repairRequestModel.getModifyUser());
            badCellRepository.save(mesBadCell);
        }

        //新增不良明细数据
        MesBadCellDetail badCellDetail;
        for(MesBadCellDetail mesBadCellDetail : badCellDetailList){
            badCellDetail = new MesBadCellDetail();
            BeanUtils.copyProperties(mesBadCellDetail, badCellDetail, MesPcnExtConstWords.ID);
            badCellDetail.setWorkTime(workCenterExt.getWorkTime());
            badCellDetail.setShiftCode(workCenterExt.getShiftCode());
            badCellDetail.setSerialNumber(repairRequestModel.getSerialNumber());
            badCellDetail.setWorkCellCode(repairRequestModel.getWorkCellCode());
            badCellDetail.setRepairStatus(MesPcnExtEnumUtil.MES_REPAIR_STATUS.NO_REPAIR.getValue());
            ConvertBean.serviceModelInitialize(badCellDetail, repairRequestModel.getModifyUser());
            badCellDetail.setDefectActionTime(badCellDetail.getCreateDatetime());
            mesBadCellDetailRDao.insert(badCellDetail);
        }

        produceSnExt.setQcStatus(MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.DEFECTED.getValue());
        ConvertBean.serviceModelUpdate(produceSnExt, repairRequestModel.getModifyUser());
        produceSnExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        new ConvertBeanExt(produceSnExt).convertBean(produceSnExt);
        produceSnExtRepository.save(produceSnExt);
    }

    /**
     * 异常
     *
     * @param softTypeCode          softTypeCode
     * @param errorDetailString     错误消息字符串
     * @param imppExceptionEnumCode 异常代码
     * @param args                  参数
     */
    private void throwImppException(String softTypeCode, String errorDetailString, String imppExceptionEnumCode, Object... args) {
        throw ImppExceptionBuilder.newInstance()
                .setSystemID(softTypeCode)
                .setErrorCode(imppExceptionEnumCode)
                .setErrorDetail(errorDetailString, args)
                .build();
    }


}
