//package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.busi;
//
//import cn.estsh.i3plus.ext.mes.api.busi.IWorkOrderStartService;
//import cn.estsh.i3plus.ext.mes.pojo.bean.*;
//import cn.estsh.i3plus.ext.mes.pojo.repository.*;
//import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
//import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
//import cn.estsh.i3plus.mes.api.iservice.busi.ISyncFuncService;
//import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
//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.BaseResultBean;
//import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
//import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
//import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
//import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
//import cn.estsh.i3plus.pojo.mes.bean.MesProcess;
//import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
//import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
//import cn.estsh.i3plus.pojo.mes.repository.MesProcessRepository;
//import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
//import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
//import cn.estsh.impp.framework.boot.util.ResultBean;
//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.*;
//import java.util.stream.Collectors;
//
///**
// * @author wangjie
// * @version 1.0
// * @date 2021/1/13 9:28
// **/
//@Service("qManageOrderService")
//public class QManageOrderService implements IWorkOrderStartService {
//
//    @Autowired
//    private MesWorkCenterExtRepository mesWorkCenterExtRDao;
//
//    @Autowired
//    private MesOrderRuleRepository mesOrderRuleRDao;
//
//    @Autowired
//    private MesProcessCellRepository mesProcessCellRDao;
//
//    @Autowired
//    private MesProcessQManageRepository mesProcessQManageRDao;
//
//    @Autowired
//    private MesOrderJobRepository mesOrderJobRDao;
//
//    @Autowired
//    private MesQManageTaskDetailRepository mesQManageTaskDetailRDao;
//
//    @Autowired
//    private ISyncFuncService syncFuncService;
//
//    @Autowired
//    private MesProcessRepository mesProcessRDao;
//
//    @Autowired
//    private MesWorkCellRepository mesWorkCellRDao;
//
//    @Override
//    public ResultBean execute(MesWorkOrderExt mesWorkOrderExt) {
//        List<MesProcessQManage> mesProcessQManages = new ArrayList<>();
//        MesOrderRule mesOrderRule = null;
//        //根据产线获取产线信息
//        MesWorkCenterExt mesWorkCenterExt = mesWorkCenterExtRDao.getByProperty(
//                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED,"workCenterCode"},
//                new Object[]{mesWorkOrderExt.getOrganizeCode(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
//                        CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),mesWorkOrderExt.getWorkCenterCode()});
//
//        //产线代码、班次代码、单据类型【Q管理】创建规则【工单产生】查询单据作业信息
//        mesOrderRule = mesOrderRuleRDao.getByProperty(
//                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED,
//                        "orderType","createRule","workCenterCode","shiftCode"},
//                new Object[]{mesWorkOrderExt.getOrganizeCode(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
//                        CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),MesExtEnumUtil.MES_OR_ORDER_TYPE.Q_MANAGE.getValue(),
//                        MesExtEnumUtil.MES_OR_CREATE_RULE.WORK_ORDER_CREATE.getValue(),mesWorkOrderExt.getWorkCenterCode(),mesWorkCenterExt.getShiftCode()});
//
//        if(mesOrderRule == null){
//            mesOrderRule = mesOrderRuleRDao.getByProperty(
//                    new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED,
//                            "orderType","createRule","workCenterCode"},
//                    new Object[]{mesWorkOrderExt.getOrganizeCode(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
//                            CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),MesExtEnumUtil.MES_OR_ORDER_TYPE.Q_MANAGE.getValue(),
//                            MesExtEnumUtil.MES_OR_CREATE_RULE.WORK_ORDER_CREATE.getValue(),mesWorkOrderExt.getWorkCenterCode()});
//
//            if(mesOrderRule == null){
//                throw ImppExceptionBuilder.newInstance()
//                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
//                        .setErrorDetail("Q管理的单据规则信息不存在，请检查")
//                        .build();
//            }
//        }
//
//        //根据产线获取产线工序工位信息数据
//        List<MesProcessCell> mesProcessCellList = mesProcessCellRDao.findByProperty(
//                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED,"workCenterCode"},
//                new Object[]{mesWorkOrderExt.getOrganizeCode(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
//                        CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),mesWorkOrderExt.getWorkCenterCode()});
//
//        if(CollectionUtils.isEmpty(mesProcessCellList)){
//            throw ImppExceptionBuilder.newInstance()
//                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
//                    .setErrorDetail("当前产线【%s】在产线工序工位信息中不存在数据",mesWorkOrderExt.getWorkCenterCode())
//                    .build();
//        }
//
//        //根据工序代码分组
//        Map<String, List<MesProcessCell>> processCellmMap = mesProcessCellList.stream().collect(Collectors.groupingBy(MesProcessCell::getProcessCode));
//        //获取工序代码集合
//        List<String> processCodeList = mesProcessCellList.stream().map(MesProcessCell::getProcessCode).collect(Collectors.toList());
//
//        //根据工序代码集合和零件号为空查询工序Q管理项目信息
//        DdlPackBean packBean = findMesProcessQManage(mesWorkOrderExt.getOrganizeCode(), null, processCodeList);
//        List<MesProcessQManage> processQManageListByMotPartNo = mesProcessQManageRDao.findByHqlWhere(packBean);
//        if(!CollectionUtils.isEmpty(processQManageListByMotPartNo)){
//            mesProcessQManages.addAll(processQManageListByMotPartNo);
//        }
//
//        //根据工序代码集合和零件号查询工序Q管理项目信息
//        packBean = findMesProcessQManage(mesWorkOrderExt.getOrganizeCode(), mesWorkOrderExt.getPartNo(), processCodeList);
//        List<MesProcessQManage> processQManageList = mesProcessQManageRDao.findByHqlWhere(packBean);
//        if(!CollectionUtils.isEmpty(processQManageList)){
//            mesProcessQManages.addAll(processQManageList);
//        }
//
//        if(CollectionUtils.isEmpty(mesProcessQManages)){
//            throw ImppExceptionBuilder.newInstance()
//                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
//                    .setErrorDetail("根据规则无法查询到工序Q管理项目数据，请检查")
//                    .build();
//        }
//
//        //根据单据类型【Q管理】、产线代码和产线信息中的班次代码、生产日期获取Q管理单信息
//        packBean = DdlPackBean.getDdlPackBean(mesWorkOrderExt.getOrganizeCode());
//        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.MES_OR_ORDER_TYPE.Q_MANAGE.getValue(), "orderType", packBean);
//        DdlPreparedPack.getStringEqualPack(mesWorkOrderExt.getWorkCenterCode(), "workCenterCode", packBean);
//        DdlPreparedPack.getStringEqualPack(mesWorkCenterExt.getShiftCode(), "shiftCode", packBean);
//        DdlPreparedPack.getStringEqualPack(mesWorkCenterExt.getWorkTime(), "workTime", packBean);
//
//        MesOrderJob mesOrderJob = mesOrderJobRDao.getByProperty(packBean);
//
//        if(mesOrderJob == null){
//            String orderNo = insertMesOrderJob(mesWorkOrderExt, mesWorkCenterExt, mesOrderRule.getTaskType());
//            insertMesQManageTaskDetail(mesProcessQManages,processCellmMap,mesWorkOrderExt.getCreateUser(),orderNo);
//        }else {
//            //根据作业单号查询明细数据
//            packBean = DdlPackBean.getDdlPackBean(mesWorkOrderExt.getOrganizeCode());
//            DdlPreparedPack.getStringEqualPack(mesOrderJob.getOrderNo(), "orderNo", packBean);
//
//            List<MesQManageTaskDetail> mesQManageTaskDetails = mesQManageTaskDetailRDao.findByHqlWhere(packBean);
//            if(mesQManageTaskDetails.size() >= mesProcessQManages.size()) {
//                return ResultBean.success("添加成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
//            }
//
//            //获取两个存在差异的数据
//            Map<String, List<MesProcessQManage>> processQManageMap = mesProcessQManages.stream().collect(Collectors.groupingBy(q-> q.getProcessCode() +"&"+ q.getManageProjects()));
//            Map<String, List<MesQManageTaskDetail>> qManageTaskDetailsMap = mesQManageTaskDetails.stream().collect(Collectors.groupingBy(q-> q.getProcessCode() +"&"+ q.getManageProjects()));
//
//            for(String key : qManageTaskDetailsMap.keySet()){
//                if(processQManageMap.containsKey(key)){
//                    processQManageMap.remove(key);
//                }
//            }
//
//            mesProcessQManages = new ArrayList<>();
//            for(String key : processQManageMap.keySet()){
//                mesProcessQManages.addAll(processQManageMap.get(key));
//            }
//
//            String orderNo = insertMesOrderJob(mesWorkOrderExt, mesWorkCenterExt, mesOrderRule.getTaskType());
//            insertMesQManageTaskDetail(mesProcessQManages,processCellmMap,mesWorkOrderExt.getCreateUser(),orderNo);
//        }
//
//        return ResultBean.success("添加成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
//    }
//
//
//    private String insertMesOrderJob(MesWorkOrderExt mesWorkOrderExt,MesWorkCenterExt mesWorkCenterExt,Integer taskType){
//        // 调用平台生成条码的方法
//        List<String> orderNoList = getOrderNoByRuleCode(1,
//                MesExtConstWords.ORDER_NO_RULE, new GenSerialNoModel(), mesWorkOrderExt.getCreateUser(), mesWorkOrderExt.getOrganizeCode());
//
//        MesOrderJob mesOrderJob = new MesOrderJob();
//        mesOrderJob.setOrganizeCode(mesWorkOrderExt.getOrganizeCode());
//        mesOrderJob.setOrderType(MesExtEnumUtil.MES_OR_ORDER_TYPE.Q_MANAGE.getValue());
//        mesOrderJob.setTaskType(taskType);
//        mesOrderJob.setOrderNo(orderNoList.get(0));
//        mesOrderJob.setWorkCenterCode(mesWorkOrderExt.getWorkCenterCode());
//        mesOrderJob.setShiftCode(mesWorkCenterExt.getShiftCode());
//        mesOrderJob.setWorkOrderNo(mesWorkOrderExt.getOrderNo());
//        mesOrderJob.setOrderStatus(MesExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue());
//        mesOrderJob.setWorkTime(mesWorkCenterExt.getWorkTime());
//        mesOrderJob.setOrderDate(TimeTool.getToday());
//
//        ConvertBean.serviceModelInitialize(mesOrderJob, mesWorkOrderExt.getCreateUser());
//        mesOrderJobRDao.insert(mesOrderJob);
//
//        return orderNoList.get(0);
//
//    }
//
//    private void insertMesQManageTaskDetail(List<MesProcessQManage> mesProcessQManages, Map<String, List<MesProcessCell>> processCellmMap, String userName,String orderNo){
//        // 查询工序表
//        Map<String, Object> processCodeEntityMap = new HashMap<>();
//        try {
//            processCodeEntityMap = MesCommonUtil.getCodeEntityMap(mesProcessRDao, MesExtConstWords.PROCESS_CODE, mesProcessQManages.get(0).getOrganizeCode(), "工序表");
//        } catch (Exception e) {
//        }
//
//        // 查询工位表
//        Map<String, Object> workCellCodeEntityMap = new HashMap<>();
//        try {
//            workCellCodeEntityMap = MesCommonUtil.getCodeEntityMap(mesWorkCellRDao, MesExtConstWords.WORK_CELL_CODE, mesProcessQManages.get(0).getOrganizeCode(), "工位表");
//        } catch (Exception e) {
//        }
//
//
//        MesQManageTaskDetail mesQManageTaskDetail ;
//        for(MesProcessQManage processQManage : mesProcessQManages){
//            mesQManageTaskDetail = new MesQManageTaskDetail();
//            BeanUtils.copyProperties(processQManage, mesQManageTaskDetail, "id");
//            mesQManageTaskDetail.setOrderNo(orderNo);
//            mesQManageTaskDetail.setWorkCellCode(processCellmMap.get(processQManage.getProcessCode()).get(0).getWorkCellCode());
//            if(!CollectionUtils.isEmpty(processCodeEntityMap) && processCodeEntityMap.containsKey(mesQManageTaskDetail.getProcessCode())){
//                mesQManageTaskDetail.setProcessName(((MesProcess)processCodeEntityMap.get(mesQManageTaskDetail.getProcessCode())).getProcessName());
//            }
//            if(!CollectionUtils.isEmpty(workCellCodeEntityMap) && workCellCodeEntityMap.containsKey(mesQManageTaskDetail.getWorkCellCode())){
//                mesQManageTaskDetail.setWorkCellName(((MesWorkCell)workCellCodeEntityMap.get(mesQManageTaskDetail.getWorkCellCode())).getWorkCellName());
//            }
//
//            ConvertBean.serviceModelInitialize(mesQManageTaskDetail, userName);
//            mesQManageTaskDetailRDao.insert(mesQManageTaskDetail);
//        }
//    }
//
//    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.getCode())
//                    .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION.getCode())
//                    .setErrorDetail(serialNumberBean == null ? "条码未生成成功" : serialNumberBean.getErrorMsg())
//                    .build();
//        }
//    }
//
//
//
//    private static DdlPackBean findMesProcessQManage(String organizeCode, String partNo, List<String> processCodeList) {
//        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
//        if(StringUtils.isEmpty(partNo)){
//            DdlPreparedPack.getStringNullPack("partNo", packBean);
//        }
//        DdlPreparedPack.getStringEqualPack(partNo, "partNo", packBean);
//        DdlPreparedPack.getInPackList(processCodeList, "processCode", packBean);
//        return packBean;
//    }
//}
