package com.sw.mes.inspect.controller;

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.SwitchConfig;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.dto.ErrorClosePlanProcessingOrderDto;
import com.sw.mes.base.workinprocess.dto.PlanProcessingOrderDto;
import com.sw.mes.core.dto.PushSapAndStoreDto;
import com.sw.mes.core.dto.PushSapDto;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.RankResultDto;
import com.sw.mes.core.dto.YbInspectDataToMcsDto;
import com.sw.mes.core.dto.mes.pc.yb.YbInspectDataDto;
import com.sw.mes.core.entity.CrystalLossRecord;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
import com.sw.mes.core.enums.SeedMassageEnum;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.*;
import com.sw.mes.dingTalk.service.DingTalkService;
import com.sw.mes.inspect.dto.*;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.entity.YbInspectDataLog;
import com.sw.mes.inspect.entity.YbOemData;
import com.sw.mes.inspect.service.YbInspectDataLogService;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.inspect.service.YbOemDataService;
import com.sw.mes.yb.mcs.event.EventPublishService;
import com.sw.mes.yb.mcs.event.RankResultEvent;
import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
import com.sw.mes.yb.pad.entity.SectionNoDetail;
import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
import com.sw.mes.yb.pad.service.SectionNoDetailService;
import com.sw.mes.yb.pc.dto.DataInspectLogDto;
import com.sw.mes.yb.pc.dto.ExportDataBaseDto;
import com.sw.mes.yb.pc.dto.GetFbInfoDto;
import com.sw.mes.yb.pc.dto.ImportGrade;
import com.sw.mes.yb.pc.entity.DataInspectLog;
import com.sw.mes.yb.plan.entity.PlanWaterLineManageRecord;
import com.sw.mes.yb.plan.service.PlanWaterLineManageService;
import com.sw.mes.yb.production.entity.LongCrystal;
import com.sw.mes.yb.production.service.LongCrystalService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.sw.mes.base.global.GlobalSwitchNamespace.NAMESPACE_COMMON_SWITCH;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/ybInspectData")
@Slf4j
@Api(description = "圆棒检验数据库接口")
public class YbInspectDataController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private PlanWaterLineManageService planWaterLineManageService;

    @Autowired
    private YbOemDataService ybOemDataService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    @Qualifier("eventPublishService")
    private EventPublishService publishService;

    @Autowired
    private DingTalkService dingTalkService;

    @ApiOperation(value = "分页查询圆棒检验数据库列表（只有最新数据）")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "search_EQ_inspector", value = "检验人员", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "晶段编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_crystalNo", value = "单晶编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_GTE_createTime", value = "检验开始时间", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_LTE_createTime", value = "检验结束时间", dataType = "String", paramType = "query"),})
    @GetMapping("/listByPage")
    public Result<ResponsePage<YbInspectDataDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<YbInspectData> specification = DynamicSpecifications.bySearchFilter(request, YbInspectData.class);
        Page<YbInspectData> page = ybInspectDataService.findByExample(specification, PageUtil.createPageable(requestPage));
        Integer userId = BaseContextHandler.getUserID();
        SwitchConfig config = GlobalSwitch.switchConfig(NAMESPACE_COMMON_SWITCH, "edit", false);
        List<YbInspectDataDto> dtos = page.getContent().stream().map(entity -> {
            YbInspectDataDto newDto = toLazyDto(entity);
            if (config != null && config.isEnable() && userIdSet(config.getValue()).contains(userId)) {
                newDto.setEdit(true);
            }
            return newDto;
        }).collect(Collectors.toList());
        ResponsePage<YbInspectDataDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    private Set<Integer> userIdSet(String value) {
        if (StringUtils.isEmpty(value)) {
            return Collections.emptySet();
        }
        return Arrays.stream(value.split(",")).map(Integer::parseInt).collect(Collectors.toSet());

    }

    @ApiOperation(value = "分页查询圆棒检验数据库列表（携带历史数据）")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "search_EQ_inspector", value = "检验人员", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "晶段编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_crystalNo", value = "单晶编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_GTE_createTime", value = "检验开始时间", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_LTE_createTime", value = "检验结束时间", dataType = "String", paramType = "query"),})
    @GetMapping("/listByPageAndLog")
    public Result<ResponsePage<YbInspectDataDto>> listByPageAndLog(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<YbInspectData> specification = DynamicSpecifications.bySearchFilter(request, YbInspectData.class);
        Page<YbInspectData> page = ybInspectDataService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<YbInspectDataDto> dtos = page.getContent().stream().map(this::toLazyDtoLog).collect(Collectors.toList());
        ResponsePage<YbInspectDataDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }


    @ApiOperation(value = "导出圆棒检验数据库")
    @ApiImplicitParams({@ApiImplicitParam(name = "search_LIKE_ybSectionNo", value = "圆棒编号", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_fbSectionNo", value = "方棒编号", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_EQ_checkUserName", value = "检验人员", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "晶棒编号", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_GTE_checkTime", value = "检验开始时间", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "search_LTE_checkTime", value = "检验结束时间", dataType = "String", paramType = "query"),})
    @GetMapping("/export")
    public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
        try {
            Specification<YbInspectData> specification = DynamicSpecifications.bySearchFilter(request, YbInspectData.class);
            Page<YbInspectData> page = ybInspectDataService.findByExample(specification, PageUtil.createPageable(requestPage));
            List<ExportDataBaseDto> dtos = page.getContent().stream().map(entity -> toExportDto(entity)).collect(Collectors.toList());
            for (ExportDataBaseDto dto : dtos) {
                if (StringUtils.isNotBlank(dto.getKube()) && dto.getKube().equals("0")) {
                    dto.setKube("正常");
                }
                if (StringUtils.isNotBlank(dto.getKube()) && dto.getKube().equals("1")) {
                    dto.setKube("直径不良单晶");
                }
                if (StringUtils.isNotBlank(dto.getKube()) && dto.getKube().equals("2")) {
                    dto.setKube("退料");
                }
            }
            EasyExcelUtils.write(response, YbInspectDataDto.class, "导出圆棒检验数据库", "导出圆棒检验数据库", dtos);
        } catch (Exception e) {
            throw new RuntimeException("方棒拼棒记录导出失败，错误信息：" + e.getMessage());
        }
    }

    /**
     * 晶段编号、规格、产品等级、实验等级
     *
     * @param file
     */
    @ApiOperation(value = "导入")
    @PostMapping("/import")
    public Result importGrade(MultipartFile file) {
        Object objList = EasyExcelUtils.readExcel(file, new ImportGrade(), 1, 1);
        if (objList != null) {
            List<ImportGrade> importGrades = (List<ImportGrade>) objList;
            StringBuilder failMessage = new StringBuilder();
            int successCount = 0, failCount = 0;
            for (ImportGrade importGrade : importGrades) {
                YbInspectData inspectDataBase = ybInspectDataService.findBySectionNo(importGrade.getSectionNo());
                try {
                    if (inspectDataBase != null) {
                        DataInspectLog dataInspectLog = new DataInspectLog();
                        BeanUtils.copyProperties(inspectDataBase, dataInspectLog, BeanUtil.getIgnoreProperties(inspectDataBase, "id", null));
                        dataInspectLog.setOperateTime(new Date());
                        dataInspectLog.setOperator(BaseContextHandler.getUsername());
                        dataInspectLog.setOperateType(1);
                        dataInspectLog.setRemarks(BaseContextHandler.getUsername() + "导入评级，数据变动");
                        BeanUtils.copyProperties(importGrade, inspectDataBase, BeanUtil.getIgnoreProperties(importGrade, null, null));
                        ybInspectDataService.saveAndLog(inspectDataBase, dataInspectLog);
                        successCount++;
                    } else {
                        failMessage.append(importGrade.getSectionNo()).append("导入失败【 检验信息不存在 】\\n");
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                    failMessage.append(importGrade.getSectionNo()).append("导入失败【").append(e.getMessage()).append("】；\\n");
                }
                successCount++;
            }
            if (successCount > 0) {
                return ResultGenerator.success("共【" + successCount + failCount + "】条，成功【" + successCount + "】条；\\n"
                        + "失败【" + failCount + "】：" + failMessage);
            } else {
                return ResultGenerator.fail("共【" + successCount + failCount + "】条，全部失败：" + failMessage);
            }
        } else {
            return ResultGenerator.fail("导入数据为空");
        }
    }

    @ApiOperation(value = "导入圆棒检验数据")
    @PostMapping("/resultsImport")
    public Result resultsImport(MultipartFile file) {

        try {
            Result result = ybInspectDataService.readResultsImportMk(file);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "获取所有圆棒检验数据库")
    @GetMapping("/listAll")
    public Result<List<YbInspectDataDto>> listAll(ServletRequest request) {
        Specification<YbInspectData> specification = DynamicSpecifications.bySearchFilter(request, YbInspectData.class);
        List<YbInspectData> inspectDataBases = ybInspectDataService.findByExampleSort(specification, null);
        List<YbInspectDataDto> inspectDataBaseDtos = inspectDataBases.stream().map(inspectDataBase -> toLazyDto(inspectDataBase)).collect(Collectors.toList());
        return ResultGenerator.success(inspectDataBaseDtos);
    }

    @ApiOperation(value = "根据检验数据库ID获取  圆棒检验数据库详细信息")
    @GetMapping("/{id}")
    public Result<YbInspectDataDto> get(@PathVariable @ApiParam(value = "InspectDataBaseid") Long id) {
        YbInspectData inspectDataBase = ybInspectDataService.get(id);
        if (null == inspectDataBase) {
            return ResultGenerator.fail("该InspectDataBase不存在");
        }
        YbInspectDataDto ybInspectDataDto = toEagerDto(inspectDataBase);
        ProductionPaintingLineDetail bySegmentNo = productionPaintingLineDetailService.findBySegmentNo(inspectDataBase.getSectionNo());
        if (null != bySegmentNo) {
            ybInspectDataDto.setUnmodifiedLength(bySegmentNo.getLength());
        }
        return ResultGenerator.success(ybInspectDataDto);
    }

    @ApiOperation(value = "根据检验数据库ID获取  圆棒检验数据库详细信息")
    @PostMapping("/getInspectDataById")
    public Result<YbInspectDataDto> getInspectDataById(@RequestParam @ApiParam(value = "InspectDataBaseid") Long id) {
        YbInspectData inspectDataBase = ybInspectDataService.get(id);
        if (null == inspectDataBase) {
            return ResultGenerator.fail("该InspectDataBase不存在");
        }
        YbInspectDataDto ybInspectDataDto = toEagerDto(inspectDataBase);
        ProductionPaintingLineDetail bySegmentNo = productionPaintingLineDetailService.findBySegmentNo(inspectDataBase.getSectionNo());
        if (null != bySegmentNo) {
            ybInspectDataDto.setUnmodifiedLength(bySegmentNo.getLength());
        }
        return ResultGenerator.success(ybInspectDataDto);
    }

    @ApiOperation(value = "接收MCS的编号查询检验数据")
    @PostMapping("/bySectionList")
    public Result<List<YbInspectData>> getData(@RequestBody List<String> sectionNos) {
        List<YbInspectData> dataList = new ArrayList<>();
        if (null != sectionNos && sectionNos.size() > 0) {
            for (String sectionNo : sectionNos) {
                YbInspectData inspectDataBase = ybInspectDataService.findBySectionNo(sectionNo);
                if (null == inspectDataBase) {
                    continue;
                }
//                PlanWaterLineManageRecord planWaterLineManageRecord = planWaterLineManageService.selectOneOrder(inspectDataBase.getDopant(), inspectDataBase.getConductiveType(), inspectDataBase.getProductTypeSecond(), inspectDataBase.getProductType());
                PlanWaterLineManageRecord planWaterLineManageRecord = null;
                planWaterLineManageRecord = getPlanWaterLineManageRecord(inspectDataBase, planWaterLineManageRecord);
                if (null != planWaterLineManageRecord) {
                    inspectDataBase.setOrderNo(planWaterLineManageRecord.getAufnr());
                } else {
                    inspectDataBase.setOrderNo(null);
                }
                dataList.add(inspectDataBase);
            }
        }
        if (null == dataList) {
            return ResultGenerator.fail("检验数据不存在");
        }
        return ResultGenerator.success(dataList);
    }

    public PlanWaterLineManageRecord getPlanWaterLineManageRecord(YbInspectData inspectDataBase, PlanWaterLineManageRecord planWaterLineManageRecord) {
        BigDecimal tRadialCentre = inspectDataBase.getWRadialCentre();
        String resLevel = ybInspectDataService.getResistanceLevel(tRadialCentre);

        List<PlanWaterLineManageRecord> planWaterLineManageRecords = planWaterLineManageService.selectAllOrder(inspectDataBase.getDopant(), inspectDataBase.getConductiveType(), inspectDataBase.getProductTypeSecond(), "%" + inspectDataBase.getProductLevel() + "%", "%" + resLevel + "%", inspectDataBase.getSideLengthRange());
        if (null != planWaterLineManageRecords && planWaterLineManageRecords.size() > 0) {
            for (PlanWaterLineManageRecord waterLineManageRecord : planWaterLineManageRecords) {
                String productType = inspectDataBase.getProductType();
                String[] split = waterLineManageRecord.getProductType().split(",");
                for (String s : split) {
                    if (s.equals(productType)) {
                        planWaterLineManageRecord = waterLineManageRecord;
                        break;
                    }
                }
            }
        }
        return planWaterLineManageRecord;
    }

    @ApiOperation(value = "接收MCS的编号查询数据用于圆棒平库")
    @PostMapping("/getPinkuData")
    public Result<List<YbInspectDataToMcsDto>> getPinkuData(@RequestBody List<String> sectionNos) {
        List<YbInspectDataToMcsDto> ybInspectDataToMcsDtos = new ArrayList<>();
        if (null != sectionNos && sectionNos.size() > 0) {
            for (String sectionNo : sectionNos) {
                YbInspectData inspectDataBase = ybInspectDataService.findBySectionNo(sectionNo);
                if (null == inspectDataBase) {
                    continue;
                }
                YbInspectDataToMcsDto pinKuData = ybInspectDataService.getPinKuData(inspectDataBase, null);
//                PlanWaterLineManageRecord planWaterLineManageRecord = planWaterLineManageService.selectOneOrder(inspectDataBase.getDopant(), inspectDataBase.getConductiveType(), inspectDataBase.getProductTypeSecond(), inspectDataBase.getProductType());
                PlanWaterLineManageRecord planWaterLineManageRecord = null;
                planWaterLineManageRecord = getPlanWaterLineManageRecord(inspectDataBase, planWaterLineManageRecord);
                if (null != planWaterLineManageRecord) {
                    pinKuData.setOrderNo(planWaterLineManageRecord.getAufnr());
                } else {
                    pinKuData.setOrderNo(null);
                }
                ybInspectDataToMcsDtos.add(pinKuData);
            }
        }
        if (null == ybInspectDataToMcsDtos) {
            return ResultGenerator.fail("检验数据不存在");
        }
        if (null != ybInspectDataToMcsDtos && ybInspectDataToMcsDtos.size() > 0) {
            return ResultGenerator.success(ybInspectDataToMcsDtos);
        }
        return ResultGenerator.fail("未查到检验数据");
    }


    @ApiOperation(value = "MCS调用，查询圆棒数据（评级）用于圆棒平库")
    @PostMapping("/ratingResult")
    public Result<RankResultDto> getYbDataForPinku(@RequestBody ToMesDataDefault toMesDataDefault) {

        RankResultDto rankResultDto = new RankResultDto();
        if (null == toMesDataDefault || toMesDataDefault.getSectionNo() == null) {
            return ResultGenerator.fail("入参不能为空！");
        }

        YbInspectData inspectDataBase = ybInspectDataService.findBySectionNo(toMesDataDefault.getSectionNo());
        if (null == inspectDataBase) {
            return ResultGenerator.fail("检验数据不存在");
        }
        YbInspectDataToMcsDto pinKuData = ybInspectDataService.getPinKuData(inspectDataBase, null);
//        PlanWaterLineManageRecord planWaterLineManageRecord = planWaterLineManageService.selectOneOrder(inspectDataBase.getDopant(), inspectDataBase.getConductiveType(), inspectDataBase.getProductTypeSecond(), inspectDataBase.getProductType());
        PlanWaterLineManageRecord planWaterLineManageRecord = null;
        planWaterLineManageRecord = getPlanWaterLineManageRecord(inspectDataBase, planWaterLineManageRecord);
        if (null != planWaterLineManageRecord) {
//            pinKuData.setOrderNo(planWaterLineManageRecord.getAufnr());
            pinKuData.setWaterLineManageOrderNo(planWaterLineManageRecord.getAufnr());
        } else {
            pinKuData.setOrderNo(null);
        }
        //rankResultDto赋值
        rankResultDto.setSectionNo(inspectDataBase.getSectionNo());
        rankResultDto.setSticksCount(inspectDataBase.getSticksCount());
        rankResultDto.setActualLength(inspectDataBase.getActualLength());
        rankResultDto.setCrystalNo(inspectDataBase.getCrystalNo());
        rankResultDto.setActualWeight(inspectDataBase.getActualWeight());
        rankResultDto.setDiameterMin(inspectDataBase.getDiameterMin());
        rankResultDto.setDiameterMax(inspectDataBase.getDiameterMax());
        rankResultDto.setSpecs(inspectDataBase.getProductTypeSecond());
        rankResultDto.setData(inspectDataBase.getSectionType());
//        rankResultDto.setDiameterJudge();
        rankResultDto.setDistortion(inspectDataBase.getDistortion());
        rankResultDto.setIsBevel(inspectDataBase.getIsBevel().toString());
//        rankResultDto.setFineDiameter();
//        rankResultDto.setFineCutLength();
        rankResultDto.setPiecewiseNum(inspectDataBase.getPiecewiseNum());
        rankResultDto.setAgainNum(inspectDataBase.getAgainNum());
        rankResultDto.setHeadTailRecognition(inspectDataBase.getHeadTailRecognition());
//        rankResultDto.setIsSeeBottom();
//        rankResultDto.setLineMarking();
        rankResultDto.setIsCutBack(inspectDataBase.getIsCutBack());
        if (null != planWaterLineManageRecord && !StringUtils.isEmpty(planWaterLineManageRecord.getAufnr())) {
            rankResultDto.setWaterLineManageOrderNo(planWaterLineManageRecord.getAufnr());
        }

        rankResultDto.setProductRank(inspectDataBase.getProductLevel());
        rankResultDto.setTestRank(inspectDataBase.getProductLevelExperiment());
        rankResultDto.setType(inspectDataBase.getSectionType());
        rankResultDto.setConductiveType(inspectDataBase.getConductiveType());

        Integer sticksCount = inspectDataBase.getSticksCount();
        BigDecimal actualLength = (sticksCount != null && sticksCount.compareTo(1) > 0) ? inspectDataBase.getSpellBarLength() : inspectDataBase.getActualLength();
        rankResultDto.setGradeType(inspectDataBase.getGradeType());
        rankResultDto.setLength(actualLength);
        rankResultDto.setCrystalLength(actualLength);

        rankResultDto.setYbInspectDataToMcsDto(pinKuData);

        //圆棒评级下发MCS信息中字段gradeType和type根据数据字典映射转换
//        changeTypeForMcs(rankResultDto);
        return ResultGenerator.success(rankResultDto);
    }


    /**
     * 圆棒评级下发MCS信息中字段gradeType和type根据数据字典映射转换
     *
     * @param rankResultDto
     */
    void changeTypeForMcs(RankResultDto rankResultDto) {
        List<DictionaryItem> itemList = dictionaryItemService.findItemByThemeValue("gradeTypeToType", true);
        Map<String, String> weightCoefficient = itemList.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue));
        String type = weightCoefficient.get(rankResultDto.getGradeType());
        DictionaryItem item = dictionaryItemService.findByThemeValueAndNameAndEnable("standedLength", "标棒最小长度", true);
        BigDecimal standedLength = new BigDecimal(item.getValue());
        if (null != rankResultDto.getGradeType() && rankResultDto.getGradeType().equals("正常") && null != rankResultDto.getActualLength()) {
            if (rankResultDto.getActualLength().compareTo(standedLength) >= 0) {
                rankResultDto.setType("标棒");
            } else {
                rankResultDto.setType("非标棒");
            }
        } else if (!rankResultDto.getGradeType().equals("正常")) {
            rankResultDto.setType(type);
        }
        if (!"外观反切".equals(rankResultDto.getGradeType())) {
            Boolean aBoolean = productionPaintingLineDetailService.flowDirectionV2(rankResultDto.getCrystalNo(), rankResultDto.getSectionNo(), "mcs请求评级结果");
            if (aBoolean) {
                rankResultDto.setType("完结尾");
            }
        }
    }


    @Autowired
    private SectionNoDetailService sectionNoDetailService;
    @Autowired
    private LongCrystalService longCrystalService;

    @ApiOperation(value = "根据晶段编号获取 圆棒检验数据库详细信息")
    @GetMapping("/getYbInspectDataDto/{sectionNo}")
    public Result<YbInspectDataCUDto> getYbInspectDataDto(@PathVariable @ApiParam(value = "sectionNo") String sectionNo) {
        sectionNo = StringUtils.trim(sectionNo);

        wipStorageService.selectWipStorage(sectionNo, EnumValuesFactory.WipStorageCode.圆棒检验.getKey(), false);

        YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(sectionNo);
        if (null == ybInspectData) {
            ybInspectData = new YbInspectData();
            // 通过圆棒编号 去追溯表判断晶段是否存在
            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);
            if (sectionNoDetail == null) {
                return ResultGenerator.fail(sectionNo + "晶段信息不存在，数据异常");
            }
            LongCrystal longCrystal = longCrystalService.get(sectionNoDetail.getCrystalId());
            if (longCrystal == null) {
                return ResultGenerator.fail(sectionNo + "长棒信息不存在，数据异常");
            }
            ybInspectData.setSectionNo(sectionNo);
            ybInspectData.setDiameterMax(longCrystal.getMaxDiam());
            ybInspectData.setDiameterMin(longCrystal.getMinDiam());
            ybInspectDataService.initInspectData(ybInspectData, sectionNoDetail, longCrystal);
        }

        YbInspectDataCUDto ybInspectDataCuDto = new YbInspectDataCUDto();
        BeanUtil.copyBeanPropWithNullValue(ybInspectDataCuDto, ybInspectData, "id");
        return ResultGenerator.success(ybInspectDataCuDto);
    }

    @ApiOperation(value = "根据晶段编号获取 圆棒检验数据库详细信息")
    @RequestMapping(value = "/getYbInspectData", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<YbInspectDataCUDto> getYbInspectData(String sectionNo) {
        sectionNo = StringUtils.trim(sectionNo);
        YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(sectionNo);
        YbInspectDataCUDto ybInspectDataCuDto = new YbInspectDataCUDto();
        BeanUtil.copyBeanPropWithNullValue(ybInspectDataCuDto, ybInspectData, "id");
        return ResultGenerator.success(ybInspectDataCuDto);
    }


    @ApiOperation(value = "（激光刻码掺杂剂规格查询接口）根据晶段编号获取对应长晶棒详细信息")
    @PostMapping("/getLongCrystalBySectionNo")
    public Result<LongCrystal> getLongCrystal(@RequestBody @ApiParam(value = "晶段编号") MCSQuerryParam mcsQuerryParam) {
        if (mcsQuerryParam == null || StringUtils.isEmpty(mcsQuerryParam.getSectionNo())) {
            throw new RuntimeException("晶段编号不能为空！");
        }
        String sectionNo = StringUtils.trim(mcsQuerryParam.getSectionNo());
        if (sectionNo.length() < 13) {
            throw new RuntimeException("晶段编号格式不正确！");
        }
        LongCrystal longCrystal = null;
        String fromMark = sectionNo.substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
        if (fromMark.matches("[A-Z]+")) {
            longCrystal = longCrystalService.findByCrystalNo2(sectionNo.substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
        } else {
            longCrystal = longCrystalService.findByCrystalNo2(sectionNo.substring(0, 12));
        }
        if (longCrystal == null) {
            return ResultGenerator.fail(sectionNo + "长棒信息不存在，数据异常");
        }
//        wipStorageService.selectWipStorage(sectionNo, EnumValuesFactory.WipStorageCode.圆棒检验.getKey(), false);
//        YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(sectionNo);
//        if (null == ybInspectData) {
//            ybInspectData = new YbInspectData();
//            // 通过圆棒编号 去追溯表判断晶段是否存在
//            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);
//            if (sectionNoDetail == null) {
//                return ResultGenerator.fail(sectionNo + "晶段信息不存在，数据异常");
//            }
//            LongCrystal longCrystal = longCrystalService.get(sectionNoDetail.getCrystalId());
//            if (longCrystal == null) {
//                return ResultGenerator.fail(sectionNo + "长棒信息不存在，数据异常");
//            }
//            ybInspectData.setSectionNo(sectionNo);
//            ybInspectData.setDiameterMax(longCrystal.getMaxDiam());
//            ybInspectData.setDiameterMin(longCrystal.getMinDiam());
//            ybInspectDataService.initInspectData(ybInspectData, sectionNoDetail, longCrystal);
//        }
//        YbInspectDataCUDto ybInspectDataCuDto = new YbInspectDataCUDto();
//        BeanUtil.copyBeanPropWithNullValue(ybInspectDataCuDto, ybInspectData, "id");
        return ResultGenerator.success(longCrystal);
    }


    @ApiOperation(value = "创建圆棒检验数据库")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "InspectDataBase对象") YbInspectDataCUDto ybInspectDataCUDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        Result result = ybInspectDataService.saveYbInspectDataNew(ybInspectDataCUDto);
        seedMessage(ybInspectDataCUDto, result);
        return result;
    }

    private void seedMessage(YbInspectDataCUDto ybInspectDataCUDto, Result result) {
        if (result.getCode() == 200 && null != ybInspectDataCUDto.getFissureLength() && ybInspectDataCUDto.getFissureLength() > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append("[MES推送]");
            sb.append("\n");
            sb.append("晶棒条码:" + ybInspectDataCUDto.getSectionNo());
            sb.append("\n");
            sb.append("线体编号:" + ybInspectDataCUDto.getCheckLineNo());
            sb.append("\n");
            sb.append("检测时间:" + ybInspectDataCUDto.getInspectionDate());
            sb.append("\n");
            sb.append("距头位置:" + ybInspectDataCUDto.getFissurePosition());
            sb.append("\n");
            sb.append("隐裂长度:" + ybInspectDataCUDto.getFissureLength());
            sb.append("\n");
            String source = "隐裂长度大于0推送";
            ArrayList<String> sceneList = new ArrayList<>();
            ArrayList<String> groupNameList = new ArrayList<>();
            sceneList.add("prod");
            groupNameList.add("隐裂长度大于0推送");
            dingTalkService.robotSeedMessage(String.valueOf(sb), groupNameList, source, sceneList, SeedMassageEnum.GROUP);
        }
    }

    @ApiOperation(value = "评级结果下发测试接口")
    @PostMapping("/testGrade")
    public Result testGrade(@RequestBody @Valid @ApiParam(value = "InspectDataBase对象") RankResultDto rankResultDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        publishService.publishEvent(new RankResultEvent(this, rankResultDto));
        return ResultGenerator.success("ok");
    }

    @ApiOperation(value = "更新圆棒检验数据库")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "InspectDataBase") YbInspectDataCUDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        //更新添加卡控
        wipStorageService.selectWipStorage(dto.getSectionNo(), EnumValuesFactory.WipStorageCode.圆棒检验.getKey(), true);
        try {
            Result result = ybInspectDataService.saveYbInspectData(dto);
            seedMessage(dto, result);
            return ResultGenerator.success(result);
        } catch (Exception e) {
            log.error("error in yb_inspect_data update:" + dto.getId(), e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "更新圆棒检验数据库")
    @PostMapping("/update/line")
    public Result updateLine(@RequestBody @Valid @ApiParam(value = "InspectDataBase") YbInspectDataDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        try {
            YbInspectData ybInspectData = fromDto(dto);
            ybInspectDataService.saveOrUpdate(ybInspectData);
            updateSeedMessage(ybInspectData);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    private void updateSeedMessage(YbInspectData ybInspectData) {
        if (null != ybInspectData.getFissureLength() && ybInspectData.getFissureLength() > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append("[MES推送]");
            sb.append("\n");
            sb.append("晶棒条码:" + ybInspectData.getSectionNo());
            sb.append("\n");
            sb.append("线体编号:" + ybInspectData.getCheckLineNo());
            sb.append("\n");
            sb.append("检测时间:" + ybInspectData.getInspectionDate());
            sb.append("\n");
            sb.append("距头位置:" + ybInspectData.getFissurePosition());
            sb.append("\n");
            sb.append("隐裂长度:" + ybInspectData.getFissureLength());
            sb.append("\n");
            String source = "隐裂长度大于0推送";
            ArrayList<String> sceneList = new ArrayList<>();
            ArrayList<String> groupNameList = new ArrayList<>();
            sceneList.add("prod");
            groupNameList.add("隐裂长度大于0推送");
            dingTalkService.robotSeedMessage(String.valueOf(sb), groupNameList, source, sceneList, SeedMassageEnum.GROUP);
        }
    }


    @ApiOperation(value = "更新圆棒检验数据库的方棒边长字段")
    @PostMapping("/updateYbInspectDataSideLengthRange")
    public Result updateYbInspectDataSideLengthRange(@RequestBody @Valid @ApiParam(value = "YbInspectDataSideLengthUpdateDto") YbInspectDataSideLengthUpdateDto dto) {

        if (null == dto.getSectionNos()) {
            return ResultGenerator.fail("晶编不能为空！");
        }
        try {
            return ybInspectDataService.updateYbInspectDataSideLengthRange(dto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }


    /**
     * 圆棒检验数据库电阻率人工维护接口
     *
     * @param dto
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "圆棒检验数据库电阻率人工维护")
    @PostMapping("/updateResistivity")
    public Result updateResistivity(@RequestBody @Valid @ApiParam(value = "InspectDataBase") YbInspectDataCUDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        try {
            return ybInspectDataService.updateYbInspectResistivity(dto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除圆棒检验数据库")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            ybInspectDataService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "圆棒检验数据库详细信息")
    @GetMapping("/getInspectDataBaseBySectionNo")
    public Result<YbInspectDataDto> getInspectDataBaseBySectionNo(@RequestParam(value = "sectionNo") String sectionNo) {
        YbInspectData inspectDataBase = ybInspectDataService.findBySectionNo(sectionNo);
        if (inspectDataBase == null) {
            return ResultGenerator.fail("圆棒检验数据库数据不存在！");
        }
        YbInspectDataDto obj = modelMapper.map(inspectDataBase, YbInspectDataDto.class);
        return ResultGenerator.success(obj);
    }


    @ApiOperation(value = "圆棒检验数据库详细信息")
    @GetMapping("/getInspectDatasByCrystalNo")
    public Result<YbInspectDataDto> getInspectDatasByCrystalNo(@RequestParam(value = "sectionNo") String crystalNo) {
        List<YbInspectDataDto> ybInspectDataDtos = new ArrayList<>();
        List<YbInspectData> inspectDatas = ybInspectDataService.getInspectDatasByCrystalNo(crystalNo);
        if (inspectDatas == null || inspectDatas.size() == 0) {
            return ResultGenerator.fail("圆棒检验数据库数据不存在！");
        }
        for (YbInspectData inspectData : inspectDatas) {
            if (null != inspectData && !StringUtils.isEmpty(inspectData.getClosureIdentification()) &&
                    inspectData.getClosureIdentification().equals("是")) {

                YbInspectDataDto obj = modelMapper.map(inspectData, YbInspectDataDto.class);
                ybInspectDataDtos.add(obj);
            }
        }
        return ResultGenerator.success(ybInspectDataDtos.get(0));
    }


    @ApiOperation(value = "根据方棒编号圆棒检验数据库详细信息")
    @GetMapping("/accordSquareGetInspect")
    public Result<YbInspectDataDto> accordSquareGetInspect(@RequestParam(value = "sectionNo") String sectionNo) {
        YbInspectData inspectDataBase = ybInspectDataService.getSectionNo(sectionNo);
        if (inspectDataBase == null) {
            return ResultGenerator.fail("圆棒检验数据库数据不存在！");
        }
        YbInspectDataDto obj = modelMapper.map(inspectDataBase, YbInspectDataDto.class);
        return ResultGenerator.success(obj);
    }

    @ApiOperation(value = "通过圆棒编号获取圆棒检验信息")
    @GetMapping(value = "/findFbInfoByYbNo")
    public Result<GetFbInfoDto> findFbInfoByYbNo(@RequestParam String sectionNoYb) {
        return ybInspectDataService.findInfoByYbNo(sectionNoYb);
    }

    @ApiModelProperty("通过晶棒编号查询圆棒检验记录")
    @RequestMapping(value = "/getDataByCrystalNo", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<List<DataInspectLogDto>> getDataByCrystalNo(String crystalNo) {
        List<YbInspectData> list = ybInspectDataService.getDataByCrystalNo(crystalNo);
        if (null != list && list.size() > 0) {
            List<DataInspectLogDto> dtos = list.stream().map(this::toLazyDto1)
                    .collect(Collectors.toList());
            return ResultGenerator.success(dtos);
        }
        return ResultGenerator.success();
    }


    @ApiOperation(value = "导出 出入库记录Excel")
    @GetMapping("/exportExcel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        ybInspectDataService.exportExcel(request, resp);
    }

    @ApiOperation(value = "根据圆棒编号查询长晶棒信息")
    @GetMapping("/findBySectionNo")
    public Result<String> findBySectionNo(@RequestParam String sectionNo) {
        Integer isDone = ybInspectDataService.findLongCrystalByCrystalNo(sectionNo);
        if (isDone == 0) {
            return ResultGenerator.success("否");
        }
        return ResultGenerator.success("是");
    }

    public DataInspectLogDto toLazyDto1(YbInspectData entity) {
        DataInspectLogDto map = modelMapper.map(entity, DataInspectLogDto.class);
        return map;
    }

    @Autowired
    private YbInspectDataLogService ybInspectDataLogService;

    public YbInspectDataDto toLazyDto(YbInspectData entity) {
        return modelMapper.map(entity, YbInspectDataDto.class);
    }

    private YbInspectDataDto toLazyDtoLog(YbInspectData entity) {
        YbInspectDataDto dto = modelMapper.map(entity, YbInspectDataDto.class);
        YbInspectDataLog ybInspectDataLog = ybInspectDataLogService.findByInspectDataId(dto.getId());
        if (ybInspectDataLog != null) {
            dto.setYbInspectDataLogDtos(JSON.parseArray(ybInspectDataLog.getDataLog(), YbInspectDataDto.class));
        }
        return dto;
    }

    public ExportDataBaseDto toExportDto(YbInspectData entity) {
        return modelMapper.map(entity, ExportDataBaseDto.class);
    }

    public YbInspectDataDto toEagerDto(YbInspectData entity) {
        YbInspectDataDto dto = modelMapper.map(entity, YbInspectDataDto.class);
        return dto;
    }

    public YbInspectData fromDto(YbInspectDataDto dto) {
        return modelMapper.map(dto, YbInspectData.class);
    }


    @ApiOperation(value = "导入代工数据")
    @PostMapping("/oemImport")
    public Result oemImport(MultipartFile file) {

        try {
            Result result = ybOemDataService.readOemImport(file);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "分页查询代工数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_trayNo", value = "托盘编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "单晶编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "结束时间", dataType = "String", paramType = "query"),})
    @GetMapping("/oemListByPage")
    public Result<ResponsePage<YbOemDataDto>> oemListByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<YbOemData> specification = DynamicSpecifications.bySearchFilter(request, YbOemData.class);
        Page<YbOemData> page = ybOemDataService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<YbOemDataDto> dtos = page.getContent().stream().map(this::toYbOemDataDto).collect(Collectors.toList());
        ResponsePage<YbOemDataDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }


    @ApiOperation(value = "更新接收状态(只允许勾选未接收状态数据):0未接收 1已接收")
    @PostMapping("/updateStatus")
    public Result updateStatus(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids,
                               @ApiParam(value = "status 0未接收 1已接收", type = "query") @RequestParam Integer status) {

        ArrayList<YbInspectData> list = new ArrayList<>();
        for (Long id : ids) {
            YbOemData ybOemData = ybOemDataService.get(id);
            if (null == ybOemData) {
                return ResultGenerator.fail("Id:" + id + "数据不存在!");
            }
            if (0 != ybOemData.getStatus()) {
                return ResultGenerator.fail("Id:" + id + "数据不是未接收状态!");
            }
            ybOemDataService.updateStatus(id, 1);
            wipStorageService.oemOutStation(ybOemData.getSectionNo(), ybOemData.getTheoryWeight(), ybOemData.getActualLength());

            YbInspectData ybInspectData = fromYbOemData(ybOemData);
            ybInspectData.setCrystalNo(ybInspectData.getSectionNo());
            ybInspectData.setGradeType("正常");
            list.add(ybInspectData);
        }
        //写入圆棒检验数据库
        ybInspectDataService.saveAll(list);
        //进入开方待进站

        return ResultGenerator.success();
    }

    @ApiOperation(value = "检验预警管理")
    @GetMapping("/verificationManagement")
    public Result verificationManagement(@RequestParam String sectionNo) {
        try {
            Map<String, Object> bySectionNoMap = ybInspectDataService.findBySectionNoMap(sectionNo);
            ybInspectDataService.verificationManagement(bySectionNoMap);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "方棒上报SAP数据")
    @GetMapping("/sendSquareRodInfo")
    public Result sendSquareRodInfo(@RequestParam String fbSectionNo, @RequestParam String ybSectionNo, @RequestParam BigDecimal weight, @RequestParam String userName) {

        try {
            ybInspectDataService.sendSquareRodInfo(fbSectionNo, ybSectionNo, weight, userName);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "方棒上报SAP数据")
    @PostMapping("/sendSquareRodInfoList")
    public Result sendSquareRodInfoList(@RequestBody List<PushSapDto> list) {

        try {
            ybInspectDataService.sendSquareRodInfoList(list);
        } catch (Exception e) {
            log.error("error_in_sendSquareRodInfoList", e);
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "方棒上报SAP数据")
    @PostMapping("/sendSquareWriteOffAccounts")
    public Result sendSquareWriteOffAccounts(@RequestBody PushSapAndStoreDto pushSapAndStoreDto) {

        try {
            ybInspectDataService.sendSquareWriteOffAccounts(pushSapAndStoreDto.getPushSapDtoList(), pushSapAndStoreDto.getWarehouseOutputBillBo());
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation("异常完工工单恢复")
    @GetMapping("/recoverOrder")
    public Result<ResponsePage<ErrorClosePlanProcessingOrderDto>> errorProcessOrderListByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<PlanProcessingOrder> specification = DynamicSpecifications.bySearchFilter(request, PlanProcessingOrder.class);
        Page<PlanProcessingOrder> byExample = planProcessingOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
        //默认查询到的数据都是remarks包含：异常关闭原因的数据
        List<PlanProcessingOrderDto> dtos = byExample.getContent().stream().map(entity -> toLazyDto(entity)).collect(Collectors.toList());
        List<ErrorClosePlanProcessingOrderDto> planProcessingOrderDtos = ybInspectDataService.supplementaryData(dtos);
        ResponsePage responsePage = new ResponsePage(planProcessingOrderDtos, byExample.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "损耗报废校验")
    @GetMapping("/verifyScrapLoss")
    public Result findVerifyScrapLoss(@RequestParam String processName, @RequestParam BigDecimal lossLength, @RequestParam String sectionNo) {
        try {
            return ybInspectDataService.findVerifyScrapLoss(processName, lossLength, sectionNo);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "损耗录入处理记录")
    @PostMapping("/handleCrystalLossRecord")
    public Result handleCrystalLossRecord(@RequestBody CrystalLossRecord crystalLossRecord) {

        try {
            ybInspectDataService.handleCrystalLossRecord(crystalLossRecord);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据毛棒编号获取检验的电阻率")
    @GetMapping("/getInspectDataByCrystalNo")
    public Result<List<YbInspectDataPdaAutomaticDto>> getInspectDataByCrystalNo(@RequestParam String crystalNo) {

        try {
            return ybInspectDataService.getInspectDataByCrystalNo(crystalNo);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "Pda检验的电阻率赋值")
    @PostMapping("/assignmentResistance")
    public Result assignmentResistance(@RequestBody List<YbInspectDataPdaAutomaticDto> ybInspectDataPdaAutomaticDtos) {
        String result = "";
        try {
            result = ybInspectDataService.assignmentResistance(ybInspectDataPdaAutomaticDtos);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success(result);
    }

    public PlanProcessingOrderDto toLazyDto(PlanProcessingOrder entity) {
        return modelMapper.map(entity, PlanProcessingOrderDto.class);
    }

    public YbOemDataDto toYbOemDataDto(YbOemData entity) {
        return modelMapper.map(entity, YbOemDataDto.class);
    }


    public YbInspectData fromYbOemData(YbOemData dto) {
        return modelMapper.map(dto, YbInspectData.class);
    }

}
