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


import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesQmsScrapService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesPartInspectionModel;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
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.bean.MesProduceSn;
import cn.estsh.i3plus.pojo.mes.bean.MesQmsScrap;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspection;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspectionDetail;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspectionPerson;
import cn.estsh.i3plus.pojo.mes.repository.MesPartInspectionDetailRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesProduceSnRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesQmsScrapRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description :MES_QMS报废品汇总
 * @Reference :
 * @Author : gsz
 * @CreateDate 2024/7/3 10:28
 * @Modify:
 **/
@Service
@Slf4j
public class MesQmsScrapService implements IMesQmsScrapService {
    @Autowired
    private MesPartInspectionDetailRepository partInspectionDetailRDao;

    @Autowired
    private MesProduceSnRepository mesProduceSnRepository;

    @Autowired
    private MesQmsScrapRepository mesQmsScrapRepository;

    @Override
    public void doQmsScrapByPartInspectionNew(List<MesPartInspection> mesPartInspectionLists, List<MesPartInspectionPerson> mesPartInspectionPersonList, String organizeCode) {

        Map<String, List<MesPartInspection>> map =  mesPartInspectionLists.stream().collect(Collectors.groupingBy(MesPartInspection::getInspectionDate));

        map.forEach((k,v) -> {
            String inspectionDate = k;
            List<MesPartInspection> mesPartInspectionList = v;

            List<Long> idList = mesPartInspectionList.stream().map(MesPartInspection::getId).collect(Collectors.toList());
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getInPackList(idList, "pid", packBean);
            List<MesPartInspectionDetail> partInspectionDetails = partInspectionDetailRDao.findByHqlWhere(packBean);
            Map<Long, List<MesPartInspectionDetail>> idDetailListMap = partInspectionDetails.stream().collect(Collectors.groupingBy(MesPartInspectionDetail::getPid));

            List<MesPartInspectionModel> partInspectionModels = new ArrayList<>();
            for (MesPartInspection mesPartInspection : mesPartInspectionList) {
                MesPartInspectionModel mesPartInspectionModel = new MesPartInspectionModel();
                BeanUtils.copyProperties(mesPartInspection, mesPartInspectionModel);
                if (Objects.equals(mesPartInspection.getSourceType(), MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue())) {
                    // 根据条码查询条码信息
                    DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                    DdlPreparedPack.getStringEqualPack(mesPartInspection.getSn(),"productSn", ddlPackBean);
                    DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, ddlPackBean);
                    MesProduceSn mesProduceSn = mesProduceSnRepository.getByProperty(ddlPackBean);
                    if (mesProduceSn == null) {
                        DdlPackBean custPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                        DdlPreparedPack.getStringEqualPack(mesPartInspection.getSn(),"custSn", custPackBean);
                        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, custPackBean);
                        mesProduceSn = mesProduceSnRepository.getByProperty(custPackBean);
                        if (mesProduceSn == null) {
                            MesPcnException.throwBusiException(String.format("条码:【%s】不存在", mesPartInspection.getSn()));
                        }
                    }
                    mesPartInspectionModel.setWorkCenterCode(mesProduceSn.getWorkCenterCode());
                    mesPartInspectionModel.setWorkCellCode(mesProduceSn.getWorkCellCode());
                    mesPartInspectionModel.setShiftGroup(mesProduceSn.getShiftGroup());

                    partInspectionModels.add(mesPartInspectionModel);
                } else {
                    mesPartInspectionModel.setWorkCenterCode(mesPartInspection.getWorkCenterCode());
                    partInspectionModels.add(mesPartInspectionModel);
                }
            }

            //43326 电子化检验，发送给QMS的数据，按照零件号+责任人类型分组发送
            //Map<String, List<MesPartInspection>> workOrderPartMap = mesPartInspectionList.stream().collect(Collectors.groupingBy(p -> p.getPartNo() +"="+p.getResponsibleParty()));
            Map<MesPartInspectionModel, List<MesPartInspectionModel>> workOrderPartMap = partInspectionModels.stream().collect(Collectors.groupingBy(p -> {
                MesPartInspectionModel mesPartInspectionModel = new MesPartInspectionModel();
                mesPartInspectionModel.setWorkCenterCode(p.getWorkCenterCode());
                mesPartInspectionModel.setWorkCellCode(p.getWorkCellCode());
                mesPartInspectionModel.setShiftGroup(p.getShiftGroup());
                mesPartInspectionModel.setPartNo(p.getPartNo());
                mesPartInspectionModel.setResponsibleParty(p.getResponsibleParty());

                return mesPartInspectionModel;
            }));
            //根据物料对可疑品分组
            List<MesQmsScrap> qmsScrapList = new ArrayList<>();
            log.info("一共需要汇总{}条报废数据2", workOrderPartMap.size());
            Map<Long, List<MesPartInspectionPerson>> personMap = mesPartInspectionPersonList.stream().collect(Collectors.groupingBy(MesPartInspectionPerson::getPid));


            for (Map.Entry<MesPartInspectionModel, List<MesPartInspectionModel>> stringListEntry : workOrderPartMap.entrySet()) {

                MesPartInspectionModel mesPartInspectionModel = stringListEntry.getKey();
                String keyPartNo = mesPartInspectionModel.getPartNo();
                List<MesPartInspectionModel> mesPartInspections = stringListEntry.getValue();
                MesPartInspectionModel next = mesPartInspections.iterator().next();
                List<MesPartInspectionDetail> mesPartInspectionDetails = new ArrayList<>();
                for (MesPartInspectionModel mesPartInspection : mesPartInspections) {
                    mesPartInspectionDetails.addAll(idDetailListMap.get(mesPartInspection.getId()));
                }

                //新增一条数据到报废表中
                MesQmsScrap mesQmsScrap = new MesQmsScrap();
                mesQmsScrap.setWorkCenterCode(mesPartInspectionModel.getWorkCenterCode());
                mesQmsScrap.setWorkCellCode(mesPartInspectionModel.getWorkCellCode());
                mesQmsScrap.setShiftGroup(mesPartInspectionModel.getShiftGroup());
                mesQmsScrap.setOrganizeCode(organizeCode);
                mesQmsScrap.setAsnNo("");
                mesQmsScrap.setSource("MES");
                double sum = 0.0;
                for (MesPartInspection mesPartInspection : mesPartInspections) {
                    if (Objects.equals(mesPartInspection.getSourceType(), MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue())) {
                        sum += mesPartInspection.getRejectQty();
                    } else {
                        List<MesPartInspectionPerson> personList = personMap.get(mesPartInspection.getId());
                        if (!CollectionUtils.isEmpty(personList)) {
                            double rejectQty = personList.stream().map(MesPartInspectionPerson::getQty).reduce((a, b) -> a + b).get();
                            sum += rejectQty;
                        }
                    }
                }
                mesQmsScrap.setRejectQty(sum);
                mesQmsScrap.setPartNo(keyPartNo);
                mesQmsScrap.setPartName(next.getPartName());
                String defectTypeName = mesPartInspectionDetails.stream().map(MesPartInspectionDetail::getDefectTypeName).collect(Collectors.joining(";"));
                mesQmsScrap.setDefectTypeName(defectTypeName);
                mesQmsScrap.setReponsibilityId(next.getResponsibleParty());
                mesQmsScrap.setNcJudger(next.getModifyUser());
                ConvertBean.serviceModelInitialize(mesQmsScrap, "MesScrapJob");
                qmsScrapList.add(mesQmsScrap);
            }
            log.info("一共需要汇总{}条报废数据3", qmsScrapList.size());
            mesQmsScrapRepository.saveAll(qmsScrapList);
        });
    }

    @Override
    public void doQmsScrapByPartInspection(List<MesPartInspection> mesPartInspectionLists, String organizeCode){

        Map<String, List<MesPartInspection>> map =  mesPartInspectionLists.stream().collect(Collectors.groupingBy(MesPartInspection::getInspectionDate));

        map.forEach((k,v) -> {
            String inspectionDate = k;
            List<MesPartInspection> mesPartInspectionList = v;

            List<Long> idList = mesPartInspectionList.stream().map(MesPartInspection::getId).collect(Collectors.toList());
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getInPackList(idList, "pid", packBean);
            List<MesPartInspectionDetail> partInspectionDetails = partInspectionDetailRDao.findByHqlWhere(packBean);
            Map<Long, List<MesPartInspectionDetail>> idDetailListMap = partInspectionDetails.stream().collect(Collectors.groupingBy(MesPartInspectionDetail::getPid));
            //43326 电子化检验，发送给QMS的数据，按照零件号+责任人类型分组发送
            Map<String, List<MesPartInspection>> workOrderPartMap = mesPartInspectionList.stream().collect(Collectors.groupingBy(p -> p.getPartNo() + "=" + p.getResponsibleParty()));
            //根据物料对可疑品分组
            List<MesQmsScrap> qmsScrapList = new ArrayList<>();
            log.info("一共需要汇总{}条报废数据2", workOrderPartMap.size());

            for (Map.Entry<String, List<MesPartInspection>> stringListEntry : workOrderPartMap.entrySet()) {
                String keyPartNo = stringListEntry.getKey().split("=")[0];
                List<MesPartInspection> mesPartInspections = stringListEntry.getValue();
                MesPartInspection next = mesPartInspections.iterator().next();
                List<MesPartInspectionDetail> mesPartInspectionDetails = new ArrayList<>();
                for (MesPartInspection mesPartInspection : mesPartInspections) {
                    mesPartInspectionDetails.addAll(idDetailListMap.get(mesPartInspection.getId()));
                }

                //新增一条数据到报废表中
                MesQmsScrap mesQmsScrap = new MesQmsScrap();
                mesQmsScrap.setOrganizeCode(organizeCode);
                mesQmsScrap.setAsnNo("");
                mesQmsScrap.setSource("MES");
                double sum = mesPartInspections.stream().mapToDouble(MesPartInspection::getRejectQty).sum();
                mesQmsScrap.setRejectQty(sum);
                mesQmsScrap.setPartNo(keyPartNo);
                mesQmsScrap.setPartName(next.getPartName());
                String defectTypeName = mesPartInspectionDetails.stream().map(MesPartInspectionDetail::getDefectTypeName).collect(Collectors.joining(";"));
                mesQmsScrap.setDefectTypeName(defectTypeName);
                mesQmsScrap.setReponsibilityId(next.getResponsibleParty());
                mesQmsScrap.setNcJudger(next.getModifyUser());
                ConvertBean.serviceModelInitialize(mesQmsScrap, "MesScrapJob");
                qmsScrapList.add(mesQmsScrap);
            }
            log.info("一共需要汇总{}条报废数据3", qmsScrapList.size());
            mesQmsScrapRepository.saveAll(qmsScrapList);
        });
    }

}
