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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesOrderJobService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.IOrderJobDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesOrderJobModel;
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.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
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.bean.MesWorkOrder;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkOrderRepository;
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.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/01/18 16:00
 * @Description:
 **/
@Service
@Transactional(readOnly = false)
public class MesOrderJobService implements IMesOrderJobService {
    @Autowired
    private MesOrderJobRepository mesOrderJobRDao;
    @Autowired
    private IOrderJobDao orderJobDao;
    @Autowired
    private MesWorkOrderRepository mesWorkOrderRDao;
    @Autowired
    private MesWorkCenterExtRepository workCenterRepository;
    @Autowired
    private MesProjectTourDetailRepository projectTourDetailRDao;
    @Autowired
    private MesExteriorScratchProofDetailRepository exteriorScratchProofDetailRDao;
    @Autowired
    private MesPersonCheckDetailRepository personCheckDetailRDao;
    @Autowired
    private MesConsistencyAffirmRecordRepository consistencyAffirmRecordRepository;
    @Autowired
    private MesEquipmentCheckDetailRepository equDetailRepository;
    @Autowired
    private MesAntiStaticCheckDetailRepository antiStaticCheckDetailRepository;
    @Autowired
    private MesFirstOrderDetailRepository mesFirstOrderDetailRDao;
    @Autowired
    private MesFailCaseCheckDetailRepository failCaseCheckDetailRDao;
    @Autowired
    private MesProcessTorqueManageTaskDetailRepository torqueManageTaskDetailRepository;

    @Override
    public List<MesOrderJobModel> queryMesOrderJob(MesOrderJobModel orderJob) {
        //获取产线的当前班次
        //默认查询当前班次的单据作业
        /*MesWorkCenterExt workCenter = getWorkCenter(orderJob.getWorkCenterCode(), orderJob.getOrganizeCode());
        orderJob.setShiftCode(workCenter.getShiftCode());*/
        return this.orderJobDao.queryMesOrderJob(orderJob);
    }

    @Override
    public MesWorkCenterExt getWorkCenter(String workCenterCode, String organizeCode) {
        return workCenterRepository.getByProperty(
                new String[]{"workCenterCode", "organizeCode", "isValid", "isDeleted"},
                new Object[]{workCenterCode, organizeCode,
                        CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                        CommonEnumUtil.IS_DEAL.NO.getValue()});
    }

    @Override
    public void doCommitOrderJob(String orderNo, Integer orderType, String modifyUser, String organizeCode) {
        //查询单据主表
        DdlPackBean jobPackage = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(orderNo, "orderNo", jobPackage);
        MesOrderJob mesOrderJob = mesOrderJobRDao.getByProperty(jobPackage);
        if (null == mesOrderJob) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("单据【%s】不存在!", orderNo)
                    .build();
        }

        //查询单据下点检单是否全部完成
        boolean isAllCommplete = isAllCommplete(orderNo, orderType, organizeCode);
        if (!isAllCommplete) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("单据【%s】下点检明细还未全部完成!", orderNo)
                    .build();
        }

        //修改单据状态为 完成
        mesOrderJob.setComplateTime(TimeTool.getNowTime(true));
        ConvertBean.serviceModelUpdate(mesOrderJob, modifyUser);
        mesOrderJob.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECK_COMPLETE.getValue());
        mesOrderJobRDao.save(mesOrderJob);
    }

    private boolean isAllCommplete(String orderNo, Integer orderType, String organizeCode) {
        DdlPackBean packBean = MesPcnHqlPack.getAllBaseData(organizeCode);
        DdlPreparedPack.getStringEqualPack(orderNo, MesPcnExtConstWords.ORDER_NO, packBean);

        switch (MesPcnExtEnumUtil.MES_OR_ORDER_TYPE.getByValue(orderType)) {
            /*case PART_CHECK:
                DdlPreparedPack.getNotInPackArray(new Object[]{MesPcnExtEnumUtil.CHECK_RESULT.NG.getValue(), MesPcnExtEnumUtil.CHECK_RESULT.OK.getValue()},
                        MesPcnExtConstWords.CHECK_RESULT, packBean);
                List<MesPartCheckDetail> partCheckDetailList = partCheckDetailRDao.findByHqlWhere(packBean);
                return CollectionUtils.isEmpty(partCheckDetailList);*/

            case PERSON_CHECK:
                DdlPreparedPack.getNotInPackArray(new Object[]{MesPcnExtEnumUtil.CHECK_RESULT.NG.getValue()+"", MesPcnExtEnumUtil.CHECK_RESULT.OK.getValue()+""},
                        MesPcnExtConstWords.CHECK_RESULT, packBean);
                DdlPreparedPack.getNotInPack(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CLOSE.getValue(),MesPcnExtConstWords.ORDER_STATUS,packBean);
                List<MesPersonCheckDetail> personCheckDetailList = personCheckDetailRDao.findByHqlWhere(packBean);
                return CollectionUtils.isEmpty(personCheckDetailList)? true : false;

            //case Q_MANAGE:
            //    //判断当前明细数据中【刀头是否完好】字段存在数据
            //    List<MesQManageTaskDetail> qDetailsTotal = qManageTaskDetailRDao.findByHqlWhere(packBean);
            //    DdlPreparedPack.getStringNotBlanklPack("isIntact", packBean);
            //    List<MesQManageTaskDetail> qDetails = qManageTaskDetailRDao.findByHqlWhere(packBean);
            //    return qDetails.size() == qDetailsTotal.size() ? true : false;

            case EQU_CHECK:
                DdlPackBean equPackBean = MesPcnHqlPack.getAllBaseData(organizeCode);
                DdlPreparedPack.getStringEqualPack(orderNo, "orderJobNo", equPackBean);
                DdlPreparedPack.getNotInPack(Stream.of(MesPcnExtEnumUtil.EQU_CHECK_RESULT.QUALIFIED.getValue(),
                        MesPcnExtEnumUtil.EQU_CHECK_RESULT.EQUIPMENT_ABNORMAL.getValue(),
                        MesPcnExtEnumUtil.EQU_CHECK_RESULT.EQUIPMENT_FAILURE.getValue()).collect(Collectors.toList()), "checkResult", equPackBean);
                List<MesEquipmentCheckDetail> equDetails = equDetailRepository.findByHqlWhere(equPackBean);
                return CollectionUtils.isEmpty(equDetails) ? true : false;

            //兼容EP
            //case EP_EQU_CHECK:
            //    DdlPackBean epEquPackBean = MesPcnHqlPack.getAllBaseData(organizeCode);
            //    DdlPreparedPack.getStringEqualPack(orderNo, "orderJobNo", epEquPackBean);
            //    DdlPreparedPack.getNotInPack(Stream.of(MesPcnExtEnumUtil.EQU_CHECK_RESULT.QUALIFIED.getValue(),
            //            MesPcnExtEnumUtil.EQU_CHECK_RESULT.EQUIPMENT_ABNORMAL.getValue(),
            //            MesPcnExtEnumUtil.EQU_CHECK_RESULT.EQUIPMENT_FAILURE.getValue()).collect(Collectors.toList()), "checkResult", epEquPackBean);
            //    List<MesEpEquipmentCheckDetail> epEquDetails = epEquDetailRepository.findByHqlWhere(epEquPackBean);
            //    return CollectionUtils.isEmpty(epEquDetails) ? true : false;

            case ESD_CHECK:
                DdlPackBean antPackBean = MesPcnHqlPack.getAllBaseData(organizeCode);
                DdlPreparedPack.getStringEqualPack(orderNo, "orderJobNo", antPackBean);
                DdlPreparedPack.getNotInPack(Stream.of(MesPcnExtEnumUtil.ANTI_CHECK_RESULT.QUALIFIED.getValue(),
                        MesPcnExtEnumUtil.ANTI_CHECK_RESULT.UN_QUALIFIED.getValue()).collect(Collectors.toList()), "checkResult", antPackBean);
                List<MesAntiStaticCheckDetail> antiStaticCheckDetailList = antiStaticCheckDetailRepository.findByHqlWhere(antPackBean);
                return CollectionUtils.isEmpty(antiStaticCheckDetailList) ? true : false;

                case FAILURE_CASE_CHECK:
                DdlPackBean failPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getStringEqualPack(orderNo, "orderJobNo", failPackBean);
                List<Integer> statusList = Stream.of(MesPcnExtEnumUtil.ANTI_CHECK_RESULT.QUALIFIED.getValue(),
                        MesPcnExtEnumUtil.ANTI_CHECK_RESULT.UN_QUALIFIED.getValue()).collect(Collectors.toList());
                DdlPreparedPack.getNotInPack(statusList, "checkResult", failPackBean);
                List<MesFailCaseCheckDetail> failDetails = failCaseCheckDetailRDao.findByHqlWhere(failPackBean);
                return CollectionUtils.isEmpty(failDetails) ? true : false;

            case WORK_ORDER_FIRST:
                List<MesFirstOrderDetail> fDetailsTotal = mesFirstOrderDetailRDao.findByHqlWhere(packBean);
                DdlPreparedPack.getStringNotBlanklPack("checkResult", packBean);
                List<MesFirstOrderDetail> fDetails = mesFirstOrderDetailRDao.findByHqlWhere(packBean);
                return fDetailsTotal.size() == fDetails.size() ? true : false;

            case NAMEPLATE_GUARANTEE_CONSISTENCY:
                DdlPreparedPack.getNotInPackArray(new Object[]{MesPcnExtEnumUtil.CHECK_RESULT.NG.getValue(), MesPcnExtEnumUtil.CHECK_RESULT.OK.getValue()},
                        MesPcnExtConstWords.CHECK_RESULT, packBean);
                List<MesConsistencyAffirmRecord> consistencyAffirmRecordList = consistencyAffirmRecordRepository.findByHqlWhere(packBean);
                return CollectionUtils.isEmpty(consistencyAffirmRecordList)? true : false;

            case EXTERIOR_SCRATCH_PROOF_CHECK:
                DdlPreparedPack.getNotInPackArray(new Object[]{MesPcnExtEnumUtil.CHECK_RESULT.NG.getValue(), MesPcnExtEnumUtil.CHECK_RESULT.OK.getValue()},
                        MesPcnExtConstWords.CHECK_RESULT, packBean);
                List<MesExteriorScratchProofDetail> exteriorScratchProofDetailList = exteriorScratchProofDetailRDao.findByHqlWhere(packBean);
                return CollectionUtils.isEmpty(exteriorScratchProofDetailList)? true : false;

            case PROJECT_TOUR_CONTRIM:
                DdlPreparedPack.getNotInPackArray(new Object[]{MesPcnExtEnumUtil.CHECK_RESULT.NG.getValue(), MesPcnExtEnumUtil.CHECK_RESULT.OK.getValue()},
                        MesPcnExtConstWords.CHECK_RESULT, packBean);
                List<MesProjectTourDetail> projectTourDetailList = projectTourDetailRDao.findByHqlWhere(packBean);
                return CollectionUtils.isEmpty(projectTourDetailList)? true : false;

            case TORQUE_MANAGE:
                DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getStringEqualPack(orderNo, "orderJobNo", ddlPackBean);
                DdlPreparedPack.getNotInPackArray(new Object[]{MesPcnExtEnumUtil.CHECK_RESULT.NG.getValue(), MesPcnExtEnumUtil.CHECK_RESULT.OK.getValue()},
                        MesPcnExtConstWords.CHECK_RESULT, ddlPackBean);
                List<MesProcessTorqueManageTaskDetail> torqueManageTaskDetailList = torqueManageTaskDetailRepository.findByHqlWhere(ddlPackBean);
                return CollectionUtils.isEmpty(torqueManageTaskDetailList)? true : false;

            default:
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("单据类型不存在！")
                        .build();
        }
    }


    @Override
    public ListPager<MesOrderJobModel> queryMesOrderJobByPager(MesOrderJobModel orderJob, Pager pager) {
        pager = PagerHelper.getPager(pager, orderJobDao.queryMesOrderJobCount(orderJob));
        List<MesOrderJobModel> jobList = orderJobDao.queryMesOrderJob(orderJob, pager);
        return new ListPager(jobList, pager);
    }

    @Override
    public int orderJobUpdateOrderStatus(long id, Integer orderStatus, String organizeCode, String modifyUser, String closeReason) {
        List<MesOrderJob> jobList = mesOrderJobRDao.findByProperty(new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue(), id});
        if (CollectionUtils.isEmpty(jobList)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("该单据作业不存在")
                    .build();
        }

        String nowTime = TimeTool.getNowTime(true);

        return mesOrderJobRDao.updateByProperties(new String[]{MesPcnExtConstWords.ID}, new Object[]{id},
                new String[]{MesPcnExtConstWords.ORDER_STATUS, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME, "closeReason", "closeUser", "closeTime"},
                new Object[]{orderStatus, modifyUser, nowTime, closeReason, modifyUser, nowTime});
    }

    @Override
    public List<MesOrderJob> findMesOrderJob(MesOrderJob mesOrderJob) {
        List<Integer> statusList = new ArrayList<>();
        DdlPackBean packBean = MesPcnHqlPack.getAllBaseData(mesOrderJob.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesOrderJob.getWorkCenterCode(), MesPcnExtConstWords.WORK_CENTER_CODE, packBean);
        statusList.add(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue());
        statusList.add(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue());
        DdlPreparedPack.getNumEqualPack(mesOrderJob.getOrderType(), "orderType", packBean);
        DdlPreparedPack.getInPackList(statusList, "orderStatus", packBean);

        List<MesOrderJob> mesOrderJobs = mesOrderJobRDao.findByHqlWhere(packBean);
        if (!CollectionUtils.isEmpty(mesOrderJobs)) {

            List<String> workOrderNoList = mesOrderJobs.stream().map(MesOrderJob::getWorkOrderNo).collect(Collectors.toList());

            Map<String, MesWorkOrder> workOrderMapByOrderNo = new HashMap<>();

            if (!CollectionUtils.isEmpty(workOrderNoList)) {

                DdlPackBean workPackBean = DdlPackBean.getDdlPackBean(mesOrderJob.getOrganizeCode());
                DdlPreparedPack.getInPackList(workOrderNoList, MesPcnExtConstWords.ORDER_NO, workPackBean);
                List<MesWorkOrder> workOrderList = mesWorkOrderRDao.findByHqlWhere(workPackBean);

                workOrderMapByOrderNo = workOrderList.stream().collect(Collectors.toMap(MesWorkOrder::getOrderNo, Function.identity(), (x, y) -> y));

            }

            for (MesOrderJob orderJob : mesOrderJobs) {
                if (!StringUtils.isEmpty(orderJob.getWorkOrderNo())) {
                    MesWorkOrder workOrder = workOrderMapByOrderNo.get(orderJob.getWorkOrderNo());
                    orderJob.setPartNo(workOrder.getPartNo());
                    orderJob.setPartNameRdd(workOrder.getPartNameRdd());
                }
            }
        }

        return mesOrderJobs;
    }

    @Override
    public int updateOrderStatusByIds(String[] idsStr, Integer orderStatus, String organizeCode, String modifyUser) {
        StringBuffer wheres = new StringBuffer();
        HqlPack.getInPack(String.join(",", idsStr), MesPcnExtConstWords.ID, wheres);
        HqlPack.getStringEqualPack(organizeCode, MesPcnExtConstWords.ORGANIZE_CODE, wheres);
        int num = mesOrderJobRDao.updateByHqlWhere(
                wheres.toString(),
                new String[]{MesPcnExtConstWords.ORDER_STATUS, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
                new Object[]{orderStatus, modifyUser, TimeTool.getNowTime(true)}
        );
        return num;
    }
}
