package com.sw.mes.fb.aio.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.dto.EapCutCraftDto;
import com.sw.mes.core.dto.GetFbInfoDto;
import com.sw.mes.core.dto.LongCrystalDto1;
import com.sw.mes.core.dto.mes.pc.yb.YbInspectDataDto;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.fb.aio.dao.EapCutCraftDao;
import com.sw.mes.fb.aio.dao.EapSpecificationSendDao;
import com.sw.mes.fb.aio.dao.FbReCutDAO;
import com.sw.mes.fb.aio.dao.ProductionRecutDao;
import com.sw.mes.fb.aio.dto.*;
import com.sw.mes.fb.aio.entity.EapCutCraft;
import com.sw.mes.fb.aio.entity.EapEvolutionRecord;
import com.sw.mes.fb.aio.entity.EapGrindingMachine;
import com.sw.mes.fb.aio.entity.EapSpecificationSend;
import com.sw.mes.fb.aio.service.EapCutCraftService;
import com.sw.mes.fb.aio.service.EapEvolutionRecordService;
import com.sw.mes.fb.aio.service.EapGrindingMachineService;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class EapCutCraftServiceImpl extends BaseServiceImpl<EapCutCraft> implements EapCutCraftService {
    EapCutCraftDao dao;

    @Autowired
    public void setDao(EapCutCraftDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    FbReCutDAO fbReCutDAO;

    @Autowired
    ProductionRecutDao productionRecutDao;

    @Autowired
    EapSpecificationSendDao eapSpecificationSendDao;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    YbFeignClients ybFeignClients;

    @Autowired
    EapEvolutionRecordService eapEvolutionRecordService;

    @Autowired
    EapGrindingMachineService eapGrindingMachineService;

    @Autowired
    FbCheckOutDataService fbCheckOutDataService;

    @Override
    public ResponsePage<TurnStoreOtherDto> getCutRecordListPage(String crystalType, String search_gte_startCut, String search_lt_startCut, String search_gte_endCut, String search_lt_endCut, String search_like_roundSN, String search_like_equipNo, Pageable pageable) {
        Page<Map<String, Object>> page = dao.getPageList(search_gte_startCut, search_lt_startCut, search_gte_endCut, search_lt_endCut, "%" + search_like_roundSN + '%', "%" + search_like_equipNo + '%', "%" + crystalType + '%', pageable);
        List<TurnStoreOtherDto> list = JSON.parseArray(JSON.toJSONString(page.getContent()), TurnStoreOtherDto.class);
        List<DictionaryItem> windUp = dictionaryItemService.findByThemeValueAndEnable("windUpMap", true);
        Map<String, String> windUpMap = windUp.stream().collect(Collectors.toMap(DictionaryItem::getValue, DictionaryItem::getName));
        List<DictionaryItem> closureIdentification = dictionaryItemService.findByThemeValueAndEnable("windUpMap", true);
        Map<String, String> closureIdentificationMap = closureIdentification.stream().collect(Collectors.toMap(DictionaryItem::getValue, DictionaryItem::getName));


        for (int q = 0; q < list.size(); q++) {
            list.get(q).setCrystalType(list.get(q).getCrystalType() != null ? (list.get(q).getCrystalType().equals("0") ? "圆棒" : "方棒") : "");
        }
        for (TurnStoreOtherDto turnStoreOtherDto : list) {
            turnStoreOtherDto.setWindUp(windUpMap.get(turnStoreOtherDto.getWindUp()));
            turnStoreOtherDto.setClosureIdentification(closureIdentificationMap.get(turnStoreOtherDto.getClosureIdentification()));
//            if (turnStoreOtherDto.getRoundSN().startsWith("B")) {
//                Result<GetFbInfoDto> fbInfoByIdResult = ybFeignClients.findFbInfoBySectionNoYb(turnStoreOtherDto.getRoundSN());
//                GetFbInfoDto data = fbInfoByIdResult.getData();
//                //代工数据,查询圆棒检验数据库的边长赋值给返回列表
//                if (fbInfoByIdResult.getCode() == ResultCode.SUCCESS.getCode() && null != data) {
//                    turnStoreOtherDto.setSideLengthRange(data.getSideLengthRange());
//                }
//            }

            if (turnStoreOtherDto.getCrystalType().equals("圆棒")) {
                String no;
                if (null != turnStoreOtherDto.getIsCut() && "1".equals(turnStoreOtherDto.getIsCut().toString())) {
                    no = turnStoreOtherDto.getRoundSN();
                } else {
                    no = turnStoreOtherDto.getRoundSN().substring(0, 16);
                }
                Result<LongCrystalDto1> crystalData = ybFeignClients.getCrystalData(no);
                if (null != crystalData.getData()) {

                    //圆棒理论折算系数
                    if (StringUtils.isNotBlank(crystalData.getData().getSpecs())){
                        DictionaryItem weightRatio = dictionaryItemService.findByThemeValueAndNameAndEnable("WeightRatio", crystalData.getData().getSpecs(), true);
                        if (null != weightRatio && StringUtils.isNotBlank(weightRatio.getValue())){
                            turnStoreOtherDto.setTheoryWeight(turnStoreOtherDto.getRoundLength().divide(new BigDecimal(weightRatio.getValue()), 3, BigDecimal.ROUND_HALF_UP));
                        }
                    }
                   /* DictionaryItem byNameAndThemeId = dictionaryItemService.findByNameAndThemeId(crystalData.getData().getSpecs(), 94);
                    turnStoreOtherDto.setTheoryWeight(turnStoreOtherDto.getRoundLength().divide(new BigDecimal(byNameAndThemeId.getValue()), 2, BigDecimal.ROUND_HALF_UP));*/
                }

                //等级
                Result<YbInspectDataDto> inspectDataBaseBySectionNo = ybFeignClients.getInspectDataBaseBySectionNo(turnStoreOtherDto.getRoundSN());
                if(ResultCode.SUCCESS.getCode() == inspectDataBaseBySectionNo.getCode()){
                    YbInspectDataDto data = inspectDataBaseBySectionNo.getData();
                    if(null != data){
                        turnStoreOtherDto.setProductRank(data.getProductLevel());
                    }
                }
            } else {
                FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(turnStoreOtherDto.getRoundSN());
                if (null != dataByFbSectionNo) {
                    Result<LongCrystalDto1> crystalData = ybFeignClients.getCrystalData(turnStoreOtherDto.getRoundSN().substring(0, 12));
                    if (null == crystalData.getData()) {
                        turnStoreOtherDto.setTheoryWeight(dataByFbSectionNo.getTheoryWeightFb());
                    }
                    //等级
                    turnStoreOtherDto.setProductRank(dataByFbSectionNo.getProductLevelFb());
                }

            }
        }

        return new ResponsePage(list, page.getTotalElements());
    }

    @Override
    public void updateOld(Long staId, Long endId) {

       /* //处理截断加工记录数据
       List<EapCutCraft> savelist = new ArrayList<>();
        List<EapCutCraft> findlist = dao.findlist(staId, endId);
        for (EapCutCraft eapCutCraft : findlist){
            Map<String, Object> list = dao.getInfo(eapCutCraft.getRoundSn());
            if(list != null){
                TurnStoreOtherDto turnStoreOtherDto= JSON.parseObject(JSON.toJSONString(list), TurnStoreOtherDto.class);
                BeanUtils.copyProperties(turnStoreOtherDto, eapCutCraft, BeanUtil.getIgnoreProperties(turnStoreOtherDto, "id", null));
                //查询数据字典长度范围对照表 product_length
                List<DictionaryItem> items = dictionaryItemService.findByThemeValueAndEnable("WeightFractions", true);
                eapCutCraft.setIsCut(1);
                if (eapCutCraft.getLineNum() != null){
                    eapCutCraft.setNormalNum(eapCutCraft.getLineNum() == null ? 0 : eapCutCraft.getLineNum()-1);
                }
                else{
                    ReCut reCut = fbReCutDAO.findBySectionNo(eapCutCraft.getRoundSn());
                    if (reCut != null){
                        int count = productionRecutDao.getCountById(reCut.getId());
                        eapCutCraft.setReverseNum(Integer.parseInt(reCut.getCutNum()) -1);
                        eapCutCraft.setLineNum(Integer.valueOf(reCut.getCutNum()));
                        eapCutCraft.setIsCut(0);
                        eapCutCraft.setCause(reCut.getReason());
                        eapCutCraft.setRoundLength(reCut.getSegmentNoLength() ==null ? BigDecimal.valueOf(0) : reCut.getSegmentNoLength());
                        eapCutCraft.setSliceNum(count);
                        eapCutCraft.setCrystalType(1);
                    }else {
                        ProductionBackCuttingRecord obj = productionRecutDao.findBySectionNo(eapCutCraft.getRoundSn());
                        if (obj != null){
                            int count = productionRecutDao.getCountById(obj.getId());
                            eapCutCraft.setReverseNum(obj.getKnifeNum());
                            eapCutCraft.setLineNum(obj.getKnifeNum()+1-count);
                            eapCutCraft.setIsCut(0);
                            eapCutCraft.setCause(obj.getCause());
                            eapCutCraft.setRoundLength(obj.getBarLength() ==null ? BigDecimal.valueOf(0) : obj.getBarLength());
                            eapCutCraft.setSliceNum(count);
                            eapCutCraft.setCrystalType(0);
                        }
                    }
                }
                if (eapCutCraft.getRoundSn() != null && eapCutCraft.getRoundSn().length() > 7){
                    //获取
                    String str = eapCutCraft.getRoundSn().substring(4,7);
                    for (DictionaryItem item : items) {
                        if (str.equals(item.getName())) {
                            BigDecimal lineLength = eapCutCraft.getRoundLength()==null ? BigDecimal.valueOf(0) : eapCutCraft.getRoundLength();
                            BigDecimal xiShu = BigDecimal.valueOf(Double.parseDouble(item.getValue()));
                            eapCutCraft.setTheoryWeight(lineLength.divide(xiShu, 2, BigDecimal.ROUND_HALF_UP));
                        }
                    }
                }
            }
            savelist.add(eapCutCraft);
        }
        this.saveAll(savelist);*/

        //处理开方加工记录旧数据interface_eap_evolution_record EapEvolutionRecord
        List<EapEvolutionRecord> eapEvolutionRecordlist = dao.findEapEvolutionRecordlist(staId, endId);

        String equipType = "04";
        //获取所有开方机规格上传记录分组
        List<EapSpecificationSend> list1 = eapSpecificationSendDao.getGroupListByEquipNo(equipType);
        //根据规格参数不通分组
        Map<String, List<EapSpecificationSend>> map = list1.stream().collect(Collectors.groupingBy(EapSpecificationSend::getEquipNo));
        for (EapEvolutionRecord eapEvolutionRecord : eapEvolutionRecordlist) {
            List<EapSpecificationSend> list3 = map.get(eapEvolutionRecord.getEquipNo());
            if (list3 != null && list3.size() > 1) {
                list3.sort((t1, t2) -> t2.getCreatedTime().compareTo(t1.getCreatedTime()));
                for (EapSpecificationSend eapSpecificationSend : list3) {
                    if (eapEvolutionRecord.getCreatedTime().compareTo(eapSpecificationSend.getCreatedTime()) > 0) {
                        eapEvolutionRecord.setSpec(eapSpecificationSend.getSpec());
                        eapEvolutionRecord.setPnType(eapSpecificationSend.getPnType());
                        eapEvolutionRecord.setSideLen(eapSpecificationSend.getSideLen());
                        eapEvolutionRecord.setProductRank(eapSpecificationSend.getProductRank());
                        eapEvolutionRecord.setSplitJoint(eapSpecificationSend.getSplitJoint());
                        eapEvolutionRecord.setIsAssign(eapSpecificationSend.getIsAssign());
                        break;
                    }
                }
            }
        }
        eapEvolutionRecordService.saveAll(eapEvolutionRecordlist);


        //处理磨削加工记录旧数据interface_eap_grinding_machine EapGrindingMachine
        List<EapGrindingMachine> eapGrindingMachinelist = dao.findEapGrindingMachinelist(staId, endId);

        equipType = "05";
        list1 = eapSpecificationSendDao.getGroupListByEquipNo(equipType);
        map = list1.stream().collect(Collectors.groupingBy(EapSpecificationSend::getEquipNo));
        for (EapGrindingMachine eapGrindingMachine : eapGrindingMachinelist) {
            List<EapSpecificationSend> list3 = map.get(eapGrindingMachine.getEquipNo());
            if (list3 != null && list3.size() > 1) {
                list3.sort((t1, t2) -> t2.getCreatedTime().compareTo(t1.getCreatedTime()));
                for (EapSpecificationSend eapSpecificationSend : list3) {
                    if (eapGrindingMachine.getCreatedTime().compareTo(eapSpecificationSend.getCreatedTime()) > 0) {
                        eapGrindingMachine.setSpec(eapSpecificationSend.getSpec());
                        eapGrindingMachine.setPnType(eapSpecificationSend.getPnType());
                        eapGrindingMachine.setSideLen(eapSpecificationSend.getSideLen());
                        eapGrindingMachine.setProductRank(eapSpecificationSend.getProductRank());
                        eapGrindingMachine.setSplitJoint(eapSpecificationSend.getSplitJoint());
                        eapGrindingMachine.setIsAssign(eapSpecificationSend.getIsAssign());
                        break;
                    }
                }
            }
        }

        eapGrindingMachineService.saveAll(eapGrindingMachinelist);
    }

    @Override
    public List<TurnStoreOtherVo> getCutRecordList(String crystalType, String search_gte_startCut, String search_lt_startCut, String search_gte_endCut, String search_lt_endCut, String search_like_roundSN, String search_like_equipNo, RequestPage requestPage) {
        Page<Map<String, Object>> page = dao.getPageList(search_gte_startCut, search_lt_startCut, search_gte_endCut, search_lt_endCut, "%" + search_like_roundSN + '%', "%" + search_like_equipNo + '%', "%" + crystalType + '%', null);
        List<TurnStoreOtherVo> list = JSON.parseArray(JSON.toJSONString(page.getContent()), TurnStoreOtherVo.class);

        List<DictionaryItem> dictionaryItemList = dictionaryItemService.findByThemeValueAndEnable("WeightRatio", true);
        Map<String, String> dictionaryItemCount = dictionaryItemList.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue));

        List<String> fbSectionNos = new ArrayList<>();
        List<String> nos = new ArrayList<>();
        for (int q = 0; q < list.size(); q++) {
            list.get(q).setIsCut(list.get(q).getIsCut() != null ? (list.get(q).getIsCut().equals("0") ? "是" : "否") : "");
            list.get(q).setCrystalType(list.get(q).getCrystalType() != null ? (list.get(q).getCrystalType().equals("0") ? "圆棒" : "方棒") : "");
            fbSectionNos.add(list.get(q).getRoundSN());

//            if (list.get(q).getCrystalType().equals("圆棒")) {
                String no;
//                if (list.get(q).getIsCut().equals("1")) {
//                    no = list.get(q).getRoundSN();
//                } else {
                    //判断第二位是否为追溯标识(字母)
//                    String fromMark = list.get(q).getRoundSN().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
//                    if(fromMark.matches("[A-Z]+")){
//                        no = list.get(q).getRoundSN().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(),SectionIndexRangeEnum.毛棒范围.getEndIndex());
//                    }else {
                no = list.get(q).getRoundSN().substring(0, 16);
//                    }
//                }
                nos.add(no);
//            } else {
//                String fromMark = list.get(q).getRoundSN().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
//                if (fromMark.matches("[A-Z]+")) {
//                    nos.add(list.get(q).getRoundSN().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
//                } else {
//                    nos.add(list.get(q).getRoundSN().substring(0, 16));
//                }
//            }
        }

        List<FbCheckOutData> checkOutDataByFbSectionNoIns = fbCheckOutDataService.findCheckOutDataByFbSectionNoIns(fbSectionNos);
        Map<String, Object> checkOutDataCollect = checkOutDataByFbSectionNoIns.stream().collect(Collectors.toMap(FbCheckOutData::getFbSectionNo, FbCheckOutData::getTheoryWeightFb));
        Map<String, Object> checkOutDataCollect1 = checkOutDataByFbSectionNoIns.stream().collect(Collectors.toMap(FbCheckOutData::getFbSectionNo, FbCheckOutData::getSpecification));

        Map<String, String> productTypeCollect = null;
        Map<String, String> specsTypeCollect = null;
        Result<List<LongCrystalDto1>> allCrystalData = ybFeignClients.getAllCrystalData(nos);
        if (null != allCrystalData.getData()) {
            List<LongCrystalDto1> data = allCrystalData.getData();
//            productTypeCollect = data.stream().collect(Collectors.toMap(LongCrystalDto1::getCrystalNo, LongCrystalDto1::getProductType));
            specsTypeCollect = data.stream().collect(Collectors.toMap(LongCrystalDto1::getCrystalNo, LongCrystalDto1::getSpecs));
        }

        for (TurnStoreOtherVo turnStoreOtherVo : list) {

//            if (turnStoreOtherVo.getRoundSN().startsWith("B")) {
//                Result<GetFbInfoDto> fbInfoByIdResult = ybFeignClients.findFbInfoBySectionNoYb(turnStoreOtherVo.getRoundSN());
//                GetFbInfoDto data = fbInfoByIdResult.getData();
//                //代工数据,查询圆棒检验数据库的边长赋值给返回列表
//                if (fbInfoByIdResult.getCode() == ResultCode.SUCCESS.getCode() && null != data) {
//                    turnStoreOtherVo.setSideLengthRange(data.getSideLengthRange());
//                }
//            }
            if (turnStoreOtherVo.getCrystalType().equals("圆棒")) {
                String no;
//                if (turnStoreOtherVo.getIsCut().equals("1")) {
//                    no = turnStoreOtherVo.getRoundSN();
//                } else {
//                    String fromMark = turnStoreOtherVo.getRoundSN().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
//                    if(fromMark.matches("[A-Z]+")){
//                        no = turnStoreOtherVo.getRoundSN().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(),SectionIndexRangeEnum.毛棒范围.getEndIndex());
//                    }else {
                no = turnStoreOtherVo.getRoundSN().substring(0, 16);
//                    }
//                }
//                Result<LongCrystalDto1> crystalData = ybFeignClients.getCrystalData(no);
//                if(null != allCrystalData.getData()){
//                    List<LongCrystalDto1> data = allCrystalData.getData();
//                    turnStoreOtherVo.setProductType(crystalData.getData().getProductType());
//                    turnStoreOtherVo.setSpecs(crystalData.getData().getSpecs());
//                    turnStoreOtherVo.setTheoryWeight(turnStoreOtherVo.getRoundLength().divide(new BigDecimal(dictionaryItemCount.get(crystalData.getData().getSpecs())), 2, BigDecimal.ROUND_HALF_UP));
//                }
                if (specsTypeCollect.containsKey(no)) {
//                    turnStoreOtherVo.setProductType(productTypeCollect.get(no));
                    turnStoreOtherVo.setSpecs(specsTypeCollect.get(no));
                    turnStoreOtherVo.setTheoryWeight(turnStoreOtherVo.getRoundLength().divide(new BigDecimal(dictionaryItemCount.get(turnStoreOtherVo.getSpecs())), 3, BigDecimal.ROUND_HALF_UP));
                }
            } else {
                if (checkOutDataCollect.containsKey(turnStoreOtherVo.getRoundSN())) {
//                    Result<LongCrystalDto1> crystalData = ybFeignClients.getCrystalData(turnStoreOtherVo.getRoundSN().substring(0, 12));
//                    if(null!=crystalData.getData()) {
//                        turnStoreOtherVo.setProductType(crystalData.getData().getProductType());
//                    }
                    String no ;
//                    String fromMark = turnStoreOtherVo.getRoundSN().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
//                    if(fromMark.matches("[A-Z]+")){
//                        no = turnStoreOtherVo.getRoundSN().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(),SectionIndexRangeEnum.毛棒范围.getEndIndex());
//                    }else {
                    no = turnStoreOtherVo.getRoundSN().substring(0, 16);
//                    }
                    if(productTypeCollect.containsKey(no)){
                        turnStoreOtherVo.setProductType(productTypeCollect.get(no));
                    }
                    turnStoreOtherVo.setTheoryWeight(new BigDecimal(checkOutDataCollect.get(turnStoreOtherVo.getRoundSN()).toString()));
                    turnStoreOtherVo.setSpecs(checkOutDataCollect1.get(turnStoreOtherVo.getRoundSN()).toString());
                }
            }
        }
        return JSON.parseArray(JSON.toJSONString(list), TurnStoreOtherVo.class);
    }

    @Override
    public EapCutCraft getCutCraftByRoundSn(String roundSn) {
        return dao.findTopByRoundSnOrderByIdDesc(roundSn);
    }

    public EapCutCraft getCutCraftByRoundSnAndAuto(String roundSn, Integer isAuto) {
        return dao.findTopByRoundSnAndIsAutoOrderByIdDesc(roundSn, isAuto);
    }

    @Override
    public ResponsePage<EapGoldBreakReportDto> getGoldBreakListPage(String search_eq_equipType, String search_like_equipNo, String search_like_sn, String search_lt_startTime, String search_lt_endTime, Pageable pageable) {
        Page<Map<String, Object>> page = dao.getGoldBreakListPage(search_eq_equipType, search_lt_startTime, search_lt_endTime, "%" + search_like_equipNo + '%', "%" + search_like_sn + '%', pageable);
        List<EapGoldBreakReportDto> list = JSON.parseArray(JSON.toJSONString(page.getContent()), EapGoldBreakReportDto.class);
        return new ResponsePage(list, page.getTotalElements());
    }

    @Override
    public ResponsePage<EapSpecificationReportDto> specificationListPage(String search_like_equip, String search_like_lotNo,
                                                                         String search_gte_startTrimming, String search_lt_startTrimming, String search_gte_endTrimming, String search_lt_endTrimming, Pageable pageable) {
//        Page<Map<String, Object>> page = dao.specificationListPage(search_gte_startTrimming, search_lt_startTrimming, search_gte_endTrimming, search_lt_endTrimming, "%" + search_like_equip + '%', "%" + search_like_lotNo + '%', pageable);
        Page<Map<String, Object>> page = dao.specificationListPageV2(search_gte_startTrimming, search_lt_startTrimming, "%" + search_like_lotNo + '%',  "%" + search_like_equip + '%' , pageable);
        List<EapSpecificationReportDto> list = JSON.parseArray(JSON.toJSONString(page.getContent()), EapSpecificationReportDto.class);
        //开方加工记录表
        return new ResponsePage(list, page.getTotalElements());
    }

    @Override
    public ResponsePage<EapGrindingHoursReportDto> grindingReportListPage(String search_like_equip, String search_like_sn, String search_gte_startGrinding, String search_lt_startGrinding, String search_gte_endGrinding, String search_lt_endGrinding, Pageable pageable) {
        Page<Map<String, Object>> page = dao.grindingReportListPageV2("%" + search_like_equip + '%', "%" + search_like_sn + '%',search_gte_startGrinding,search_lt_startGrinding, pageable);
        List<EapGrindingHoursReportDto> list = JSON.parseArray(JSON.toJSONString(page.getContent()), EapGrindingHoursReportDto.class);
        if(null != list && list.size() > 0){
            List<DictionaryItem> theoreticalWeightCoefficientFb = dictionaryItemService.findByThemeValueAndEnable("TheoreticalWeightCoefficientFb", true);
            Map<String, String> collect = theoreticalWeightCoefficientFb.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue));
            for (EapGrindingHoursReportDto eapGrindingHoursReportDto : list) {
                //等级
                Result<YbInspectDataDto> inspectDataBaseBySectionNo = ybFeignClients.getInspectDataBaseBySectionNo(eapGrindingHoursReportDto.getSn());
                if(ResultCode.SUCCESS.getCode() == inspectDataBaseBySectionNo.getCode()){
                    YbInspectDataDto data = inspectDataBaseBySectionNo.getData();
                    if(null != data){
                        //等级
                        eapGrindingHoursReportDto.setProductRank(data.getProductLevel());
                        //边长
                        eapGrindingHoursReportDto.setLength(data.getActualLength());
                        if(collect.containsKey(data.getProductTypeSecond())){
                            String s = collect.get(data.getProductTypeSecond());
                            //理论重量
                            eapGrindingHoursReportDto.setWeight(data.getActualLength().divide(new BigDecimal(s), 3, RoundingMode.HALF_UP).setScale(3, BigDecimal.ROUND_HALF_UP));
                        }
                    }
                }
            }
        }
        //磨削加工记录表
        return new ResponsePage(list, page.getTotalElements());
    }

    @Override
    public Result saveEapCutCraftInfo(EapCutCraftDto eapCutCraftDto, Integer isAuto) {

        EapCutCraft obj = this.getCutCraftByRoundSnAndAuto(eapCutCraftDto.getRoundSn(), isAuto);

        //入站时和已存在一条完整记录时新增数据。
        if (obj != null && obj.getStartCut() != null && obj.getEndCut() != null) {
            //反切截断进站新建数据，否则更新前一条数据
            obj = null;
        }

        //eap上传
        if (isAuto == 0) {
            DictionaryItem item = null;
            //查询数据字典长度范围对照表 product_length
            if (eapCutCraftDto.getRoundSn() != null && eapCutCraftDto.getRoundSn().length() > 7) {
                //获取
                //todo:此取值尺寸无效
                String str = eapCutCraftDto.getRoundSn().substring(5, 8);
                item = dictionaryItemService.findByThemeValueAndNameAndEnable("WeightFractions", str, true);
            }
            eapCutCraftDto.setCrystalType(0);
            boolean matching = false;
            //查询方棒返切记录
            Result resultReCut = ybFeignClients.getReCutBySectionNoFb(eapCutCraftDto.getRoundSn());
            if (resultReCut != null && resultReCut.getCode() == ResultCode.SUCCESS.getCode()) {
                RecutDto recutDto = JSONObject.parseObject(JSONObject.toJSONString(resultReCut.getData()), RecutDto.class);
                if (recutDto != null) {
                    matching = true;
                    eapCutCraftDto.setCrystalType(1);
                    Result result1 = ybFeignClients.getProductionPaintingLineDetail(recutDto.getId(), 3);
                    if (result1 != null && result1.getCode() == ResultCode.SUCCESS.getCode()) {
//                        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(eapCutCraftDto.getRoundSn());
//                        if (dataByFbSectionNo != null){
//                            eapCutCraftDto.setTheoryWeight(dataByFbSectionNo.getTheoryWeightFb());
//                        }

                        if (item != null) {
                            BigDecimal lineLength = recutDto.getSegmentNoLength() == null ? BigDecimal.valueOf(0) : recutDto.getSegmentNoLength();
                            BigDecimal xiShu = BigDecimal.valueOf(Double.parseDouble(item.getValue()));
                            eapCutCraftDto.setTheoryWeight(lineLength.divide(xiShu, 2, BigDecimal.ROUND_HALF_UP));
                        }
                        List<ProductionPaintingLineDetailDto> paintingLineDetailList = JSONObject.parseArray(JSONObject.toJSONString(result1.getData()), ProductionPaintingLineDetailDto.class);
                        if (paintingLineDetailList != null) {
                            //晶棒长度
                            eapCutCraftDto.setRoundLength(recutDto.getSegmentNoLength());
                            eapCutCraftDto.setReverseNum(recutDto.getCutNum() != null && isInteger(recutDto.getCutNum()) ? Integer.parseInt(recutDto.getCutNum()) : 0);
                            int sliceNum = 0;
                            int knifeNum = 0;
                            eapCutCraftDto.setLineNum(paintingLineDetailList.size());
                            for (ProductionPaintingLineDetailDto productionPaintingLineDetailDto : paintingLineDetailList) {
                                if (productionPaintingLineDetailDto.getType() != null && productionPaintingLineDetailDto.getType() == 1) {
                                    sliceNum++;
                                }
                                if (productionPaintingLineDetailDto.getType() != null && productionPaintingLineDetailDto.getType() == 0) {
                                    knifeNum++;
                                }
                            }
                            eapCutCraftDto.setKnifeNum(knifeNum);
                            eapCutCraftDto.setSliceNum(sliceNum);
                            eapCutCraftDto.setCause(recutDto.getReason());
                            eapCutCraftDto.setIsCut(0);
                        }
                    }
                }
            }
            //查询圆棒返切记录
            if (!matching) {
                Result resultBackCuttingRecord = ybFeignClients.getProductionBackCuttingRecord(eapCutCraftDto.getRoundSn());
                if (resultBackCuttingRecord != null && resultBackCuttingRecord.getCode() == ResultCode.SUCCESS.getCode()) {
                    ProductionBackCuttingRecordDto backCuttingRecordDto = JSONObject.parseObject(JSONObject.toJSONString(resultBackCuttingRecord.getData()), ProductionBackCuttingRecordDto.class);
                    if (backCuttingRecordDto != null) {
                        matching = true;
                        Result result1 = ybFeignClients.getProductionPaintingLineDetail(backCuttingRecordDto.getId(), 2);
                        if (result1 != null && result1.getCode() == ResultCode.SUCCESS.getCode()) {
//                            Result inspectDataBaseDtoResult = ybFeignClients.getInspectDataBaseBySectionNo(eapCutCraftDto.getRoundSn());
//                            if (inspectDataBaseDtoResult != null  && inspectDataBaseDtoResult.getCode() == ResultCode.SUCCESS.getCode()){
//                                InspectDataBaseDto inspectDataBaseDto = JSONObject.parseObject(JSONObject.toJSONString(inspectDataBaseDtoResult.getData()), InspectDataBaseDto.class);
//                                if (inspectDataBaseDto != null) {
//                                    eapCutCraftDto.setTheoryWeight(inspectDataBaseDto.getTheoryWeight());
//                                }
//                            }
                            if (item != null) {
                                BigDecimal lineLength = backCuttingRecordDto.getBarLength() == null ? BigDecimal.valueOf(0) : backCuttingRecordDto.getBarLength();
                                BigDecimal xiShu = BigDecimal.valueOf(Double.parseDouble(item.getValue()));
                                eapCutCraftDto.setTheoryWeight(lineLength.divide(xiShu, 2, BigDecimal.ROUND_HALF_UP));
                            }

                            List<ProductionPaintingLineDetailDto> paintingLineDetailList = JSONObject.parseArray(JSONObject.toJSONString(result1.getData()), ProductionPaintingLineDetailDto.class);
                            if (paintingLineDetailList != null) {
                                //晶棒长度
                                eapCutCraftDto.setRoundLength(backCuttingRecordDto.getBarLength());
                                eapCutCraftDto.setReverseNum(backCuttingRecordDto.getKnifeNum());
                                int sliceNum = 0;
                                int knifeNum = 0;
                                if (paintingLineDetailList != null) {
                                    eapCutCraftDto.setLineNum(paintingLineDetailList.size());
                                    for (ProductionPaintingLineDetailDto productionPaintingLineDetailDto : paintingLineDetailList) {
                                        if (productionPaintingLineDetailDto.getType() != null && productionPaintingLineDetailDto.getType() == 1) {
                                            sliceNum++;
                                        }
                                        if (productionPaintingLineDetailDto.getType() != null && productionPaintingLineDetailDto.getType() == 0) {
                                            knifeNum++;
                                        }
                                    }
                                }
                                eapCutCraftDto.setKnifeNum(knifeNum);
                                eapCutCraftDto.setSliceNum(sliceNum);
                                eapCutCraftDto.setCause(backCuttingRecordDto.getCause());
                                eapCutCraftDto.setIsCut(0);
                            }
                        }
                    }
                }
            }
            //查询圆棒画线记录
            if (!matching) {
                eapCutCraftDto.setIsCut(1);
                //圆棒画线记录
                Result result = ybFeignClients.getProductionPaintingLine(eapCutCraftDto.getRoundSn());
                if (result != null && result.getCode() == ResultCode.SUCCESS.getCode()) {
                    ProductionPaintingLineDto productionPaintingLine = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), ProductionPaintingLineDto.class);
                    if (productionPaintingLine != null) {

                        if (item != null) {
                            BigDecimal lineLength = productionPaintingLine.getValidLength() == null ? BigDecimal.valueOf(0) : productionPaintingLine.getValidLength();
                            BigDecimal xiShu = BigDecimal.valueOf(Double.parseDouble(item.getValue()));
                            eapCutCraftDto.setTheoryWeight(lineLength.divide(xiShu, 2, BigDecimal.ROUND_HALF_UP));
                        }
                        eapCutCraftDto.setRoundLength(productionPaintingLine.getValidLength());
                        int SliceNum = 0;
                        Result result1 = ybFeignClients.getProductionPaintingLineDetail(productionPaintingLine.getId(), 1);
                        if (result1 != null && result1.getCode() == ResultCode.SUCCESS.getCode()) {
                            List<ProductionPaintingLineDetailDto> paintingLineDetailList = JSONObject.parseArray(JSONObject.toJSONString(result1.getData()), ProductionPaintingLineDetailDto.class);
                            if (paintingLineDetailList != null) {
                                eapCutCraftDto.setNormalNum(paintingLineDetailList.size() - 1);
                                for (ProductionPaintingLineDetailDto paintingLineDetail : paintingLineDetailList) {
                                    if (paintingLineDetail.getType() != null && paintingLineDetail.getType() == 1) {
                                        SliceNum++;
                                    }
                                }
                                eapCutCraftDto.setLineNum(paintingLineDetailList.size());
                            }
                        }
                        eapCutCraftDto.setKnifeNum(productionPaintingLine.getLineNum());
                        eapCutCraftDto.setSliceNum(SliceNum);

                    }
                }
            }
        }

        if (obj != null) {
            BeanUtils.copyProperties(eapCutCraftDto, obj, BeanUtil.getIgnoreProperties(eapCutCraftDto, "id", null));
            obj.setIsAuto(isAuto);
            this.saveOrUpdate(obj);
        } else {
            EapCutCraft eapCutCraft = fromDto(eapCutCraftDto);
            eapCutCraft.setCreatedTime(new Date());
            eapCutCraft.setIsAuto(isAuto);
            this.saveOrUpdate(eapCutCraft);
        }

        return ResultGenerator.success("接收完成");
    }

    /**
     * 判断字符串是否是整数
     */
    private boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public EapCutCraft fromDto(EapCutCraftDto dto) {
        return modelMapper.map(dto, EapCutCraft.class);
    }

    public TurnStoreOtherDto toLazyDto(Map entity) {
        return modelMapper.map(entity, TurnStoreOtherDto.class);
    }
}
