package com.sw.mes.yb.mcs.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sw.mes.base.factory.inspect.entity.DefaultSample;
import com.sw.mes.base.factory.inspect.service.DefaultSampleService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.dto.CurrentWipStorageStatusDto;
import com.sw.mes.base.workinprocess.dto.PlanProcessingOrderWipStorageDto;
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.api.system.FbFeignClients;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.RankResultDto;
import com.sw.mes.core.dto.SeedMassageDto;
import com.sw.mes.core.dto.mes.pc.yb.ProductionBindingTrayDto;
import com.sw.mes.core.dto.store.WarehouseInventoryBo;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.enums.SeedMassageEnum;
import com.sw.mes.core.exception.BusinessException;
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.NumberUtil;
import com.sw.mes.dingTalk.service.DingTalkService;
import com.sw.mes.inspect.dto.YbInspectDataCUDto;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.production.service.TruncationReccutDetailsService;
import com.sw.mes.wipstorage.service.WipStorageYbService;
import com.sw.mes.yb.check.entity.PieceCheck;
import com.sw.mes.yb.check.service.PieceCheckService;
import com.sw.mes.yb.fls.dto.TrayAutoUnBinding;
import com.sw.mes.yb.fls.service.FlsToMesService;
import com.sw.mes.yb.mcs.dto.*;
import com.sw.mes.yb.mcs.dto.fillingMaterial.McsMaterialDto;
import com.sw.mes.yb.mcs.dto.fillingMaterial.McsMoWorkReportingDto;
import com.sw.mes.yb.mcs.entity.*;
import com.sw.mes.yb.mcs.service.*;
import com.sw.mes.yb.mcs.vo.HiddenCrackDetectionVo;
import com.sw.mes.yb.pad.dao.PieceDetailDao;
import com.sw.mes.yb.pad.entity.PieceDetail;
import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
import com.sw.mes.yb.pad.service.ProductionPaintingLineService;
import com.sw.mes.yb.pc.service.HeadTailMaterialRuleService;
import com.sw.mes.yb.production.dao.LongCrystalDao;
import com.sw.mes.yb.production.dto.AgainTask.AgainTaskDto;
import com.sw.mes.yb.production.dto.AgainTaskDetail.AgainTaskDetailDto;
import com.sw.mes.yb.production.dto.AgainTaskPrepare.InputTaskDatailPrepareDto;
import com.sw.mes.yb.production.dto.BlastFurnaceDetail.BlastFurnaceAddDto;
import com.sw.mes.yb.production.dto.BlastFurnaceDetail.BlastFurnaceDetailDto;
import com.sw.mes.yb.production.dto.InputFurnaceBurden.InputFurnaceBurdenDto;
import com.sw.mes.yb.production.dto.InputFurnaceDetailDto;
import com.sw.mes.yb.production.dto.InspectionRecord.InspectionRecordDto;
import com.sw.mes.yb.production.dto.LoadingTask.LoadingTaskDto;
import com.sw.mes.yb.production.entity.*;
import com.sw.mes.yb.production.entity.AgainTaskPrepare.AgainTaskPrepare;
import com.sw.mes.yb.production.entity.AgainTaskPrepare.InputTaskDatailPrepare;
import com.sw.mes.yb.production.service.*;
import com.sw.mes.yb.turnstore.service.ProductionBindingTrayService;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: GaoXinJian
 * @Date: 2022-01-14 10:56
 */
@Service
@Transactional
public class YbMcsToMesServiceImpl implements YbMcsToMesService {
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    private YbInspectDataService inspectDataBaseService;
    @Autowired
    private RecycledMaterialCaseService recycledMaterialCaseService;
    @Autowired
    private RecycledMaterialCaseRecordService recycledMaterialCaseRecordService;
    @Autowired
    @Lazy
    private FbFeignClients fbFeignClients;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;
    /**
     * 托盘绑定service
     */
    @Autowired
    private ProductionBindingTrayService productionBindingTrayService;

    /**
     * 头尾料分类规则service
     */
    @Autowired
    HeadTailMaterialRuleService headTailMaterialRuleService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private SegmentInspectionPassPointInfoService segmentInspectionPassPointInfoService;

    @Autowired
    private SegmentInspectionPassPointRecordService segmentInspectionPassPointRecordService;

    @Autowired
    private WipStorageYbService wipStorageYbService;

    @Autowired
    private PieceCheckService pieceCheckService;

    @Autowired
    private PieceDetailDao pieceDetailDao;

    @Autowired
    private LongCrystalDao longCrystalDao;

    @Autowired
    private DefaultSampleService defaultSampleService;

    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;

    @Autowired
    private FlsToMesService flsToMesService;
    /**
     * 截断返切记录service
     */
    @Autowired
    private TruncationReccutDetailsService truncationReccutDetailsService;

    @Autowired
    private DislocationInfoService dislocationInfoService;

    @Autowired
    private DislocationExceptionInfoService dislocationExceptionInfoService;

    @Autowired
    private ProductionPaintingLineService productionPaintingLineService;

    @Autowired
    private LongCrystalService longCrystalService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private McsSquareInventoryLogService mcsSquareInventoryLogService;

    @Autowired
    private SegmentBindInfoService segmentBindInfoService;

    @Autowired
    private AgainTaskService againTaskService;
    @Autowired
    private LoadingTaskService loadingTaskService;

    @Autowired
    private AgainTaskDetailService againTaskDetailService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private BlastFurnaceDetailService blastFurnaceDetailService;

    @Autowired
    private LoadingTaskLogService loadingTaskLogService;

    @Autowired
    private InputFurnaceBurdenService inputFurnaceBurdenService;

    @Autowired
    private InputFurnaceDetailService inputFurnaceDetailService;

    @Autowired
    private StoreFeignClients storeFeignClients;

    @Autowired
    private AgainTaskPrepareService againTaskPrepareService;

    @Autowired
    private InputTaskDatailPrepareService inputTaskDatailPrepareService;

    @Autowired
    private DingTalkService dingTalkService;

    @Autowired
    private InspectionRecordService inspectionRecordService;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Override
    public Result segmentCheckInfo(SegmentCheckInfoDto segmentCheckInfoDto) {
        //托盘流转至检验区，MCS根据检验线点位将晶段上下检验信息发送给MES
        if (StringUtils.isBlank(segmentCheckInfoDto.getIdentification())) {
            //无上下线表示，暂不处理
            return ResultGenerator.success();
        }
        //下线
        if (segmentCheckInfoDto.getIdentification().equals("1")) {
            //删除上线信息
            List<SegmentInspectionPassPointInfo> segmentInspectionPassPointInfoList = segmentInspectionPassPointInfoService.findBySectionNo(segmentCheckInfoDto.getSectionNo());
            for (SegmentInspectionPassPointInfo segmentInspectionPassPointInfo : segmentInspectionPassPointInfoList) {
                segmentInspectionPassPointInfoService.delete(segmentInspectionPassPointInfo.getId());
            }

            //上线
        } else if (segmentCheckInfoDto.getIdentification().equals("0")) {
            //创建上线信息
            SegmentInspectionPassPointInfo segmentInspectionPassPointInfo = JSONObject.parseObject(JSONObject.toJSONString(segmentCheckInfoDto), SegmentInspectionPassPointInfo.class);
            segmentInspectionPassPointInfo.setCreateTime(new Date());
            segmentInspectionPassPointInfoService.saveOrUpdate(segmentInspectionPassPointInfo);
        } else {
            //除上下线点位外，暂不处理
            return ResultGenerator.success();
        }
        //创建上下限记录

        SegmentInspectionPassPointRecord segmentInspectionPassPointRecord = JSONObject.parseObject(JSONObject.toJSONString(segmentCheckInfoDto), SegmentInspectionPassPointRecord.class);
        segmentInspectionPassPointRecord.setCreateTime(new Date());
        segmentInspectionPassPointRecordService.saveOrUpdate(segmentInspectionPassPointRecord);


        return ResultGenerator.success();
    }

    @Override
    public Result ybCheckResult(YbCheckResultDto ybCheckResultDto) {
        YbInspectDataCUDto ybInspectDataCuDto = modelMapper.map(ybCheckResultDto, YbInspectDataCUDto.class);
        if (StringUtils.isBlank(ybInspectDataCuDto.getCheckReback())) {
            ybInspectDataCuDto.setCheckReback("无");
        }
        // 导电型号 -> 少子寿命  (sz * 1.801)+0.0658
        YbInspectDataCUDto coefficient = inspectDataBaseService.coefficient(ybInspectDataCuDto);

        this.handleDataFormat(coefficient, ybCheckResultDto.getSectionNo(), ybCheckResultDto);
        return inspectDataBaseService.saveYbInspectData(coefficient);
    }

    private void handleDataFormat(YbInspectDataCUDto coefficient, String sectionNo, YbCheckResultDto ybCheckResultDto) {
        // 暂时只有 少子寿命
        BigDecimal meanResistivityA = BigDecimal.ZERO;
        BigDecimal meanResistivityB = BigDecimal.ZERO;
        BigDecimal divideDecimal = new BigDecimal(3);

        BigDecimal meanCarrierLifetimeA = BigDecimal.ZERO;
        BigDecimal meanCarrierLifetimeB = BigDecimal.ZERO;

        if (null != ybCheckResultDto.getTCentreLife()) {
            meanCarrierLifetimeA = meanCarrierLifetimeA.add(ybCheckResultDto.getTCentreLife());
            coefficient.setCarrierLifetimeAOne(ybCheckResultDto.getTCentreLife());
        }
        if (null != ybCheckResultDto.getTLifeEdge1()) {
            meanCarrierLifetimeA = meanCarrierLifetimeA.add(ybCheckResultDto.getTLifeEdge1());
            coefficient.setCarrierLifetimeATwo(ybCheckResultDto.getTLifeEdge1());
        }
        if (null != ybCheckResultDto.getTLifeEdge2()) {
            meanCarrierLifetimeA = meanCarrierLifetimeA.add(ybCheckResultDto.getTLifeEdge2());
            coefficient.setCarrierLifetimeAThree(ybCheckResultDto.getTLifeEdge2());
        }
        if (meanCarrierLifetimeA.compareTo(BigDecimal.ZERO) == 0) {
            throw new BusinessException(sectionNo + ",A少子寿命未上传!");
        }
        coefficient.setMeanCarrierLifetimeA(meanCarrierLifetimeA.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));
        if (null != ybCheckResultDto.getWCentreLife()) {
            meanCarrierLifetimeB = meanCarrierLifetimeB.add(ybCheckResultDto.getWCentreLife());
            coefficient.setCarrierLifetimeBOne(ybCheckResultDto.getWCentreLife());
        }
        if (null != ybCheckResultDto.getWLifeEdge1()) {
            meanCarrierLifetimeB = meanCarrierLifetimeB.add(ybCheckResultDto.getWLifeEdge1());
            coefficient.setCarrierLifetimeBTwo(ybCheckResultDto.getWLifeEdge1());
        }
        if (null != ybCheckResultDto.getWLifeEdge2()) {
            meanCarrierLifetimeB = meanCarrierLifetimeB.add(ybCheckResultDto.getWLifeEdge2());
            coefficient.setCarrierLifetimeBThree(ybCheckResultDto.getWLifeEdge2());
        }
        if (meanCarrierLifetimeB.compareTo(BigDecimal.ZERO) == 0) {
            throw new BusinessException(sectionNo + ",B少子寿命未上传!");
        }
        coefficient.setMeanCarrierLifetimeB(meanCarrierLifetimeB.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));


        if (null != ybCheckResultDto.getTRadialCentre()) {
            meanResistivityA = meanResistivityA.add(ybCheckResultDto.getTRadialCentre());
            coefficient.setResistivityAOne(ybCheckResultDto.getTRadialCentre());
        }
        if (null != ybCheckResultDto.getTRadialEdge1()) {
            meanResistivityA = meanResistivityA.add(ybCheckResultDto.getTRadialEdge1());
            coefficient.setResistivityATwo(ybCheckResultDto.getTRadialEdge1());
        }
        if (null != ybCheckResultDto.getTRadialEdge2()) {
            meanResistivityA = meanResistivityA.add(ybCheckResultDto.getTRadialEdge2());
            coefficient.setResistivityAThree(ybCheckResultDto.getTRadialEdge2());
        }
        if (meanResistivityA.compareTo(BigDecimal.ZERO) > 0) {
            coefficient.setMeanResistivityA(meanResistivityA.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));
        }
        if (null != ybCheckResultDto.getWRadialCentre()) {
            meanResistivityB = meanResistivityB.add(ybCheckResultDto.getWRadialCentre());
            coefficient.setResistivityBOne(ybCheckResultDto.getWRadialCentre());
        }
        if (null != ybCheckResultDto.getWRadialEdge1()) {
            meanResistivityB = meanResistivityB.add(ybCheckResultDto.getWRadialEdge1());
            coefficient.setResistivityBTwo(ybCheckResultDto.getWRadialEdge1());
        }
        if (null != ybCheckResultDto.getWRadialEdge2()) {
            meanResistivityB = meanResistivityB.add(ybCheckResultDto.getWRadialEdge2());
            coefficient.setResistivityBThree(ybCheckResultDto.getWRadialEdge2());
        }
        if (meanResistivityB.compareTo(BigDecimal.ZERO) > 0) {
            coefficient.setMeanResistivityB(meanResistivityB.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));
        }

        if (com.sw.mes.utils.StringUtils.isNotBlank(ybCheckResultDto.getConductiveType())) {
            coefficient.setConductiveType(ybCheckResultDto.getConductiveType());
        }
    }

    @Override
    public Result skinCodingInfo(String segmentNo) {
        return null;
    }

    @Override
    public Result unbindInfo(UnbindInfoDto unbindInfoDto) {
        //解绑
        TrayAutoUnBinding trayAutoUnBinding = new TrayAutoUnBinding();
        trayAutoUnBinding.setPoint("截断上料");
        trayAutoUnBinding.setSectionNo(unbindInfoDto.getCrystalNo());
        trayAutoUnBinding.setReason("");
        flsToMesService.trayAutoUnBinding(trayAutoUnBinding, "mcs");
        //查询当前站点信息，判断是否满足进站条件
        PlanProcessingOrderWipStorageDto planProcessingOrderWipStorageDto = wipStorageService.selectWipStorage(unbindInfoDto.getCrystalNo(), EnumValuesFactory.WipStorageCode.圆棒截断.getKey(), false);
        List<String> processingOrderCodeArr = wipStorageYbService.getSectionNos(planProcessingOrderWipStorageDto.getPlanProcessingOrder().getMaterialType(), planProcessingOrderWipStorageDto.getPlanProcessingOrder().getCode());
        for (String processingOrderCode : processingOrderCodeArr) {
            if (!processingOrderCode.equals(planProcessingOrderWipStorageDto.getPlanProcessingOrder().getCode())) {
                wipStorageService.selectWipStorage(processingOrderCode, EnumValuesFactory.WipStorageCode.圆棒截断.getKey(), false);
            }
            Result result = wipStorageService.inStation(processingOrderCode, unbindInfoDto.getCutNo());
            if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                throw new BusinessException(result.getMessage());
            }
        }
        //出截断站并生成子工单
        wipStorageYbService.execJd(planProcessingOrderWipStorageDto, true);
        return ResultGenerator.success();
    }

    @Override
    public HeadTailMaterialTypeDto getHeadTailMaterialType(String code) {
        HeadTailMaterialTypeDto headTailMaterialTypeDto = headTailMaterialRuleService.findHeadTailMaterialRuleByRecoveryNo(code);
        if (headTailMaterialTypeDto == null) {
            throw new RuntimeException("无匹配的头尾料分类规则");
        }

        return headTailMaterialTypeDto;
    }

    @Override
    public void headTailMaterialInfo(HeadTailMaterialInfoDto headTailMaterialInfoDto) {
        //查询并删除回收料箱信息
        List<RecycledMaterialCase> recycledMaterialCaseList = recycledMaterialCaseService.findByCaseNo(headTailMaterialInfoDto.getCaseNo());
        for (RecycledMaterialCase recycledMaterialCase : recycledMaterialCaseList) {
            recycledMaterialCaseService.delete(recycledMaterialCase.getId());
        }
        //创建回收料箱信息
        RecycledMaterialCase recycledMaterialCase = JSONObject.parseObject(JSONObject.toJSONString(headTailMaterialInfoDto), RecycledMaterialCase.class);
        recycledMaterialCaseService.saveOrUpdate(recycledMaterialCase);
        //创建回收料箱记录
        RecycledMaterialCaseRecord recycledMaterialCaseRecord = JSONObject.parseObject(JSONObject.toJSONString(headTailMaterialInfoDto), RecycledMaterialCaseRecord.class);
        recycledMaterialCaseRecordService.saveOrUpdate(recycledMaterialCaseRecord);

    }

    @Override
    public Result sectionWipStorageInfo(SkinCodingInfoDto skinCodingInfoDto) {
        String segmentNo = skinCodingInfoDto.getSegmentNo();
        if (null == segmentNo || StringUtils.isBlank(segmentNo)) {
            return ResultGenerator.fail("晶段编号为空！");
        }
        PlanProcessingOrder byCode = planProcessingOrderService.findByCode(segmentNo);
        if (null == byCode) {
            return ResultGenerator.fail("加工工单表中无此编号： " + segmentNo);
        }
        if (null == byCode.getStatus() || byCode.getStatus() != 1) {
            return ResultGenerator.fail("此编号： " + segmentNo + " 不在加工中状态，当前状态为：" + EnumValuesFactory.PlanProcessingOrderStatus.getText(byCode.getStatus()));
        }

//        if (!EnumValuesFactory.WipStorageCode.圆棒检验.getValue().equals(byCode.getWipStorage().getProcessName())) {
//            return ResultGenerator.fail("此编号： " + segmentNo + " 站点不在圆棒检验");
//        }
//        // 待进站和已进站通过
//        if (byCode.getWipStorage().getStatus() == EnumValuesFactory.WipStorageStatus.已出站.getKey()
//        ) {
//            return ResultGenerator.fail("此编号： " + segmentNo + " 已出站");
//        }
//        String toMcsInfo = byCode.getWipStorage().getProcessName() + EnumValuesFactory.WipStorageStatus.valueOf(byCode.getWipStorage().getProcessName());
        String toMcsInfo = byCode.getWipStorage().getProcessName();
        return ResultGenerator.success(toMcsInfo, null);
    }

    @Override
    public Result ybInspectStationIn(SkinCodingInfoDto skinCodingInfoDto) {
        //校验卡控：不是检验待进站状态不允许当前操作
        Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(skinCodingInfoDto.getSegmentNo());
        if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException(currentWipStorageStatusDtoResult.getMessage());
        }
        CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
        if (currentWipStorageStatusDto == null || currentWipStorageStatusDto.getWipStorageCode() == null || currentWipStorageStatusDto.getWipStorageStatus() == null) {
            throw new BusinessException("站点信息查询失败，请检查在制品信息");
        }
        //如果不是检验待进站状态，报错
        boolean isStatus = currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.圆棒检验.getKey())
                && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey();
        if (!isStatus) {
            return ResultGenerator.fail("晶棒:" + skinCodingInfoDto.getSegmentNo() + "不是检验待进站状态不允许当前操作！");
        }
        //操作过站
        Result result = wipStorageService.inStation(skinCodingInfoDto.getSegmentNo(), null, false);
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return ResultGenerator.success();
    }

    @Override
    public Result checkForAutoBind(PdaBingDto pdaBingDto) {

        //校验卡控：不是检验待进站状态不允许当前操作
        Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(pdaBingDto.getSectionNo());
        if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException(currentWipStorageStatusDtoResult.getMessage());
        }
        CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
        if (currentWipStorageStatusDto == null || currentWipStorageStatusDto.getWipStorageCode() == null || currentWipStorageStatusDto.getWipStorageStatus() == null) {
            throw new BusinessException("站点信息查询失败，请检查在制品信息");
        }
        //如果不是检验待进站状态，报错
        boolean isStatus = currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.圆棒检验.getKey());
//                && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey();
        if (!isStatus) {
            return ResultGenerator.fail("晶棒:" + pdaBingDto.getSectionNo() + "不是检验待进站状态不允许当前操作！");
        }

        //校验是否存在绑定记录，存在则告警
        List<SegmentBindInfo> bindInfos = segmentBindInfoService.findBysegmentNo(pdaBingDto.getSectionNo());
        if (null != bindInfos && !bindInfos.isEmpty()) {
            return ResultGenerator.fail("晶棒:" + pdaBingDto.getSectionNo() + "已经执行过绑定操作不允许重复绑定！");
        }

        //绑定信息表中新增一条记录，用以预防重复绑定
        SegmentBindInfo segmentBindInfo = new SegmentBindInfo();
        segmentBindInfo.setSegmentNo(pdaBingDto.getSectionNo());
        segmentBindInfo.setDeviceNo(pdaBingDto.getCutNo());
        segmentBindInfo.setCreateTime(new Date());
        segmentBindInfo.setCreateUserName(BaseContextHandler.getUsername());
        segmentBindInfoService.saveOrUpdate(segmentBindInfo);

        // 中间段免检
        Map<String, String> map = productionPaintingLineDetailService.flowDirection(pdaBingDto.getSectionNo(), "截断下料");
        if (!map.isEmpty() && map.containsKey("index")) {
            map.remove("index");
        }

        return ResultGenerator.success(map);
    }

    @Override
    public Result squareOrder(SquareOrderMesDto squareOrderDto) {
        SquareOrderMesResultDto squareOrderMesResultDto = new SquareOrderMesResultDto();
        //查询检验数据库
        YbInspectData inspectDataBase = inspectDataBaseService.findBySectionNo(squareOrderDto.getSectionNo());
        //匹配订单编号
        if (inspectDataBase != null) {
            RankResultDto rankResultDto = new RankResultDto();
            rankResultDto.setSectionNo(inspectDataBase.getSectionNo());
            rankResultDto.setProductRank(inspectDataBase.getProductLevel());
            rankResultDto.setTestRank(inspectDataBase.getProductLevelExperiment());
            rankResultDto.setType(inspectDataBase.getSectionType());
            rankResultDto.setGradeType(inspectDataBase.getGradeType());
            rankResultDto.setSpecs(inspectDataBase.getProductTypeSecond());
            rankResultDto.setConductiveType(inspectDataBase.getConductiveType());
            rankResultDto.setDopant(inspectDataBase.getDopant());
            String type = inspectDataBase.getSectionType();
            if (inspectDataBase.getSticksCount() != null && inspectDataBase.getSticksCount() > 1) {
                rankResultDto.setLength(inspectDataBase.getSpellBarLength());
                type = "拼棒";
            } else {
                rankResultDto.setLength(inspectDataBase.getActualLength());
            }
            if ("标棒".equals(rankResultDto.getType()) && "正常".equals(rankResultDto.getGradeType())) {
                Result<String> result = fbFeignClients.findProductionScheduleCodePro(rankResultDto);
                if (result.getCode() == ResultCode.SUCCESS.getCode() && result.getData() != null && StringUtils.isNotBlank(result.getData())) {
                    rankResultDto.setOrderNo(result.getData());
                }
            }

            if (inspectDataBase.getIsCutBack() != null && inspectDataBase.getIsCutBack() == 1) {
                rankResultDto.setType("反切");
            } else {
                rankResultDto.setType(type);
            }

            squareOrderMesResultDto = toLazyDto(rankResultDto);
        }

        return ResultGenerator.success(squareOrderMesResultDto);
    }

    @Override
    public Result sampleInfo(SampleCheckInfoDto sampleCheckInfoDto) {
        List<PieceCheck> pieceChecks = new ArrayList<>();
        List<PieceDetail> pieceMaterialDetails = this.pieceDetailDao.findByPieceNo(sampleCheckInfoDto.getPieceNo());
        if (pieceMaterialDetails == null || pieceMaterialDetails.size() <= 0) {
            return ResultGenerator.fail("样片编号不存在");
        }
        PieceDetail pieceDetail = pieceMaterialDetails.get(0);
        PieceCheck pieceCheck = pieceCheckService.getByPieceNo(sampleCheckInfoDto.getPieceNo());
        if (pieceCheck == null) {
            pieceCheck = new PieceCheck();
            pieceCheck.setPieceNo(sampleCheckInfoDto.getPieceNo());

            LongCrystal sectionDetail = this.longCrystalDao.findByPieceNo(sampleCheckInfoDto.getPieceNo());
            if (sectionDetail != null) {
                pieceCheck.setDeviceNo(sectionDetail.getEquipmentCode());
                pieceCheck.setLotNo(sectionDetail.getLotNo());
                pieceCheck.setMotherCrystalNo(sectionDetail.getCrystalNo());
            }
        }
        // 默认值
        // 截取样片倒数第二位,判断是头是尾
        String pieceNo = pieceDetail.getPieceNo();
        String TorW = pieceNo.substring(pieceNo.length() - 2, pieceNo.length() - 1);
        DefaultSample sample = this.defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(pieceDetail.getDopant(), pieceDetail.getSpecs(), pieceDetail.getProductType());
//        // 微缺陷
//        if (sampleCheckInfoDto.getMicroDefect() == null){
//            if (TorW.equals("T") && sample != null){
//                pieceCheck.setMicroDefect(sample.getHeadDefect());// 头微缺陷
//            }else if (TorW.equals("W") && sample != null){
//                pieceCheck.setMicroDefect(sample.getTailDefect());// 尾微缺陷
//            }else {
//                pieceCheck.setMicroDefect(null);
//            }
//        }else {
//            pieceCheck.setMicroDefect(sampleCheckInfoDto.getMicroDefect());// 微缺陷
//        }
//
//        // 位错
//        if (sampleCheckInfoDto.getLineDefect() == null){
//            if (TorW.equals("T") && sample != null){
//                pieceCheck.setLineDefect(sample.getHeadDislocation());// 头位错
//            }else if (TorW.equals("W") && sample != null){
//                pieceCheck.setLineDefect(sample.getTailDislocation());// 尾位错
//            }else {
//                pieceCheck.setLineDefect(null);
//            }
//        }else {
//            pieceCheck.setLineDefect(sampleCheckInfoDto.getLineDefect());// 位错
//        }
        BeanUtils.copyProperties(sampleCheckInfoDto, pieceCheck, BeanUtil.getIgnoreProperties(sampleCheckInfoDto, null, null));
        pieceCheck.setUserName1("mcs");
        pieceCheck.setCheckTime1(new Date());
        pieceCheck.setUserName2("mcs");
        pieceCheck.setCheckTime2(new Date());
        pieceCheck.setAnnealUser("mcs");
        pieceCheck.setAnnealTime(new Date());
        pieceChecks.add(pieceCheck);

        pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片检验-新增");
        this.pieceCheckService.saveInspectDataBaseInfo(sampleCheckInfoDto.getPieceNo());


        return ResultGenerator.success();
    }

    @Override
    public Result biddingRecycledMaterial(RecycledBindingInfoDto recycledBindingInfoDto) {
        //验证编号是否存在
        ProductionPaintingLineDetail bySegmentNo = productionPaintingLineDetailService.findBySegmentNo(recycledBindingInfoDto.getCode());
        if (bySegmentNo != null) {
            if (bySegmentNo.getType() == 0) {
                return ResultGenerator.fail("编号【" + recycledBindingInfoDto.getCode() + "】非样片、回收料！");
            }
        } else {
            String crystalNoBySectionNo = truncationReccutDetailsService.findCrystalNoBySectionNo(recycledBindingInfoDto.getCode());
            if (StringUtils.isBlank(crystalNoBySectionNo)) {
                throw new RuntimeException("编号【" + recycledBindingInfoDto.getCode() + "】非回收料！");
            }
        }

        //初始化绑定信息
        ProductionBindingTrayDto productionBindingTrayDto = new ProductionBindingTrayDto();
        productionBindingTrayDto.setCrystalNo(recycledBindingInfoDto.getCode());
        productionBindingTrayDto.setBindingPeople("mcs");
        productionBindingTrayDto.setBindingSite("截断自动下料");
        productionBindingTrayDto.setBindingTime(new Date());
        //自动绑定
        productionBindingTrayDto.setIsBinding(0);
        //只有一个工位，默认为空
        productionBindingTrayDto.setLocationNo("1");
        productionBindingTrayDto.setTrayNo(recycledBindingInfoDto.getTrayCode());
        productionBindingTrayDto.setCrystalDirection(recycledBindingInfoDto.getOrientation());
        productionBindingTrayDto.setType("回收料");
        productionBindingTrayDto.setPoint("JD");

        //绑定
        Result result = productionBindingTrayService.bindingCrystal(productionBindingTrayDto);

        //绑定结果，200成功，其它失败
        if (result.getCode() != 200) {
            return ResultGenerator.message(104, "绑定异常：" + result.getMessage(), null);
        }

        return ResultGenerator.message(200, "绑定成功", null);
    }

    @Override
    public Result staggerPositionInfo(DislocationInfoDto dislocationDto) {
        JSONArray detailJsonArray = JSONArray.parseArray(dislocationDto.getDetailJsonStr());
        DislocationInfo dislocationInfo = toLazyDto(dislocationDto);
        dislocationInfo.setCreateTime(new Date());
        dislocationInfoService.saveOrUpdate(dislocationInfo);
        List<DislocationExceptionInfoDto> list = JSONObject.parseArray(detailJsonArray.toJSONString(), DislocationExceptionInfoDto.class);
        for (DislocationExceptionInfoDto entity : list) {
            DislocationExceptionInfo dislocationExceptionInfo = toLazyDto(entity);
            dislocationExceptionInfo.setDislocationId(dislocationInfo.getId());
            dislocationExceptionInfoService.saveOrUpdate(dislocationExceptionInfo);
        }
        return ResultGenerator.message(200, "发送成功", null);
    }

    @Override
    public Result uploadInventory(List<McsFbInventoryDto> fbInventoryDto) {
        fbInventoryDto.stream().forEach(t -> {
            McsSquareInventoryLog mcsSquareInventoryLog = new McsSquareInventoryLog();
            BeanUtil.copyProperties(mcsSquareInventoryLog, t);
            mcsSquareInventoryLog.setDelFlag(0);
            mcsSquareInventoryLog.setCreateTime(new Date());
            mcsSquareInventoryLog.setUpdateTime(new Date());
            mcsSquareInventoryLog.setCreateUser("mcs");
            mcsSquareInventoryLog.setInventoryType("out");
            mcsSquareInventoryLog.setLength(String.valueOf(t.getLength()));
            mcsSquareInventoryLog.setSpecification(t.getSpecs());
            mcsSquareInventoryLog.setConductionType(t.getConductiveType());
            mcsSquareInventoryLog.setProductLevelFb(t.getProductGrade());
            mcsSquareInventoryLog.setProductType(t.getProductType());
            //先删除在插入
            mcsSquareInventoryLogService.deleteByCrystalNoAndInventoryType(t.getCrystalNo(), "out");
            mcsSquareInventoryLogService.saveOrUpdate(mcsSquareInventoryLog);
        });
        try {
            List<String> sectionList = new ArrayList<>();
            for (McsFbInventoryDto mcsFbInventoryDto : fbInventoryDto) {
                sectionList.add(mcsFbInventoryDto.getCrystalNo());
            }
            fbFeignClients.create(sectionList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.success();
    }

    @Override
    public CrystalTrayBindInfoResult findBindingInfoBySectionNo(SectionInfo info) {
        String sectionNo = info.getSectionNo();
        ProductionPaintingLineDetail lineDetail = productionPaintingLineDetailService.findBySegmentNo(sectionNo);
        if (lineDetail == null) {
            throw new RuntimeException("该晶棒" + sectionNo + "不存在");
        }

        LongCrystal longCrystal = longCrystalService.get(lineDetail.getCrystalId());
        if (longCrystal == null) {
            throw new RuntimeException("该晶棒" + sectionNo + "对应长晶棒信息不存在");
        }

        return buildCrystalTrayBindInfoResult(lineDetail, longCrystal);
    }

    private CrystalTrayBindInfoResult buildCrystalTrayBindInfoResult(ProductionPaintingLineDetail lineDetail, LongCrystal longCrystal) {
        CrystalTrayBindInfoResult result = new CrystalTrayBindInfoResult();
        result.setSectionNo(lineDetail.getNo());
        result.setLength(Convert.toStr(lineDetail.getLength(), null));
        DictionaryItem item = dictionaryItemService.findByThemeValueAndValueAndEnable("product_category", longCrystal.getProductType(), true);
        result.setProductType(Optional.ofNullable(item).map(DictionaryItem::getName).orElse(""));
        result.setDopant(longCrystal.getDopant());
        result.setConductiveType(longCrystal.getConductiveType());
        result.setType(longCrystal.getSpecs());
        result.setSegmentType(lineDetail.getType());
        result.setIsReCut(lineDetail.getIsCut());
//        result.setIsAvoidCheck();//Todo 后面预留

        return result;
    }

    @Override
    public Result moWorkReportingInterface(McsMoWorkReportingDto dto, Object obj) {
        if (obj instanceof LoadingTask) {// 装料任务
            LoadingTask task = (LoadingTask) obj;
            Integer rawStatus = null;
            if (dto.getFinishType() != null && 0 == dto.getFinishType()) {
                rawStatus = AgainTaskDto.rawStatus_3;
            } else if (dto.getFinishType() != null && 1 == dto.getFinishType()) {
                rawStatus = AgainTaskDto.rawStatus_4;
            } else {
                rawStatus = AgainTaskDto.rawStatus_3;
            }
            BlastFurnaceAddDto addDto = new BlastFurnaceAddDto();
            addDto.setLoadingTaskDto(toLazyDto(task));
            addDto.getLoadingTaskDto().setOperationTime(dto.getFeedingEndTime());
//            addDto.getLoadingTaskDto().setWeight(getWeight(dto.getMaterialList()));
            addDto.setVehicleCode(dto.getFrockCode());
            List<BlastFurnaceDetailDto> list = new ArrayList<>();
            if (dto.getMaterialList() != null) {
                for (McsMaterialDto mDto : dto.getMaterialList()) {
                    BlastFurnaceDetailDto detail = new BlastFurnaceDetailDto();
                    detail.setBlastFurnaceId(task.getId());
                    detail.setMaterialCode(mDto.getMaterialNo());
                    detail.setMaterialName(mDto.getMaterialName());
                    detail.setBatchNo(mDto.getBatch());
                    detail.setWeight(mDto.getMaterialWeight());
                    detail.setFactoryBrand(mDto.getFactoryBrand());
                    detail.setRemark(JSON.toJSONString(mDto));
                    detail.setUserName(task.getUserName());
                    detail.setInstallTime(dto.getFeedingEndTime());
                    //通过批次号查询库存信息
                    Result<WarehouseInventoryBo> warehouseInventoryBoResult = storeFeignClients.findByBatchNo(mDto.getBatch());
                    if (warehouseInventoryBoResult.getCode() != 200 && null != warehouseInventoryBoResult.getData()) {
                        detail.setStoreLocationId(warehouseInventoryBoResult.getData().getWarehouseId() == null ? null : warehouseInventoryBoResult.getData().getWarehouseId().intValue());
                        detail.setStoreLocationName(warehouseInventoryBoResult.getData().getWarehouseName());
                    }

//                    detail.setUniqueCode();
//                    detail.setBucketForty();
//                    detail.setBucketTen();
//                    detail.setAlloyBrand();
//                    detail.setAlloyType();
//                    detail.setTrialType();
//                    detail.setPulled();
//                    detail.setErpWarehouseCode();
//                    detail.setErpBatchNo();
                    MaterialModel model = materialModelService.findByCode(mDto.getMaterialNo());
                    if (model != null) {
                        detail.setSupplierName(model.getSupplier());
                        if (model.getMaterialType() != null) {
                            detail.setProductCode(model.getMaterialType().getCode());
                            detail.setMaterialTypeName(model.getMaterialType().getName());
                            if (StringUtils.contains(model.getMaterialType().getName(), "坩埚")) {
                                detail.setMarkCrucible(true);
                            } else {
                                detail.setMarkCrucible(false);
                            }
                        }
                        if (model.getUnit() != null) {
                            detail.setUnit(model.getUnit().getName());
                        }
                    }
                    list.add(detail);
                }
            }
            addDto.setBlastFurnaceDetailDtos(list);
            blastFurnaceDetailService.addBlastFurnace(addDto.getLoadingTaskDto(), addDto.getBlastFurnaceDetailDtos(), rawStatus, "MCS");
        } else if (obj instanceof AgainTaskDetail) {// 灌料任务
            AgainTaskDetail task = (AgainTaskDetail) obj;
            Integer rawStatus = null;
            if (dto.getFinishType() != null && 0 == dto.getFinishType()) {
                rawStatus = AgainTaskDto.rawStatus_3;
            } else if (dto.getFinishType() != null && 1 == dto.getFinishType()) {
                rawStatus = AgainTaskDto.rawStatus_4;
            } else {
                rawStatus = AgainTaskDto.rawStatus_3;
            }

            //复投任务
            AgainTask againTask = againTaskService.get(task.getAgainTaskId());

            if (1 == dto.getReportType()) {
                task.setRawStatus(AgainTaskDto.rawStatus_2);
                againTaskDetailService.saveOrUpdate(task);

                againTask.setRawStatus(AgainTaskDto.rawStatus_0);
                againTask.setReportType(dto.getReportType() + "");
                againTaskService.saveOrUpdate(againTask);
                return ResultGenerator.success();
            }

            InputFurnaceBurdenDto inputFurnaceBurdenDto = new InputFurnaceBurdenDto();
            initInputFurnaceBurdenData(task, inputFurnaceBurdenDto, dto);
            List<InputFurnaceDetailDto> list = new ArrayList<>();
            if (dto.getMaterialList() != null) {
                for (McsMaterialDto mDto : dto.getMaterialList()) {
                    InputFurnaceDetailDto detail = new InputFurnaceDetailDto();
                    detail.setMaterialCode(mDto.getMaterialNo());
                    detail.setMaterialName(mDto.getMaterialName());
                    detail.setBatchNo(mDto.getBatch());
                    detail.setWeight(mDto.getMaterialWeight());
                    detail.setBucketNo(mDto.getVesselNo());
                    detail.setFactoryBrand(mDto.getFactoryBrand());
                    detail.setMaterialTypeName(mDto.getMaterialType());
                    detail.setUnit(mDto.getUnit());
                    //detail.setUniqueCode();
                    //通过批次号查询库存信息
                    Result<WarehouseInventoryBo> warehouseInventoryBoResult = storeFeignClients.findByBatchNo(mDto.getBatch());
                    if (warehouseInventoryBoResult.getCode() != 200 && null != warehouseInventoryBoResult.getData()) {
                        detail.setStoreLocationId(warehouseInventoryBoResult.getData().getWarehouseId() == null ? null : warehouseInventoryBoResult.getData().getWarehouseId().intValue());
                        detail.setStoreLocationName(warehouseInventoryBoResult.getData().getWarehouseName());
                    }
                    MaterialModel model = materialModelService.findByCode(mDto.getMaterialNo());
                    if (model != null) {
                        detail.setSupplierName(model.getSupplier());
                        if (model.getMaterialType() != null) {
                            detail.setProductCode(model.getMaterialType().getCode());
                            detail.setMaterialTypeName(model.getMaterialType().getName());
                        }
                        if (model.getUnit() != null) {
                            detail.setUnit(model.getUnit().getName());
                        }
                    }

                    list.add(detail);
                }
            }

            inputFurnaceBurdenDto.setDetails(list);
            inputFurnaceBurdenService.endInputFurnace(inputFurnaceBurdenDto, rawStatus, "MCS");
        } else if (obj instanceof AgainTaskPrepare) {// 预装料任务
            AgainTaskPrepare task = (AgainTaskPrepare) obj;
            Integer rawStatus = null;
            if (dto.getFinishType() != null && 0 == dto.getFinishType()) {
                rawStatus = AgainTaskDto.rawStatus_3;
            } else if (dto.getFinishType() != null && 1 == dto.getFinishType()) {
                rawStatus = AgainTaskDto.rawStatus_4;
            } else {
                rawStatus = AgainTaskDto.rawStatus_3;
            }
            task.setRawStatus(rawStatus);
            task.setCarrierNo(dto.getFrockCode());
            task.setEndTime(dto.getFeedingEndTime());
            task.setReportTime(dto.getReportTime());
            task.setFeedingEndTime(dto.getFeedingEndTime());
            task.setFinishType(dto.getFinishType());
            task.setReportType(dto.getReportType());
            if (1 == dto.getReportType()) {
                task.setRawStatus(AgainTaskDto.rawStatus_2);
                againTaskPrepareService.saveOrUpdate(task);
                return ResultGenerator.success();
            }
            againTaskPrepareService.saveOrUpdate(task);

            List<InputTaskDatailPrepareDto> list = new ArrayList<>();
            if (dto.getMaterialList() != null) {
                for (McsMaterialDto mDto : dto.getMaterialList()) {
                    InputTaskDatailPrepareDto detail = new InputTaskDatailPrepareDto();
                    detail.setMaterialCode(mDto.getMaterialNo());
                    detail.setMaterialName(mDto.getMaterialName());
                    detail.setBatchNo(mDto.getBatch());
                    detail.setWeight(mDto.getMaterialWeight());
                    detail.setBucketNo(mDto.getVesselNo());
                    detail.setFactoryBrand(mDto.getFactoryBrand());
                    detail.setMaterialTypeName(mDto.getMaterialType());
                    detail.setUnit(mDto.getUnit());
                    //detail.setUniqueCode();
                    //通过批次号查询库存信息
                    Result<WarehouseInventoryBo> warehouseInventoryBoResult = storeFeignClients.findByBatchNo(mDto.getBatch());
                    if (warehouseInventoryBoResult.getCode() != 200 && null != warehouseInventoryBoResult.getData()) {
                        detail.setStoreLocationId(warehouseInventoryBoResult.getData().getWarehouseId() == null ? null : warehouseInventoryBoResult.getData().getWarehouseId().intValue());
                        detail.setStoreLocationName(warehouseInventoryBoResult.getData().getWarehouseName());
                    }
                    MaterialModel model = materialModelService.findByCode(mDto.getMaterialNo());
                    if (model != null) {
                        detail.setSupplierName(model.getSupplier());
                        if (model.getMaterialType() != null) {
                            detail.setMaterialTypeName(model.getMaterialType().getName());
                        }
                        if (model.getUnit() != null) {
                            detail.setUnit(model.getUnit().getName());
                        }
                    }

                    list.add(detail);
                }
            }

            inputTaskDatailPrepareService.endInput(task, list);
        }

        return ResultGenerator.success();
    }

    private void initInputFurnaceBurdenData(AgainTaskDetail againTaskDetail, InputFurnaceBurdenDto inputFurnaceBurden, McsMoWorkReportingDto dto) {
        inputFurnaceBurden.setEquipmentCode(againTaskDetail.getEquipmentCode());
        inputFurnaceBurden.setLotNo(againTaskDetail.getLotNo());
        inputFurnaceBurden.setSeries(againTaskDetail.getSeries());
        inputFurnaceBurden.setArea(againTaskDetail.getArea());
        inputFurnaceBurden.setRawType(againTaskDetail.getRawType());
        if (inputFurnaceBurden.getPailNum() == null) {
            inputFurnaceBurden.setPailNum(againTaskDetail.getNum());
        }
        inputFurnaceBurden.setWeigth(againTaskDetail.getAgainWeigth());
        inputFurnaceBurden.setEndTime(new Date());
        inputFurnaceBurden.setUserName("MCS");
        inputFurnaceBurden.setStartTime(dto.getReportTime());
        inputFurnaceBurden.setFurnaceType(againTaskDetail.getFurnaceType());
        inputFurnaceBurden.setSapNo(againTaskDetail.getSapNo());
        inputFurnaceBurden.setProductCode(againTaskDetail.getProductCode());
        inputFurnaceBurden.setProductGrade(againTaskDetail.getProductGrade());
        inputFurnaceBurden.setSpecs(againTaskDetail.getSpecs());
        inputFurnaceBurden.setDopant(againTaskDetail.getDopant());
        inputFurnaceBurden.setProductType(againTaskDetail.getProductType());
        if (againTaskDetail.getPailNum() != null) {
            String[] split = againTaskDetail.getPailNum().split(",");
            String[] split1 = againTaskDetail.getTaskWeigths().split(",");
            if (split.length > 0) {
                inputFurnaceBurden.setLeftCode(split[0]);
                inputFurnaceBurden.setLeftWeight(NumberUtil.Object2BigDecimal(split1[0]));
            }
            if (split.length > 1) {
                inputFurnaceBurden.setRightCode(split[1]);
                inputFurnaceBurden.setRightWeight(NumberUtil.Object2BigDecimal(split1[1]));
            }
        }
        inputFurnaceBurden.setAgainNum(againTaskDetail.getAgainNum());
        inputFurnaceBurden.setAgainTaskDetailId(againTaskDetail.getId());
        inputFurnaceBurden.setVehicleCode(dto.getFrockCode());
    }

    @Override
    public Result mcsMoWorkReporting(AgainTaskPrepare taskPrepare, AgainTaskDetail againTaskDetail) {
        Integer rawStatus = null;
        if (taskPrepare.getFinishType() != null && 0 == taskPrepare.getFinishType()) {
            rawStatus = AgainTaskDto.rawStatus_3;
        } else if (taskPrepare.getFinishType() != null && 1 == taskPrepare.getFinishType()) {
            rawStatus = AgainTaskDto.rawStatus_4;
        } else {
            rawStatus = AgainTaskDto.rawStatus_3;
        }

        InputFurnaceBurden inputFurnaceBurden = new InputFurnaceBurden();
        initInputFurnaceBurdenDataPrepare(againTaskDetail, inputFurnaceBurden, taskPrepare);
        //桶任务 - 灌料任务
        if (againTaskDetail.getRawStatus().equals(AgainTaskDetailDto.rawStatus_1) || againTaskDetail.getRawStatus().equals(AgainTaskDetailDto.rawStatus_0)) {
            againTaskDetail.setRawStatus(rawStatus);
        } else {
            throw new RuntimeException("当前任务未处在可执行状态");
        }

        //复投任务
        AgainTask againTask = againTaskService.get(againTaskDetail.getAgainTaskId());

        //已灌料桶数
        int alreadyPailNum = againTask.getAlreadyPailNum() == null ? 0 : againTask.getAlreadyPailNum();
        alreadyPailNum += inputFurnaceBurden.getPailNum();

        againTaskDetail.setCarrierNo(taskPrepare.getCarrierNo());
        againTaskDetail.setAlreadyPailNum(alreadyPailNum);
        againTaskDetail.setStartTime(taskPrepare.getStartTime());
        againTaskDetail.setEndTime(taskPrepare.getEndTime());
        againTaskDetail.setUserName("MCS");
        againTaskDetail.setAgainRealWeight(taskPrepare.getAgainWeigth());
        if (againTaskDetail.getAgainRealWeight().compareTo(againTaskDetail.getAgainWeigth()) > 0) {
            throw new RuntimeException("实际灌料重量不能大于当前复投重量！");
        }
        againTaskDetailService.saveOrUpdate(againTaskDetail);

        againTask.setAlreadyPailNum(alreadyPailNum);
        //完成任务 - 复投任务
        if (againTask.getAgainPailNum() == null || againTask.getAlreadyPailNum() >= againTask.getAgainPailNum()) {
            if (againTask.getRawStatus().equals(AgainTaskDto.rawStatus_1)) {
                againTask.setRawStatus(rawStatus);
                robotSeedMessage(againTask.getEquipmentCode(), againTask.getAgainNum());
            } else {
                throw new RuntimeException("当前复投任务未处在可执行状态");
            }
        }
        Integer pailNum = againTask.getPailNum();
        pailNum = pailNum == null ? 0 : pailNum;
        againTask.setPailNum(pailNum + againTaskDetail.getNum());//当前桶数
        againTaskService.saveOrUpdate(againTask);

        inputFurnaceBurdenService.saveOrUpdate(inputFurnaceBurden);

        List<InputFurnaceDetail> list = new ArrayList<>();
        //查询预装料任务报工明细数据
        List<InputTaskDatailPrepare> listPrepare = inputTaskDatailPrepareService.findByProductionAgainTaskPrepareId(taskPrepare.getId());
        if (listPrepare != null) {
            for (InputTaskDatailPrepare mDto : listPrepare) {
                InputFurnaceDetail detail = new InputFurnaceDetail();
                detail.setInputFurnaceId(inputFurnaceBurden.getId());
                detail.setAgainTaskDetailId(againTaskDetail.getId());
                detail.setProductCode(againTaskDetail.getProductCode());
                detail.setUniqueCode(mDto.getUniqueCode());
                detail.setSupplierName(mDto.getSupplierName());
                detail.setMaterialCode(mDto.getMaterialCode());
                detail.setMaterialName(mDto.getMaterialName());
                detail.setBatchNo(mDto.getBatchNo());
                detail.setWeight(mDto.getWeight());
                detail.setBucketNo(mDto.getBucketNo());
                detail.setFactoryBrand(mDto.getFactoryBrand());
                detail.setMaterialTypeName(mDto.getMaterialTypeName());
                detail.setUnit(mDto.getUnit());
                detail.setStoreLocationId(mDto.getStoreLocationId());
                detail.setStoreLocationName(mDto.getStoreLocationName());

                list.add(detail);
            }
            inputFurnaceDetailService.saveAll(list);
        }

        return ResultGenerator.success();
    }

    private void initInputFurnaceBurdenDataPrepare(AgainTaskDetail againTaskDetail, InputFurnaceBurden inputFurnaceBurden, AgainTaskPrepare taskPrepare) {
        inputFurnaceBurden.setIsNextEnd(againTaskDetail.getIsNextEnd());
        inputFurnaceBurden.setEquipmentCode(againTaskDetail.getEquipmentCode());
        inputFurnaceBurden.setLotNo(againTaskDetail.getLotNo());
        inputFurnaceBurden.setSeries(againTaskDetail.getSeries());
        inputFurnaceBurden.setArea(againTaskDetail.getArea());
        inputFurnaceBurden.setRawType(againTaskDetail.getRawType());
        if (inputFurnaceBurden.getPailNum() == null) {
            inputFurnaceBurden.setPailNum(againTaskDetail.getNum());
        }
        inputFurnaceBurden.setWeigth(againTaskDetail.getAgainWeigth());
        inputFurnaceBurden.setEndTime(new Date());
        inputFurnaceBurden.setUserName("MCS");
        inputFurnaceBurden.setStartTime(taskPrepare.getReportTime());
        inputFurnaceBurden.setFurnaceType(againTaskDetail.getFurnaceType());
        inputFurnaceBurden.setSapNo(againTaskDetail.getSapNo());
        inputFurnaceBurden.setProductCode(againTaskDetail.getProductCode());
        inputFurnaceBurden.setProductGrade(againTaskDetail.getProductGrade());
        inputFurnaceBurden.setSpecs(againTaskDetail.getSpecs());
        inputFurnaceBurden.setDopant(againTaskDetail.getDopant());
        inputFurnaceBurden.setProductType(againTaskDetail.getProductType());
        if (againTaskDetail.getPailNum() != null) {
            String[] split = againTaskDetail.getPailNum().split(",");
            String[] split1 = againTaskDetail.getTaskWeigths().split(",");
            if (split.length > 0) {
                inputFurnaceBurden.setLeftCode(split[0]);
                inputFurnaceBurden.setLeftWeight(NumberUtil.Object2BigDecimal(split1[0]));
            }
            if (split.length > 1) {
                inputFurnaceBurden.setRightCode(split[1]);
                inputFurnaceBurden.setRightWeight(NumberUtil.Object2BigDecimal(split1[1]));
            }
        }
        inputFurnaceBurden.setAgainNum(againTaskDetail.getAgainNum());
        inputFurnaceBurden.setAgainTaskDetailId(againTaskDetail.getId());
        inputFurnaceBurden.setVehicleCode(taskPrepare.getCarrierNo());
    }

    /**
     * 发送消息到精彩群
     */
    private void robotSeedMessage(String equipmentCode, Integer againNum) {
        try {
            ArrayList<String> sceneList = new ArrayList<>();
            ArrayList<String> groupNameList = new ArrayList<>();
            sceneList.add("prod");
            groupNameList.add("母合金报料群");
            SeedMassageDto seedMassageDto = new SeedMassageDto();
            seedMassageDto.setContent(equipmentCode + "炉台,系统以过账，需要领母合金" + "复投次数:" + againNum);
            seedMassageDto.setScene(sceneList);
            seedMassageDto.setGroupName(groupNameList);
            seedMassageDto.setStatus(SeedMassageEnum.GROUP);
            seedMassageDto.setSource("预装料任务缓存库拉出");
            dingTalkService.seedMassage(seedMassageDto);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result build(InspectionBindingInfoDto inspectionBindingInfoDto) {
        InspectionRecordDto inspectionRecordDto = toSpellInfo(inspectionBindingInfoDto);
        return inspectionRecordService.build(inspectionRecordDto);
    }

    @Override
    public HiddenCrackDetectionVo hiddenCrackDetection(HiddenCrackDetectionDto hiddenCrackDetectionDto) {
        HiddenCrackDetectionVo hiddenCrackDetectionVo = new HiddenCrackDetectionVo();
        YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(hiddenCrackDetectionDto.getSectionNo());
        if (Objects.isNull(ybInspectData)) {
            throw new RuntimeException("该晶编号"+hiddenCrackDetectionDto.getSectionNo()+"未查询到圆棒信息");
        }
        ybInspectData.setActualLength(hiddenCrackDetectionDto.getActualLength());
        ybInspectData.setTwinCrystalPosition(hiddenCrackDetectionDto.getTwinCrystalPosition());
        ybInspectData.setTwinCrystalLength(hiddenCrackDetectionDto.getTwinCrystalLength());
        ybInspectData.setTwinBandedPosition(hiddenCrackDetectionDto.getTwinBandedPosition());
        ybInspectData.setTwinBandedLength(hiddenCrackDetectionDto.getTwinBandedLength());
        ybInspectData.setFissurePosition(hiddenCrackDetectionDto.getFissurePosition());
        ybInspectData.setFissureLength(hiddenCrackDetectionDto.getFissureLength());
        ybInspectData.setObliquePosition(hiddenCrackDetectionDto.getObliquePosition());
        ybInspectData.setObliqueLength(hiddenCrackDetectionDto.getObliqueLength());
        ybInspectData.setStepPosition(hiddenCrackDetectionDto.getStepPosition());
        ybInspectData.setStepLength(hiddenCrackDetectionDto.getStepLength());
        ybInspectData.setCrestPosition(hiddenCrackDetectionDto.getCrestPosition());
        ybInspectData.setCrestLength(hiddenCrackDetectionDto.getCrestLength());
        ybInspectData.setObliqueA(hiddenCrackDetectionDto.getObliqueA());
        ybInspectData.setObliqueB(hiddenCrackDetectionDto.getObliqueB());
        ybInspectDataService.saveOrUpdate(ybInspectData);
        hiddenCrackDetectionVo.setSectionNo(ybInspectData.getSectionNo());
        hiddenCrackDetectionVo.setLength(ybInspectData.getActualLength());
        hiddenCrackDetectionVo.setSpecs(getProductType(ybInspectData.getPlanSpecs()));
        return hiddenCrackDetectionVo;
    }
    /**
     * 规格转换
     */
    private String getProductType(String productType) {
        List<DictionaryItem> toMCSProductSpec = dictionaryItemService.findByThemeValueAndEnable("ToMCSProductSpec", true);
        Map<String, DictionaryItem> specMap = toMCSProductSpec.stream().collect(Collectors.toMap(DictionaryItem::getName, Function.identity(), (t1, t2) -> t1));
        if (specMap.containsKey(productType)) {
            return specMap.get(productType).getValue();
        } else {
            return "0";
        }
    }
    private BigDecimal getWeight(List<McsMaterialDto> materialList) {
        BigDecimal total = BigDecimal.ZERO;
        for (McsMaterialDto dto : materialList) {
            total = total.add(dto.getMaterialWeight() == null ? BigDecimal.ZERO : dto.getMaterialWeight());
        }
        return total;
    }

    public AgainTaskDetailDto toLazyDto(AgainTaskDetail entity) {
        return modelMapper.map(entity, AgainTaskDetailDto.class);
    }

    public LoadingTaskDto toLazyDto(LoadingTask entity) {
        return modelMapper.map(entity, LoadingTaskDto.class);
    }

    public SquareOrderMesResultDto toLazyDto(RankResultDto entity) {
        return modelMapper.map(entity, SquareOrderMesResultDto.class);
    }

    public DislocationInfo toLazyDto(DislocationInfoDto entity) {
        return modelMapper.map(entity, DislocationInfo.class);
    }

    public DislocationExceptionInfo toLazyDto(DislocationExceptionInfoDto entity) {
        return modelMapper.map(entity, DislocationExceptionInfo.class);
    }

    public InspectionRecordDto toSpellInfo(InspectionBindingInfoDto inspectionBindingInfoDto) {
        InspectionRecordDto inspectionRecordDto = new InspectionRecordDto();
        LongCrystal longCrystal = longCrystalService.findByCrystalNo(inspectionBindingInfoDto.getCrystalNo());
        if (longCrystal == null)
            throw new RuntimeException("长晶棒【" + inspectionBindingInfoDto.getCrystalNo() + "】不存在产出记录！");
        String locationNo = inspectionBindingInfoDto.getLocationNo();
        inspectionRecordDto.setEquipmentCode(longCrystal.getEquipmentCode());
        inspectionRecordDto.setLotNo(longCrystal.getLotNo());
        inspectionRecordDto.setSeries(longCrystal.getSeries());
        inspectionRecordDto.setArea(longCrystal.getArea());
        inspectionRecordDto.setCrystalNo(inspectionBindingInfoDto.getCrystalNo());
        inspectionRecordDto.setWindUp(longCrystal.getWindUp());
        inspectionRecordDto.setAgainNum(longCrystal.getAgainNum());
        inspectionRecordDto.setCrystalNum(longCrystal.getCrystalNum());
        inspectionRecordDto.setLength(longCrystal.getLength());
        inspectionRecordDto.setWeight(longCrystal.getWeight());
        inspectionRecordDto.setPailNum(inspectionBindingInfoDto.getPailNum());
        inspectionRecordDto.setLandmarkCode(inspectionBindingInfoDto.getEndCode());
        inspectionRecordDto.setAbnormal("");
        inspectionRecordDto.setLocationNo(locationNo);
        inspectionRecordDto.setUserName("mcs");
//        inspectionRecordDto.setClassNo();
//        inspectionRecordDto.setTeamGroup();
        inspectionRecordDto.setBuildTime(new Date());
        inspectionRecordDto.setLongCrystalId(longCrystal.getId());
        inspectionRecordDto.setIsAuto(true);

        return inspectionRecordDto;
    }
}
