package com.sw.mes.fb.aio.controller;

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.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.EapCutCraftDto;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.*;
import com.sw.mes.base.factory.init.dto.MachineCapacityKf.MachineCapacityKfDto;
import com.sw.mes.base.factory.init.entity.ClassMonitorModel;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.entity.MachineCapacityKf;
import com.sw.mes.base.factory.init.service.ClassMonitorModelService;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.factory.init.service.MachineCapacityKfService;
import com.sw.mes.fb.aio.dto.*;
import com.sw.mes.fb.aio.entity.*;
import com.sw.mes.fb.aio.service.*;
import com.sw.mes.fb.checkout.dao.RecutDetailDao;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Date: Create in
 * @Modified By: EAP-MES数据上报接口
 */
@RestController
@RequestMapping("/eapStateUpload")
@Slf4j
@Api(description = "EAP-MES数据上报接口")
public class EapStateUploadController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private EapStateUploadService eapStateUploadService;

    @Autowired
    private EapCutCraftService eapCutCraftService;

    @Autowired
    private EapIngredientsTimesService eapIngredientsTimesService;

    @Autowired
    private EapSpecificationSendService eapSpecificationSendService;

    @Autowired
    private EapRetreatFeedbackService eapRetreatFeedbackService;

    @Autowired
    private EapEvolutionRackService eapEvolutionRackService;

    @Autowired
    private EapEvolutionRecordService eapEvolutionRecordService;

    @Autowired
    private EapGrindingRackService eapGrindingRackService;

    @Autowired
    private EapGrindingMachineService eapGrindingMachineService;

    @Autowired
    private EapGoldBreakService eapGoldBreakService;

    @Autowired
    private EapOpenHoursService eapOpenHoursService;

    @Autowired
    private EapGrindingHoursService eapGrindingHoursService;

    @Autowired
    private EapEvolutionBlankingService eapEvolutionBlankingService;

    @Autowired
    private EapGrindingReportService eapGrindingReportService;

    @Autowired
    private EapGrindingTaskService eapGrindingTaskService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private MachineCapacityKfService machineCapacityKfService;

    @Autowired
    private GrindingBlankingService grindingBlankingService;

    @Autowired
    private RecutDetailDao recutDetailDao;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private EapCutRecordService eapCutRecordService;

    @Autowired
    private ClassMonitorModelService classMonitorModelService;

    @Autowired
    private EapCutCraftShortService eapCutCraftShortService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CutProcessRecordService cutProcessRecordService;

    @ApiOperation(value = "上传截断机设备状态上报(文档01)")
    @PostMapping("/guillotineStateUpload")
    public Result create(@RequestBody @Valid @ApiParam(value = "EAP状态上报") EapStateUploadDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapStateUpload eapStateUpload = fromDto(dto);
        eapStateUpload.setSource(1);
        eapStateUpload.setCreatedTime(new Date());
        eapStateUploadService.saveOrUpdate(eapStateUpload);
        return ResultGenerator.success("接收完成");
    }

    @ApiOperation(value = "上传开方设备状态上传(文档05)")
    @PostMapping("/evolutionStateUpload")
    public Result evolutionStateUpload(@RequestBody @Valid @ApiParam(value = "EAP状态上报") EapStateUploadDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapStateUpload eapStateUpload = fromDto(dto);
        eapStateUpload.setSource(2);
        eapStateUpload.setCreatedTime(new Date());
        eapStateUploadService.saveOrUpdate(eapStateUpload);
        return ResultGenerator.success("接收完成");
    }

    @ApiOperation(value = "上传磨削机设备状态上传(文档06)")
    @PostMapping("/grindingStateUpload")
    public Result grindingStateUpload(@RequestBody @Valid @ApiParam(value = "EAP状态上报") EapStateUploadDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapStateUpload eapStateUpload = fromDto(dto);
        eapStateUpload.setSource(3);
        eapStateUpload.setCreatedTime(new Date());
        eapStateUploadService.saveOrUpdate(eapStateUpload);
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "上传EAP截断工艺上报(文档02)")
    @PostMapping("/cutCraftUpload")
    public Result cutCraftUpload(@RequestBody @Valid @ApiParam(value = "EAP截断工艺上报对象") EapCutCraftShortDto eapCutCraftShortDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (eapCutCraftShortDto.getRoundSn() == null) {
            throw new BusinessException("圆棒SN不能为空");
        }
        EapCutCraftShort eapCutCraftShort = fromDto(eapCutCraftShortDto);

        //用于记录线速度等工艺数据
        eapCutCraftShortService.saveOrUpdate(eapCutCraftShort);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "上传截断工艺人工上报")
    @PostMapping("/cutCraftArtificialUpload")
    public Result cutCraftArtificialUpload(@RequestBody @Valid @ApiParam(value = "上传截断工艺人工上报") EapCutCraftDto eapCutCraftDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (StringUtils.isBlank(eapCutCraftDto.getRoundSn())) {
            return ResultGenerator.fail("圆棒SN不能为空");
        }

        //     截断过站地方已经处理过，进站出站
//        // 查询加工工单信息，判断是否是本站点的加工品
//        wipStorageService.selectWipStorage(eapCutCraft.getRoundSn(), EnumValuesFactory.WipStorageCode.截断.getKey(), false);
//        if (eapCutCraft.getStartCut() != null) {
//            wipStorageService.inStation(eapCutCraft.getRoundSn(), EnumValuesFactory.WipStorageStatus.已进站.getValue());
//        } else {
//            wipStorageService.outStation(eapCutCraft.getRoundSn(), EnumValuesFactory.WipStorageStatus.已出站.getValue(), false);
//        }
        return eapCutCraftService.saveEapCutCraftInfo(eapCutCraftDto, 1);
    }

    @ApiOperation(value = "上传开方磨削工艺人工上报")
    @PostMapping("/openGrinding")
    public Result openGrinding(@RequestBody @Valid @ApiParam(value = "上传截断工艺人工上报") EapCutCraftDto eapCutCraftDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (StringUtils.isBlank(eapCutCraftDto.getRoundSn())) {
            return ResultGenerator.fail("SN不能为空");
        }
        if("KF".equals(eapCutCraftDto.getWipStorageCode())) {
            EapEvolutionRack eapEvolutionRack = eapEvolutionRackService.findTopBySnOrderByIdDesc(eapCutCraftDto.getRoundSn());
            if (null == eapEvolutionRack) {
                eapEvolutionRack = new EapEvolutionRack();
                eapEvolutionRack.setEquipNo(eapCutCraftDto.getEquipNo());
                eapEvolutionRack.setSn(eapCutCraftDto.getRoundSn());
                eapEvolutionRack.setCreatedTime(eapCutCraftDto.getStartCut());
                eapEvolutionRack.setHeadLoading(eapCutCraftDto.getCutOperator());
                eapEvolutionRackService.saveOrUpdate(eapEvolutionRack);
            }

            EapEvolutionBlanking topBySnOrderByIdDesc = eapEvolutionBlankingService.findTopBySnOrderByIdDesc(eapCutCraftDto.getRoundSn());
            if(null == topBySnOrderByIdDesc){
                // 开方下料，向后延迟10~20分钟
                Random random = new Random();
                int randomNumber = random.nextInt(10);
                int index = 10;
                topBySnOrderByIdDesc = new EapEvolutionBlanking();
                topBySnOrderByIdDesc.setEquipNo(eapCutCraftDto.getEquipNo());
                topBySnOrderByIdDesc.setSn(eapCutCraftDto.getRoundSn());
                if (null != eapCutCraftDto.getStartCut()) {
                    topBySnOrderByIdDesc.setCreatedTime(new Date(eapCutCraftDto.getStartCut().getTime() + 1000 * 60 * (index + randomNumber)));
                } else {
                    topBySnOrderByIdDesc.setCreatedTime(new Date(new Date().getTime() + 1000 * 60 * (index + randomNumber)));
                }
                topBySnOrderByIdDesc.setHeadLoading(eapCutCraftDto.getCutOperator());
                eapEvolutionBlankingService.saveOrUpdate(topBySnOrderByIdDesc);
            }

            Boolean flag = false;
            List<DictionaryItem> dictionaryItemList = dictionaryItemService.findByThemeValueAndEnable("GrindingBlanking", true);
            if(!dictionaryItemList.isEmpty() && !StringUtils.isEmpty(dictionaryItemList.get(0).getValue())){
                DictionaryItem dictionaryItem = dictionaryItemList.get(0);
                String value = dictionaryItem.getValue().trim();
                if("1".equals(value)){
                    flag = true;
                }
            }
            if(flag){
                int index = 40;
                // 磨削下料，向后延迟40~55分钟上下
                saveGrindingBlanking(eapCutCraftDto,index);
            }
        }
        if("MX".equals(eapCutCraftDto.getWipStorageCode())) {
            EapGrindingRack topBySn = eapGrindingRackService.findTopBySnOrderByIdDesc(eapCutCraftDto.getRoundSn());
            if(null == topBySn){
                topBySn = new EapGrindingRack();
                topBySn.setEquipNo(eapCutCraftDto.getEquipNo());
                topBySn.setSn(eapCutCraftDto.getRoundSn());
                topBySn.setCreatedTime(eapCutCraftDto.getStartCut());
                topBySn.setHeadLoading(eapCutCraftDto.getCutOperator());
                eapGrindingRackService.save(topBySn);
            }
            int index = 15;
            saveGrindingBlanking(eapCutCraftDto,index);
        }
        return ResultGenerator.success();
    }

    private void saveGrindingBlanking(EapCutCraftDto eapCutCraftDto,int index) {
        GrindingBlanking grindingBlanking1 = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(eapCutCraftDto.getRoundSn());
        if (null == grindingBlanking1) {
            grindingBlanking1 = new GrindingBlanking();
            grindingBlanking1.setSn(eapCutCraftDto.getRoundSn());
        }
        Random random = new Random();
        int randomNumber = random.nextInt(15);
        if("MX".equals(eapCutCraftDto.getWipStorageCode())) {
            grindingBlanking1.setEquipNo(eapCutCraftDto.getEquipNo());
            index = 0;
        } else {
            index = 1000 * 60 * (index + randomNumber);
        }


        if (null != eapCutCraftDto.getStartCut()) {
            grindingBlanking1.setCreatedTime(new Date(eapCutCraftDto.getStartCut().getTime() + index));
        } else {
            grindingBlanking1.setCreatedTime(new Date(new Date().getTime() + index));
        }
        grindingBlanking1.setEquipNo("MD1001");
        grindingBlanking1.setHeadLoading(eapCutCraftDto.getCutOperator());
        grindingBlankingService.saveOrUpdate(grindingBlanking1);

    }


    @ApiOperation(value = "创建截断加工上下料记录")
    @PostMapping("/eapCutRecordUploading")
    public Result eapCutRecordUploading(@RequestBody @Valid @ApiParam(value = "截断加工上下料记录对象") EapCutRecordDto eapCutRecordDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (eapCutRecordDto.getRoundSn() == null) {
            throw new BusinessException("圆棒SN不能为空");
        }

        return eapCutRecordService.saveCutRecord(eapCutRecordDto);
    }


    @ApiOperation(value = "上传EAP辅料使用次数上传(文档03)")
    @PostMapping("/ingredientsTimesUpload")
    public Result ingredientsTimesUpload(@RequestBody @Valid @ApiParam(value = "EAP辅料使用次数上传对象") EapIngredientsTimesDto eapIngredientsTimesDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapIngredientsTimes eapIngredientsTimes = fromDto(eapIngredientsTimesDto);
        eapIngredientsTimes.setCreatedTime(new Date());
        eapIngredientsTimesService.saveOrUpdate(eapIngredientsTimes);
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "开方/磨削加工规格下发")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "category", value = "设备类别", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "equipmentCode", value = "编号", dataType = "string", paramType = "query"),})
    @GetMapping("/getSpecificationByEquipNo")
    public Result<MachineCapacityKfDto> getSpecificationByEquipNo(String category, String equipmentCode) {
        MachineCapacityKf machineCapacityKf = machineCapacityKfService.getSpecificationByEquipNo(category, equipmentCode);
        if (null == machineCapacityKf)
            return ResultGenerator.fail("该设备加工能力不存在");
        return ResultGenerator.success(toEagerDto(machineCapacityKf));
    }

    @ApiOperation(value = "上传开方/磨削加工规格下发(文档07)")
    @PostMapping("/specificationSend")
    public Result specificationSend(@RequestBody @Valid @ApiParam(value = "EAP开方/磨削加工规格上传") EapSpecificationSendDto eapSpecificationSendDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapSpecificationSend eapSpecificationSend = fromDto(eapSpecificationSendDto);
        eapSpecificationSend.setCreatedTime(new Date());
        eapSpecificationSend.setSource(1);
        eapSpecificationSendService.saveOrUpdate(eapSpecificationSend);
        return ResultGenerator.success("接收完成");
    }

    @ApiOperation(value = "上传开方/磨削加工规格上传(文档08)")
    @PostMapping("/specificationUpload")
    public Result specificationUpload(@RequestBody @Valid @ApiParam(value = "EAP开方/磨削加工规格上传") EapSpecificationSendDto eapSpecificationSendDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapSpecificationSend eapSpecificationSend = fromDto(eapSpecificationSendDto);
        eapSpecificationSend.setCreatedTime(new Date());
        eapSpecificationSend.setSource(2);
        eapSpecificationSendService.saveOrUpdate(eapSpecificationSend);
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "上传EAP开方退库反馈接口(文档09)")
    @PostMapping("/retreatFeedback")
    public Result retreatFeedback(@RequestBody @Valid @ApiParam(value = "EAP开方退库反馈接口对象") EapRetreatFeedbackDto eapRetreatFeedbackDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapRetreatFeedback eapRetreatFeedback = fromDto(eapRetreatFeedbackDto);
        eapRetreatFeedback.setCreatedTime(new Date());
        eapRetreatFeedbackService.saveOrUpdate(eapRetreatFeedback);
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "上传EAP开方上料接口(文档10)")
    @PostMapping("/evolutionRack")
    public Result evolutionRack(@RequestBody @Valid @ApiParam(value = "EAP开方上料接口对象") CutCrystalDto cutCrystalDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapEvolutionRack eapEvolutionRack = fromDto(cutCrystalDto);
        if(null == eapEvolutionRack || StringUtils.isBlank(eapEvolutionRack.getSn())){
            return ResultGenerator.fail("数据异常或sn为空");
        }
        EapEvolutionRack topBySn = eapEvolutionRackService.findTopBySn(eapEvolutionRack.getSn());
        if(null != topBySn){
            return ResultGenerator.fail("sn重复");
        }
        eapEvolutionRack.setCreatedTime(new Date());
        eapEvolutionRack.setHeadLoading(BaseContextHandler.getUsername());
        eapEvolutionRackService.save(eapEvolutionRack);
        return ResultGenerator.success("接收完成");
    }

    @ApiOperation(value = "上传EAP开方下料(文档11)")
    @PostMapping("/evolutionBlanking")
    public Result evolutionBlanking(@RequestBody @Valid @ApiParam(value = "EAP开方下料") CutCrystalDto cutCrystalDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapEvolutionBlanking eapEvolutionBlanking = fromDtoBaiting(cutCrystalDto);
        if(StringUtils.isBlank(eapEvolutionBlanking.getSn())){
            return ResultGenerator.fail("sn不能为空");
        }
        // 查询加工工单信息，判断是否是本站点的加工品
        //PlanProcessingOrderWipStorageDto planProcessingOrderWipStorageDto = wipStorageService.selectWipStorage(eapEvolutionBlankingDto.getSn(), EnumValuesFactory.WipStorageCode.开方.getKey(), false);
        //wipStorageService.outStation(eapEvolutionBlankingDto.getSn(), null, 1);
        eapEvolutionBlanking.setCreatedTime(new Date());
        eapEvolutionBlanking.setHeadLoading(BaseContextHandler.getUsername());
        ClassMonitorModel classMonitorModel = classMonitorModelService.findByEquipmentCode(eapEvolutionBlanking.getEquipNo());
        if (classMonitorModel != null) {
            eapEvolutionBlanking.setTrimmingMan(classMonitorModel.getUser() != null ? classMonitorModel.getUser().getWorkNo() : "");
        }
        EapEvolutionBlanking topBySnOrderByIdDesc = eapEvolutionBlankingService.findTopBySnOrderByIdDesc(eapEvolutionBlanking.getSn());
        if(null != topBySnOrderByIdDesc){
            return ResultGenerator.fail("sn重复");
        }
        eapEvolutionBlankingService.saveOrUpdate(eapEvolutionBlanking);

        try {
            Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(eapEvolutionBlanking.getSn());
            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) {
                ybFeignClients.inAndOutStation(eapEvolutionBlanking.getSn(), eapEvolutionBlanking.getEquipNo(), EnumValuesFactory.WipStorageCode.开方.getKey(), 0);
            }
        } catch (BusinessException e) {
            e.printStackTrace();
            log.error(eapEvolutionBlanking.getSn() + "进出站失败");
        }
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "上传EAP开方加工记录上传(文档12)")
    @PostMapping("/evolutionRecord")
    public Result evolutionRecord(@RequestBody @Valid @ApiParam(value = "EAP开方加工记录上传对象") CutCrystalDto cutCrystalDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapEvolutionRecord eapEvolutionRecord = fromDtoProcess(cutCrystalDto);
        if(StringUtils.isBlank(eapEvolutionRecord.getSn())){
            return ResultGenerator.fail("sn不能为空");
        }
        EapEvolutionRecord topBySnOrderByIdDesc = eapEvolutionRecordService.findTopBySnOrderByIdDesc(eapEvolutionRecord.getSn());
        if(null != topBySnOrderByIdDesc){
            return ResultGenerator.fail("sn重复");
        }
        eapEvolutionRecord.setCreatedTime(new Date());
        ClassMonitorModel classMonitorModel = classMonitorModelService.findByEquipmentCode(eapEvolutionRecord.getEquipNo());
        if (classMonitorModel != null) {
            eapEvolutionRecord.setTrimmingMan(classMonitorModel.getUser() != null ? classMonitorModel.getUser().getWorkNo() : "");
            eapEvolutionRecord.setClassNoName(classMonitorModel.getClassNoName());
            eapEvolutionRecord.setTrimmingManCode(classMonitorModel.getUserCode());
        }
        eapEvolutionRecordService.saveOrUpdate(eapEvolutionRecord);
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "磨削上料(文档13)")
    @PostMapping("/grindingRack")
    public Result grindingRack(@RequestBody @Valid @ApiParam(value = "EAP开方加工记录上传对象") CutCrystalDto cutCrystalDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapGrindingRack eapGrindingRack = fromDtoGrindingFeed(cutCrystalDto);
        if(StringUtils.isBlank(eapGrindingRack.getSn())){
            return ResultGenerator.fail("sn不能为空");
        }
        EapGrindingRack topBySn = eapGrindingRackService.findTopBySnOrderByIdDesc(eapGrindingRack.getSn());
        if(null != topBySn){
            return ResultGenerator.fail("sn重复");
        }
        // 查询加工工单信息，判断是否是本站点的加工品
//        PlanProcessingOrderWipStorageDto planProcessingOrderWipStorageDto = wipStorageService.selectWipStorage(eapGrindingRack.getSn(), EnumValuesFactory.WipStorageCode.磨削.getKey(), false);
//        wipStorageService.inStation(eapGrindingRack.getSn(), EnumValuesFactory.WipStorageStatus.已进站.getValue());
        eapGrindingRack.setCreatedTime(new Date());
        eapGrindingRackService.save(eapGrindingRack);
        return ResultGenerator.success("接收完成");
    }

    @ApiOperation(value = "磨削下料上传(文档14)")
    @PostMapping("/grindingBlanking")
    public Result create(@RequestBody @Valid @ApiParam(value = "磨削下料上传对象") CutCrystalDto cutCrystalDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        GrindingBlanking grindingBlanking = fromGringBlankingDto(cutCrystalDto);
        Date date = new Date();
        grindingBlanking.setCreatedTime(date);
        // 计算边长直径等
        grindingBlankingService.calculate(grindingBlanking);
        //
//        if (StringUtils.isBlank(grindingBlanking.getSn())) {
//            return ResultGenerator.fail("sn不能为空");
//        }
//        GrindingBlanking grindingBlanking1 = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(grindingBlanking.getSn());
//        if (null != grindingBlanking1) {
//            return ResultGenerator.fail("sn重复");
//        }

        if(!StringUtils.isBlank(grindingBlanking.getSn())) {
            GrindingBlanking grindingBlanking1 = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(grindingBlanking.getSn());
            if (null != grindingBlanking1) {
//                if (null != grindingBlanking1.getGrindingOrder()) {
//                    return ResultGenerator.fail("sn重复");
//                }
                grindingBlanking.setId(grindingBlanking1.getId());
                grindingBlanking.setHeadLoading(grindingBlanking1.getHeadLoading());
            }
        }
        grindingBlanking.setCreatedTime(date);
        grindingBlanking.setHeadLoading(BaseContextHandler.getUsername());
        String equipNo = grindingBlanking.getEquipNo();
        EapEvolutionRack eapEvolutionRack = eapEvolutionRackService.findTopBySnOrderByIdDesc(grindingBlanking.getSn());
        Random random = new Random();
        int randomNumber = random.nextInt(15);
        if(null == eapEvolutionRack){
            eapEvolutionRack = new EapEvolutionRack();
            eapEvolutionRack.setEquipNo(equipNo);
            eapEvolutionRack.setSn(grindingBlanking.getSn());
            // 没有开方数据，模拟生成开方数据，时间向前40分钟上下
            eapEvolutionRack.setCreatedTime(new Date(date.getTime() - 1000 * 60 * (40 + randomNumber)));
            eapEvolutionRack.setHeadLoading("eap");
            eapEvolutionRackService.saveOrUpdate(eapEvolutionRack);
        } else {
            Date createdTime = eapEvolutionRack.getCreatedTime();
            long end = date.getTime() - createdTime.getTime();
            // 磨削开方时间相差大于40分钟
            if(end < 1000 * 60 * 40){
                eapEvolutionRack.setCreatedTime(new Date(date.getTime() - 1000 * 60 * (40 + randomNumber)));
                eapEvolutionRackService.saveOrUpdate(eapEvolutionRack);
            }
        }
        String grindingOrderKey = "grindingOrderKey";
        RLock redissonLock = redissonClient.getLock(grindingOrderKey + "-" + equipNo);
        try {
            redissonLock.lock();
            int count;
            String shift = getShift(DateUtil.formatDate(date, DateUtil.longFormat));
            GrindingBlanking byEquipNo = grindingBlankingService.findByEquipNo(equipNo);
            Date lastTime;
            if (null == byEquipNo || byEquipNo.getGrindingOrder() == null) {
                lastTime = new Date();
                count = 0;
            } else {
                lastTime = byEquipNo.getCreatedTime();
                count = Integer.parseInt(byEquipNo.getGrindingOrder());
            }
            String shift1 = getShift(DateUtil.formatDate(lastTime, DateUtil.longFormat));
            if (!shift.equals(shift1)) {
                // 班次不一样,次数被重置
                count = 1;
            } else {
                count++;
            }
            grindingBlanking.setGrindingOrder(String.valueOf(count));
            grindingBlankingService.save(grindingBlanking);
        }finally {
            redissonLock.unlock();
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "计算方棒边长直径")
    @PostMapping("/calculate")
    public Result calculate(@RequestBody @Valid @ApiParam(value = "磨削下料上传对象") GrindingBlanking grindingBlanking, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        // 计算边长直径等
        Map<String, Object> calculate = grindingBlankingService.calculate(grindingBlanking);
        return ResultGenerator.success(calculate);
    }


    @ApiOperation(value = "截断数据上传")
    @PostMapping("/CutProcessRecordUpload")
    public Result CutProcessRecordUpload(@RequestBody @Valid @ApiParam(value = "截断数据上传") CutCrystalDto cutCrystalDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        CutProcessRecord cutProcessRecord = fromCutProcessRecordDto(cutCrystalDto);
        if (StringUtils.isEmpty(cutProcessRecord.getCrystalNo())) {
            return ResultGenerator.fail("sn为空");
        }
        List<CutProcessRecord> cutProcessRecordList = cutProcessRecordService.findTopByCrystalNo(cutProcessRecord.getCrystalNo());
        if (!cutProcessRecordList.isEmpty()) {
            return ResultGenerator.fail("sn重复");
        }
        cutProcessRecord.setCreateTime(new Date());
        cutProcessRecordService.saveOrUpdate(cutProcessRecord);

        return ResultGenerator.success();
    }

    /**
     * 获取班次
     *
     * @param time
     * @return
     */
    public static String getShift(String time) {
        if (!StringUtils.isBlank(time)) {
            String hourTime = time.substring(11, 13);
            Integer integer = Integer.valueOf(hourTime);
            String substring = time.substring(14, 16);
            Integer minute = Integer.valueOf(substring);
            if (integer >= 8 && integer < 20) {
                if (integer == 8 && minute < 30) {
                    return "B";
                }
                // 白班
                return "A";
            } else {
                if (integer == 20 && minute < 30) {
                    return "A";
                }
                return "B";
            }
        }
        return null;
    }


    @ApiOperation(value = "上传EAP磨削加工记录上传(文档15)")
    @PostMapping("/grindingMachine")
    public Result create(@RequestBody @Valid @ApiParam(value = "EAP磨削加工记录上传对象") EapGrindingMachineDto eapGrindingMachineDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapGrindingMachine eapGrindingMachine = fromDto(eapGrindingMachineDto);
        ClassMonitorModel classMonitorModel = classMonitorModelService.findByEquipmentCode(eapGrindingMachineDto.getEquipNo());
        if (classMonitorModel != null) {
            eapGrindingMachine.setGrindingMan(classMonitorModel.getUser() != null ? classMonitorModel.getUser().getWorkNo() : "");
            eapGrindingMachine.setClassNoName(classMonitorModel.getClassNoName());
            eapGrindingMachine.setGrindingManCode(classMonitorModel.getUserCode());
        }
        //生成一体机编码
        eapGrindingMachineService.createOneBodyMachineCode(eapGrindingMachine);
        eapGrindingMachine.setCreatedTime(new Date());
        eapGrindingMachineService.saveOrUpdate(eapGrindingMachine);
        return ResultGenerator.success("接收完成");
    }

    @ApiOperation(value = "创建EAP开方磨削机机任务触发(文档16)")
    @PostMapping("/eapGrindingTask")
    public Result create(@RequestBody @Valid @ApiParam(value = "EAP开方磨削机机任务触发对象") EapGrindingTaskDto eapGrindingTaskDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapGrindingTask eapGrindingTask = fromDto(eapGrindingTaskDto);
        eapGrindingTask.setCreatedTime(new Date());
        eapGrindingTaskService.saveOrUpdate(eapGrindingTask);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "磨削报警下发（文档17）")
    @PostMapping("/eapGrindingReport")
    public Result create(@RequestBody @Valid @ApiParam(value = "磨削报警下发") EapGrindingReportDto eapGrindingReportDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapGrindingReport eapGrindingReport = fromDto(eapGrindingReportDto);
        eapGrindingReport.setCreatedTime(new Date());
        eapGrindingReportService.saveOrUpdate(eapGrindingReport);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "金刚线断线记录上传(文档18)")
    @PostMapping("/goldBreakUpload")
    public Result create(@RequestBody @Valid @ApiParam(value = "金刚线断线记录上传") EapGoldBreakDto eapGoldBreakDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapGoldBreak eapGoldBreak = fromDto(eapGoldBreakDto);
        eapGoldBreak.setCreatedTime(new Date());
        eapGoldBreakService.saveOrUpdate(eapGoldBreak);
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "开方工时数据(文档19)")
    @PostMapping("/openHoursUpload")
    public Result create(@RequestBody @Valid @ApiParam(value = "EAP开方工时数据对象") EapOpenHoursDto eapOpenHoursDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapOpenHours eapOpenHours = fromDto(eapOpenHoursDto);
        //查询设备对应模块
        Equipment equipment = equipmentService.findByCode(eapOpenHoursDto.getEquip());
        if (equipment != null) {
            eapOpenHours.setModule(equipment.getArea());
        }
        eapOpenHours.setCreatedTime(new Date());
        ClassMonitorModel classMonitorModel = classMonitorModelService.findByEquipmentCode(eapOpenHoursDto.getEquip());
        if (classMonitorModel != null) {
            eapOpenHours.setOperator(classMonitorModel.getUser() != null ? classMonitorModel.getUser().getWorkNo() : "");
        }

        eapOpenHours.setTotalHours(eapOpenHours.getTotalHours() == null ? "720" : eapOpenHours.getTotalHours());
        eapOpenHoursService.saveOrUpdate(eapOpenHours);
        return ResultGenerator.success("接收完成");
    }


    @ApiOperation(value = "EAP磨削工时数据(文档20)")
    @PostMapping("/grindingHoursUpload")
    public Result create(@RequestBody @Valid @ApiParam(value = "EAP磨削工时数据对象") EapGrindingHoursDto eapGrindingHoursDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        EapGrindingHours eapGrindingHours = fromDto(eapGrindingHoursDto);
        //查询设备对应模块
        Equipment equipment = equipmentService.findByCode(eapGrindingHours.getEquip());
        if (equipment != null) {
            eapGrindingHours.setModule(equipment.getArea());
        }
        eapGrindingHours.setCreatedTime(new Date());
        ClassMonitorModel classMonitorModel = classMonitorModelService.findByEquipmentCode(eapGrindingHoursDto.getEquip());
        if (classMonitorModel != null) {
            eapGrindingHours.setOperator(classMonitorModel.getUser() != null ? classMonitorModel.getUser().getWorkNo() : "");
        }
        eapGrindingHours.setTotalHours(eapGrindingHours.getTotalHours() == null ? "720" : eapGrindingHours.getTotalHours());
        eapGrindingHoursService.saveOrUpdate(eapGrindingHours);
        return ResultGenerator.success("接收完成");
    }

    @ApiOperation(value = "EAP磨削工时数据详细信息")
    @GetMapping("/{id}")
    public Result<EapGrindingReportDto> get(@PathVariable @ApiParam(value = "EAP磨削工时数据id") Long id) {
        EapGrindingReport eapGrindingReport = eapGrindingReportService.get(id);
        if (null == eapGrindingReport) return ResultGenerator.fail("该EAP磨削工时数据不存在");
        return ResultGenerator.success(toEagerDto(eapGrindingReport));
    }


    @ApiOperation(value = "截断数据报表")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_roundSN", value = "单晶编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_equipNo", value = "截断机编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_crystalType", value = "截断类别", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_startCut", value = "截断开始时间起", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_startCut", value = "截断开始时间始", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_endCut", value = "截断结束时间起", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_endCut", value = "截断结束时间始", dataType = "string", paramType = "query")})
    @GetMapping("/getCutRecordListPage")
    public Result<ResponsePage<TurnStoreOtherDto>> getCutRecordListPage(String search_LIKE_roundSN, String search_LIKE_equipNo, String search_EQ_crystalType, String search_GTE_startCut, String search_LT_startCut, String search_GTE_endCut, String search_LT_endCut, @ApiIgnore RequestPage requestPage) {
        requestPage.setOrderField(null);

        if (StringUtils.isBlank(search_LIKE_roundSN)) search_LIKE_roundSN = "";
        if (StringUtils.isBlank(search_LIKE_equipNo)) search_LIKE_equipNo = "";
        if (StringUtils.isBlank(search_EQ_crystalType)) search_EQ_crystalType = "";
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = formatter.format(currentTime);
        if (StringUtils.isBlank(search_GTE_startCut)) search_GTE_startCut = "2021-01-11 13:19:51";
        if (StringUtils.isBlank(search_LT_startCut)) search_LT_startCut = str;
        if (StringUtils.isBlank(search_GTE_endCut)) search_GTE_endCut = "2021-01-11 13:19:51";
        if (StringUtils.isBlank(search_LT_endCut)) search_LT_endCut = str;
        ResponsePage<TurnStoreOtherDto> responsePage = eapCutCraftService.getCutRecordListPage(search_EQ_crystalType, search_GTE_startCut, search_LT_startCut, search_GTE_endCut, search_LT_endCut, search_LIKE_roundSN, search_LIKE_equipNo, PageUtil.createPageable(requestPage));
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "截断数据报表导出")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_roundSN", value = "单晶编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_equipNo", value = "截断机编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_crystalType", value = "截断类别", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_startCut", value = "截断开始时间起", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_startCut", value = "截断开始时间始", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_endCut", value = "截断结束时间起", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_endCut", value = "截断结束时间始", dataType = "string", paramType = "query")})
    @GetMapping("/cut/export")
    public void cutExport(String search_LIKE_roundSN, String search_LIKE_equipNo, String search_EQ_crystalType, String search_GTE_startCut, String search_LT_startCut, String search_GTE_endCut, String search_LT_endCut, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
        try {
            if (StringUtils.isBlank(search_LIKE_roundSN)) search_LIKE_roundSN = "";
            if (StringUtils.isBlank(search_LIKE_equipNo)) search_LIKE_equipNo = "";
            if (StringUtils.isBlank(search_EQ_crystalType)) search_EQ_crystalType = "";
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = formatter.format(currentTime);
            if (StringUtils.isBlank(search_GTE_startCut)) search_GTE_startCut = "2021-01-11 13:19:51";
            if (StringUtils.isBlank(search_LT_startCut)) search_LT_startCut = str;
            if (StringUtils.isBlank(search_GTE_endCut)) search_GTE_endCut = "2021-01-11 13:19:51";
            if (StringUtils.isBlank(search_LT_endCut)) search_LT_endCut = str;
            List<TurnStoreOtherVo> list1 = eapCutCraftService.getCutRecordList(search_EQ_crystalType, search_GTE_startCut, search_LT_startCut, search_GTE_endCut, search_LT_endCut, search_LIKE_roundSN, search_LIKE_equipNo, requestPage);

            //收尾方式
            List<DictionaryItem> windUpMapList = dictionaryItemService.findByThemeValueAndEnable("windUpMap", true);
            //完结标识
            List<DictionaryItem> closureIdentificationList = dictionaryItemService.findByThemeValueAndEnable("closureIdentification", true);

            Map<String, String> windUpMapCollect = windUpMapList.stream().collect(Collectors.toMap(DictionaryItem::getValue, DictionaryItem::getName));
            Map<String, String> closureIdentificationCollect = closureIdentificationList.stream().collect(Collectors.toMap(DictionaryItem::getValue, DictionaryItem::getName));
            for (TurnStoreOtherVo dto : list1) {
                if (StringUtils.isBlank(dto.getWindUp())) {
                    dto.setWindUp("正常收尾");
                } else {
                    dto.setWindUp(windUpMapCollect.get(dto.getWindUp()));
                }
                if (StringUtils.isBlank(dto.getClosureIdentification())) {
                    dto.setClosureIdentification("无");
                } else {
                    dto.setClosureIdentification(closureIdentificationCollect.get(dto.getClosureIdentification()));
                }
            }

            EasyExcelUtils.write(response, TurnStoreOtherVo.class, "截断加工记录", "截断加工记录", list1);
        } catch (Exception e) {
            throw new RuntimeException("截断加工记录导出失败，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation(value = "辅料记录报表")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "search_EQ_equipType", value = "设备类型", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_equipNo", value = "设备编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_sn", value = "晶棒编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LT_startTime", value = "更换线日期开始时间", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LT_endTime", value = "更换线日期结束时间", dataType = "string", paramType = "query")})
    @GetMapping("/getGoldBreakListPage")
    public Result<ResponsePage<EapGoldBreakReportDto>> getGoldBreakListPage(String search_EQ_equipType, String search_LIKE_equipNo, String search_LIKE_sn, String search_LT_startTime, String search_LT_endTime, @ApiIgnore RequestPage requestPage) {
        requestPage.setOrderField(null);
        if (StringUtils.isBlank(search_LIKE_sn)) search_LIKE_sn = "";
        if (StringUtils.isBlank(search_LIKE_equipNo)) search_LIKE_equipNo = "";
        if (StringUtils.isBlank(search_EQ_equipType)) search_EQ_equipType = null;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = formatter.format(currentTime);
        if (StringUtils.isBlank(search_LT_startTime)) search_LT_startTime = "2021-01-11 13:19:51";
        if (StringUtils.isBlank(search_LT_endTime)) search_LT_endTime = str;
        ResponsePage<EapGoldBreakReportDto> responsePage = eapCutCraftService.getGoldBreakListPage(search_EQ_equipType, search_LIKE_equipNo, search_LIKE_sn, search_LT_startTime, search_LT_endTime, PageUtil.createPageable(requestPage));
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "开方记录报表")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_equip", value = "开方机编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_lotNo", value = "圆棒SN", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_GTE_startTrimming", value = "切割开始时间起", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LT_startTrimming", value = "切割开始时间始", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_GTE_endTrimming", value = "切割结束时间起", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LT_endTrimming", value = "切割结束时间始", dataType = "string", paramType = "query")})
    @GetMapping("/specificationListPage")
    public Result<ResponsePage<EapSpecificationReportDto>> specificationListPage(String search_LIKE_equip, String search_LIKE_lotNo, String search_GTE_startTrimming, String search_LT_startTrimming, String search_GTE_endTrimming, String search_LT_endTrimming, @ApiIgnore RequestPage requestPage) {
        requestPage.setOrderField(null);
        if (StringUtils.isBlank(search_LIKE_equip)) search_LIKE_equip = "";
        if (StringUtils.isBlank(search_LIKE_lotNo)) search_LIKE_lotNo = "";
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = formatter.format(currentTime);
        if (StringUtils.isBlank(search_GTE_startTrimming)) search_GTE_startTrimming = "2021-01-11 13:19:51";
        if (StringUtils.isBlank(search_LT_startTrimming)) search_LT_startTrimming = str;
        if (StringUtils.isBlank(search_GTE_endTrimming)) search_GTE_endTrimming = "2021-01-11 13:19:51";
        if (StringUtils.isBlank(search_LT_endTrimming)) search_LT_endTrimming = str;
        ResponsePage<EapSpecificationReportDto> responsePage = eapCutCraftService.specificationListPage(search_LIKE_equip, search_LIKE_lotNo, search_GTE_startTrimming, search_LT_startTrimming, search_GTE_endTrimming, search_LT_endTrimming, PageUtil.createPageable(requestPage));
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "根据方棒编号获取开方设备边长")
    @GetMapping("/getFbSideLength")
    public Result<String> getFbSideLength(@RequestParam(value = "sectionNo") String sectionNo) {
        EapEvolutionRecord eapEvolutionRecord = eapEvolutionRecordService.findTopBySnOrderByIdDesc(sectionNo);
        if (eapEvolutionRecord == null) {
            return ResultGenerator.fail("未查询到开方记录");
        }

        MachineCapacityKf machineCapacityKf = machineCapacityKfService.findTopeByEquipment_code(eapEvolutionRecord.getEquipNo());
        if (machineCapacityKf == null) {
            return ResultGenerator.fail("未查询到加工能力");
        }
        return ResultGenerator.success(machineCapacityKf.getSideLength().toString());
    }

    @ApiOperation(value = "磨削加工记录报表-弃用")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "equipType", value = "设备类型", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_equip", value = "开方机编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LIKE_sn", value = "单晶编号", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_GTE_startGrinding", value = "切割开始时间起", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LT_startGrinding", value = "切割开始时间始", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_GTE_endGrinding", value = "切割结束时间起", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "search_LT_endGrinding", value = "切割结束时间始", dataType = "string", paramType = "query")})
    @GetMapping("/grindingReportListPage")
    public Result<ResponsePage<EapGrindingHoursReportDto>> grindingReportListPage(String search_LIKE_equip, String search_LIKE_sn, String search_GTE_startGrinding, String search_LT_startGrinding, String search_GTE_endGrinding, String search_LT_endGrinding, String equipType, @ApiIgnore RequestPage requestPage) {
        requestPage.setOrderField(null);
        if (StringUtils.isBlank(search_LIKE_equip)) search_LIKE_equip = "";
        if (StringUtils.isBlank(search_LIKE_sn)) search_LIKE_sn = "";
        if (StringUtils.isBlank(equipType)) equipType = null;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = formatter.format(currentTime);
        if (StringUtils.isBlank(search_GTE_startGrinding)) search_GTE_startGrinding = "2021-01-11 13:19:51";
        if (StringUtils.isBlank(search_LT_startGrinding)) search_LT_startGrinding = str;
        if (StringUtils.isBlank(search_GTE_endGrinding)) search_GTE_endGrinding = "2021-01-11 13:19:51";
        if (StringUtils.isBlank(search_LT_endGrinding)) search_LT_endGrinding = str;
        ResponsePage<EapGrindingHoursReportDto> responsePage = eapCutCraftService.grindingReportListPage(search_LIKE_equip, search_LIKE_sn, search_GTE_startGrinding, search_LT_startGrinding, search_GTE_endGrinding, search_LT_endGrinding, PageUtil.createPageable(requestPage));
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "磨削加工记录")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"), @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("/GrindingBlankingListByPage")
    public Result<ResponsePage<EapGrindingHoursReportDto>> GrindingBlankingListByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<GrindingBlanking> specification = DynamicSpecifications.bySearchFilter(request, GrindingBlanking.class);
        Page<GrindingBlanking> page = grindingBlankingService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<EapGrindingHoursReportDto> dtos = page.getContent().stream().map(entity -> toEapGrindingHoursReportDtoDto(entity)).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "旧数据更新")
    @GetMapping("/updateOld")
    public Result updateOld(@RequestParam(value = "staId") Long staId, @RequestParam(value = "endId") Long endId) {
        eapCutCraftService.updateOld(staId, endId);
        return ResultGenerator.success();
    }


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

    public EapGrindingHours fromDto(EapGrindingHoursDto dto) {
        return modelMapper.map(dto, EapGrindingHours.class);
    }


    public EapOpenHours fromDto(EapOpenHoursDto dto) {
        return modelMapper.map(dto, EapOpenHours.class);
    }

    public EapStateUpload fromDto(EapStateUploadDto dto) {
        return modelMapper.map(dto, EapStateUpload.class);
    }

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

    public EapIngredientsTimes fromDto(EapIngredientsTimesDto dto) {
        return modelMapper.map(dto, EapIngredientsTimes.class);
    }

    public EapSpecificationSend fromDto(EapSpecificationSendDto dto) {
        return modelMapper.map(dto, EapSpecificationSend.class);
    }

    public EapRetreatFeedback fromDto(EapRetreatFeedbackDto dto) {
        return modelMapper.map(dto, EapRetreatFeedback.class);
    }

    public EapEvolutionRack fromDto(CutCrystalDto dto) {
        Map<String, Object> startCollectionData = dto.getStartCollectionData();
        String deviceCode = dto.getDeviceCode();
        EapEvolutionRack eapGrindingRack = new EapEvolutionRack();
        eapGrindingRack.setEquipNo(deviceCode);
        Object o = startCollectionData.get("5");
        if(null != o){
            eapGrindingRack.setSn((String) startCollectionData.get("6"));
            return eapGrindingRack;
        }
        Object o1 = startCollectionData.get("7");
        if(null != o1){
            eapGrindingRack.setSn((String) startCollectionData.get("8"));
            return eapGrindingRack;
        }
        Object o2 = startCollectionData.get("9");
        if(null != o2){
            eapGrindingRack.setSn((String) startCollectionData.get("10"));
            return eapGrindingRack;
        }
        Object o3 = startCollectionData.get("11");
        if(null != o3){
            eapGrindingRack.setSn((String) startCollectionData.get("12"));
            return eapGrindingRack;
        }
        return null;
    }

    public EapEvolutionBlanking fromDtoBaiting(CutCrystalDto dto) {
        Map<String, Object> startCollectionData = dto.getStartCollectionData();
        String deviceCode = dto.getDeviceCode();
        EapEvolutionBlanking eapEvolutionBlanking = new EapEvolutionBlanking();
        eapEvolutionBlanking.setEquipNo(deviceCode);
        Object o = startCollectionData.get("5");
        if(null != o){
            eapEvolutionBlanking.setSn((String) startCollectionData.get("6"));
            return eapEvolutionBlanking;
        }
        Object o1 = startCollectionData.get("7");
        if(null != o1){
            eapEvolutionBlanking.setSn((String) startCollectionData.get("8"));
            return eapEvolutionBlanking;
        }
        Object o2 = startCollectionData.get("9");
        if(null != o2){
            eapEvolutionBlanking.setSn((String) startCollectionData.get("10"));
            return eapEvolutionBlanking;
        }
        Object o3 = startCollectionData.get("11");
        if(null != o3){
            eapEvolutionBlanking.setSn((String) startCollectionData.get("12"));
            return eapEvolutionBlanking;
        }
        return null;
    }

    public EapEvolutionRecord fromDtoProcess(CutCrystalDto dto) {
        Map<String, Object> startCollectionData = dto.getStartCollectionData();
        String deviceCode = dto.getDeviceCode();
        EapEvolutionRecord eapEvolutionRecord = new EapEvolutionRecord();
        eapEvolutionRecord.setEquipNo(deviceCode);
        Object o = startCollectionData.get("5");
        if(null != o){
            eapEvolutionRecord.setSn((String) startCollectionData.get("6"));
            return eapEvolutionRecord;
        }
        Object o1 = startCollectionData.get("7");
        if(null != o1){
            eapEvolutionRecord.setSn((String) startCollectionData.get("8"));
            return eapEvolutionRecord;
        }
        Object o2 = startCollectionData.get("9");
        if(null != o2){
            eapEvolutionRecord.setSn((String) startCollectionData.get("10"));
            return eapEvolutionRecord;
        }
        Object o3 = startCollectionData.get("11");
        if(null != o3){
            eapEvolutionRecord.setSn((String) startCollectionData.get("12"));
            return eapEvolutionRecord;
        }
        return null;
    }


    private EapGrindingRack fromDtoGrindingFeed(CutCrystalDto cutCrystalDto) {
        Map<String, Object> startCollectionData = cutCrystalDto.getStartCollectionData();
        String deviceCode = cutCrystalDto.getDeviceCode();
        EapGrindingRack eapGrindingRack = new EapGrindingRack();
        eapGrindingRack.setEquipNo(deviceCode);
        eapGrindingRack.setCreatedTime(new Date());
        eapGrindingRack.setSn((String) startCollectionData.get("3"));
        return eapGrindingRack;
    }


    private GrindingBlanking fromGringBlankingDto(CutCrystalDto dto) {
        Map<String, Object> startCollectionData = dto.getStartCollectionData();
        String deviceCode = dto.getDeviceCode();
        GrindingBlanking eapGrindingRack = new GrindingBlanking();
        eapGrindingRack.setEquipNo(deviceCode);
        eapGrindingRack.setSn((String) startCollectionData.get("5"));
//        eapGrindingRack.setGrindingOrder((String) startCollectionData.get("25"));
        eapGrindingRack.setAftertaild34(NumberUtil.Object2BigDecimal(startCollectionData.get("7"),null));
        eapGrindingRack.setTurnonflag(NumberUtil.object2String(startCollectionData.get("10"),null));

        eapGrindingRack.setSide1(NumberUtil.Object2BigDecimal(startCollectionData.get("13"),null));
        eapGrindingRack.setSide2(NumberUtil.Object2BigDecimal(startCollectionData.get("14"),null));
        eapGrindingRack.setSide3(NumberUtil.Object2BigDecimal(startCollectionData.get("15"),null));
        eapGrindingRack.setSide4(NumberUtil.Object2BigDecimal(startCollectionData.get("16"),null));
        eapGrindingRack.setSide5(NumberUtil.Object2BigDecimal(startCollectionData.get("17"),null));
        eapGrindingRack.setSide6(NumberUtil.Object2BigDecimal(startCollectionData.get("18"),null));
        eapGrindingRack.setSide7(NumberUtil.Object2BigDecimal(startCollectionData.get("19"),null));
        eapGrindingRack.setSide8(NumberUtil.Object2BigDecimal(startCollectionData.get("20"),null));
        eapGrindingRack.setSide9(NumberUtil.Object2BigDecimal(startCollectionData.get("21"),null));



        eapGrindingRack.setSide10(NumberUtil.Object2BigDecimal(startCollectionData.get("22"),null));
        eapGrindingRack.setSide11(NumberUtil.Object2BigDecimal(startCollectionData.get("23"),null));
        eapGrindingRack.setSide12(NumberUtil.Object2BigDecimal(startCollectionData.get("24"),null));
        eapGrindingRack.setSide13(NumberUtil.Object2BigDecimal(startCollectionData.get("25"),null));
        eapGrindingRack.setAfterhead1(NumberUtil.Object2BigDecimal(startCollectionData.get("26"),null));
        eapGrindingRack.setAfterhead2(NumberUtil.Object2BigDecimal(startCollectionData.get("27"),null));
        eapGrindingRack.setAfterhead3(NumberUtil.Object2BigDecimal(startCollectionData.get("28"),null));
        eapGrindingRack.setAfterhead4(NumberUtil.Object2BigDecimal(startCollectionData.get("29"),null));
        eapGrindingRack.setAftertail1(NumberUtil.Object2BigDecimal(startCollectionData.get("30"),null));

        eapGrindingRack.setAftertail2(NumberUtil.Object2BigDecimal(startCollectionData.get("31"),null));
        eapGrindingRack.setAftertail3(NumberUtil.Object2BigDecimal(startCollectionData.get("32"),null));
        eapGrindingRack.setAftertail4(NumberUtil.Object2BigDecimal(startCollectionData.get("33"),null));

        eapGrindingRack.setHeadadd13(NumberUtil.Object2BigDecimal(startCollectionData.get("34"),null));
        eapGrindingRack.setHeadadd24(NumberUtil.Object2BigDecimal(startCollectionData.get("35"),null));
        eapGrindingRack.setTailadd13(NumberUtil.Object2BigDecimal(startCollectionData.get("36"),null));

        eapGrindingRack.setTailadd24(NumberUtil.Object2BigDecimal(startCollectionData.get("37"),null));
        eapGrindingRack.setBeforeheadd12(NumberUtil.Object2BigDecimal(startCollectionData.get("38"),null));
        eapGrindingRack.setBeforeheadd34(NumberUtil.Object2BigDecimal(startCollectionData.get("39"),null));
        eapGrindingRack.setBeforetaild12(NumberUtil.Object2BigDecimal(startCollectionData.get("40"),null));

        eapGrindingRack.setBeforetaild34(NumberUtil.Object2BigDecimal(startCollectionData.get("41"),null));
        eapGrindingRack.setAfterheadd12(NumberUtil.Object2BigDecimal(startCollectionData.get("42"),null));
        eapGrindingRack.setAfterheadd34(NumberUtil.Object2BigDecimal(startCollectionData.get("43"),null));
        eapGrindingRack.setAftertaild12(NumberUtil.Object2BigDecimal(startCollectionData.get("44"),null));

        return eapGrindingRack;

    }


    private CutProcessRecord fromCutProcessRecordDto(CutCrystalDto dto) {
        Map<String, Object> startCollectionData = dto.getStartCollectionData();
        String deviceCode = dto.getDeviceCode();
        CutProcessRecord cutProcessRecord = new CutProcessRecord();
        cutProcessRecord.setDeviceCode(deviceCode);
        cutProcessRecord.setCrystalNo((String) startCollectionData.get("3"));
        cutProcessRecord.setCuttingStart(NumberUtil.Object2Integer(startCollectionData.get("4"),null));
        cutProcessRecord.setCuttingEnd(NumberUtil.Object2Integer(startCollectionData.get("5"),null));
        cutProcessRecord.setCuttingHour(NumberUtil.Object2Double(startCollectionData.get("6"),null));
        cutProcessRecord.setData7(NumberUtil.Object2Double(startCollectionData.get("7"),null));
        cutProcessRecord.setData8(NumberUtil.Object2Double(startCollectionData.get("8"),null));
        cutProcessRecord.setData9(NumberUtil.Object2Double(startCollectionData.get("9"),null));
        cutProcessRecord.setData10(NumberUtil.Object2Double(startCollectionData.get("10"),null));
        cutProcessRecord.setData11(NumberUtil.Object2Double(startCollectionData.get("11"),null));
        cutProcessRecord.setData12(NumberUtil.Object2Double(startCollectionData.get("12"),null));
        cutProcessRecord.setData13(NumberUtil.Object2Double(startCollectionData.get("13"),null));
        cutProcessRecord.setData14(NumberUtil.Object2Double(startCollectionData.get("14"),null));
        cutProcessRecord.setData15(NumberUtil.Object2Double(startCollectionData.get("15"),null));
        cutProcessRecord.setData16(NumberUtil.Object2Double(startCollectionData.get("16"),null));
        cutProcessRecord.setData17(NumberUtil.Object2Double(startCollectionData.get("17"),null));
        cutProcessRecord.setData18(NumberUtil.Object2Double(startCollectionData.get("18"),null));
        cutProcessRecord.setData19(NumberUtil.Object2Double(startCollectionData.get("19"),null));
        cutProcessRecord.setData20(NumberUtil.Object2Double(startCollectionData.get("20"),null));
        cutProcessRecord.setData21(NumberUtil.Object2Double(startCollectionData.get("21"),null));
        cutProcessRecord.setData22(NumberUtil.Object2Double(startCollectionData.get("22"),null));
        cutProcessRecord.setData23(NumberUtil.Object2Double(startCollectionData.get("23"),null));
        cutProcessRecord.setData24(NumberUtil.Object2Double(startCollectionData.get("24"),null));
        cutProcessRecord.setData25(NumberUtil.Object2Double(startCollectionData.get("25"),null));
        cutProcessRecord.setData26(NumberUtil.Object2Double(startCollectionData.get("26"),null));
        cutProcessRecord.setData27(NumberUtil.Object2Double(startCollectionData.get("27"),null));
        cutProcessRecord.setData28(NumberUtil.Object2Double(startCollectionData.get("28"),null));
        cutProcessRecord.setData29(NumberUtil.Object2Double(startCollectionData.get("29"),null));
        cutProcessRecord.setData30(NumberUtil.Object2Double(startCollectionData.get("30"),null));
        return cutProcessRecord;

    }

    public EapEvolutionRecord fromDto(EapEvolutionRecordDto dto) {
        return modelMapper.map(dto, EapEvolutionRecord.class);
    }

    public EapGrindingRack fromDto(EapGrindingRackDto dto) {
        return modelMapper.map(dto, EapGrindingRack.class);
    }

    public EapGrindingMachine fromDto(EapGrindingMachineDto dto) {
        return modelMapper.map(dto, EapGrindingMachine.class);
    }

    public EapGoldBreak fromDto(EapGoldBreakDto dto) {
        return modelMapper.map(dto, EapGoldBreak.class);
    }

    public EapEvolutionBlanking fromDto(EapEvolutionBlankingDto dto) {
        return modelMapper.map(dto, EapEvolutionBlanking.class);
    }

    public EapGrindingReport fromDto(EapGrindingReportDto dto) {
        return modelMapper.map(dto, EapGrindingReport.class);
    }

    public EapGrindingTask fromDto(EapGrindingTaskDto dto) {
        return modelMapper.map(dto, EapGrindingTask.class);
    }

    public MachineCapacityKfDto toEagerDto(MachineCapacityKf entity) {
        return getMachineCapacityKfDto(entity);
    }

    private MachineCapacityKfDto getMachineCapacityKfDto(MachineCapacityKf entity) {
        MachineCapacityKfDto machineCapacityKfDto = modelMapper.map(entity, MachineCapacityKfDto.class);
        return machineCapacityKfDto;
    }

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

    public EapGrindingHoursReportDto toEapGrindingHoursReportDtoDto(GrindingBlanking entity) {
        EapGrindingHoursReportDto dto = modelMapper.map(entity, EapGrindingHoursReportDto.class);
        return dto;
    }

    public GrindingBlanking fromDto(GrindingBlankingDto dto) {
        return modelMapper.map(dto, GrindingBlanking.class);
    }

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

    public EapCutCraftShort fromDto(EapCutCraftShortDto dto) {
        return modelMapper.map(dto, EapCutCraftShort.class);
    }

    public EapCutRecord fromDto(EapCutRecordDto dto) {
        return modelMapper.map(dto, EapCutRecord.class);
    }
}
