package com.sw.mes.yb.check.controller;


import com.sw.mes.base.factory.inspect.service.DefaultSampleService;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.PieceCheckDto1;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.EasyExcelUtils;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.yb.check.entity.PieceCheck;
import com.sw.mes.yb.check.entity.ZhxxOperatePieceCheck;
import com.sw.mes.yb.check.entity.dto.PieceCheckTemplateDto;
import com.sw.mes.yb.check.entity.dto.StoreInputItemDto;
import com.sw.mes.yb.check.entity.vo.PieceCheckAnneal;
import com.sw.mes.yb.check.entity.vo.PieceCheckLife;
import com.sw.mes.yb.check.entity.vo.PieceCheckLine;
import com.sw.mes.yb.check.service.PieceCheckService;
import com.sw.mes.yb.check.service.UpdateService;
import com.sw.mes.yb.check.service.ZhxxOperatePieceCheckService;
import com.sw.mes.yb.pad.dao.PieceDetailDao;
import com.sw.mes.yb.pad.entity.PieceDetail;
import com.sw.mes.yb.pad.entity.ProductionPaintingLine;
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.production.dao.LongCrystalDao;
import com.sw.mes.yb.production.entity.LongCrystal;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/pieceCheck")
@Slf4j
@Api(description = "样片检验接口")
public class PieceCheckController {

    @Autowired
    private PieceCheckService pieceCheckService;

    @Autowired
    LongCrystalDao longCrystalDao;


    @Autowired
    private PieceDetailDao pieceDetailDao;

    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    FbFeignClients fbFeignClients;

    @Autowired
    ZhxxOperatePieceCheckService zhxxOperatePieceCheckService;

    @Autowired
    private DefaultSampleService defaultSampleService;

    @Autowired
    private UpdateService updateService;

    @Autowired
    private WipStorageService wipStorageService;


    @Autowired
    private ProductionPaintingLineService productionPaintingLineService;

    @ApiOperation(value = "创建样片检验")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public @ResponseBody
    Result create(@RequestBody @Valid PieceCheck pieceCheck) {
        List<PieceDetail> pieceMaterialDetails = this.pieceDetailDao.findByPieceNo(pieceCheck.getPieceNo());
        if (pieceMaterialDetails == null || pieceMaterialDetails.size() <= 0) {
            return ResultGenerator.fail("样片编号不存在");
        }
        pieceCheck.setBackCut(pieceMaterialDetails.get(0).getBackCut());
        //添加判断
        ProductionPaintingLineDetail productionPaintingLineDetail = productionPaintingLineDetailService.findBySegmentNo(pieceCheck.getPieceNo());
        if (null != productionPaintingLineDetail) {
            ProductionPaintingLine productionPaintingLine = productionPaintingLineService.get(productionPaintingLineDetail.getOperateDrawId());
            if (null != productionPaintingLine) {
                List<WipStorage> byProcessingByOrderCode = wipStorageService.findByProcessingByOrderCode(productionPaintingLine.getCrystalNo());
                if (!CollectionUtils.isEmpty(byProcessingByOrderCode)) {
                    WipStorage wipStorage = byProcessingByOrderCode.get(0);
                    if (null != wipStorage && StringUtils.equals(EnumValuesFactory.WipStorageCode.毛棒截断.getValue(), wipStorage.getProcessName())) {
                        return ResultGenerator.fail("请先毛棒截断操作！");
                    }
                }
            }
        }

        pieceCheckService.saveOrUpdate(pieceCheck);
        List<PieceCheck> pieceChecks = new ArrayList<>();
        // 同步更新晶段检验样片信息
        this.pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片新增");
        return ResultGenerator.success();
    }

    @ApiOperation(value = "查询位错微缺陷未录入样片列表")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/listLineDefect", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<List<PieceCheck>> listLineDefect(ServletRequest request, RequestPage page) {
//        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(request, PieceCheck.class,
//                new SearchFilter("microDefect", SearchFilter.Operator.ISNULL, 0));
        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(request, PieceCheck.class);
        List<PieceCheck> pieceChecks = pieceCheckService.findAll(specification);

        return ResultGenerator.success(pieceChecks);
    }

    @ApiOperation(value = "查询碳氧寿命未录入样片列表")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/listLiftTime", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<List<PieceCheck>> listLiftTime(ServletRequest request, RequestPage page) {
//        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(request, PieceCheck.class,
//                new SearchFilter("lifeTime", SearchFilter.Operator.ISNULL, 0));
        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(request, PieceCheck.class);
        List<PieceCheck> pieceChecks = pieceCheckService.findAll(specification);

        return ResultGenerator.success(pieceChecks);
    }


    @ApiOperation(value = "样片检验-位错微缺陷录入")
    @RequestMapping(value = "/createLineDefect", method = RequestMethod.POST)
    public @ResponseBody
    Result createLineDefect(@RequestBody @Valid List<PieceCheckLine> pieceCheckLines) {

        List<PieceCheck> pieceChecks = new ArrayList<>();
//        PieceDetail pieceDetail = null;

        if (pieceCheckLines != null && pieceCheckLines.size() > 0) {
            PieceCheck pieceCheck;
            for (PieceCheckLine line : pieceCheckLines) {
                List<PieceDetail> pieceMaterialDetails = this.pieceDetailDao.findByPieceNo(line.getPieceNo());
                if (pieceMaterialDetails == null || pieceMaterialDetails.size() <= 0) {
                    return ResultGenerator.fail("样片编号不存在");
                }
//                pieceDetail = pieceMaterialDetails.get(0);

                pieceCheck = pieceCheckService.getByPieceNo(line.getPieceNo());
                if (pieceCheck == null) {
                    pieceCheck = new PieceCheck();
                    pieceCheck.setPieceNo(line.getPieceNo());

                    LongCrystal sectionDetail = this.longCrystalDao.findByPieceNo(line.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 (line.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(line.getMicroDefect());// 微缺陷
//
//                }
//
//                // 位错
//                if (line.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(line.getLineDefect());// 位错
//                }
                pieceCheck.setBackCut(pieceMaterialDetails.get(0).getBackCut());
                pieceCheck.setRemark1(line.getRemark1());
                pieceCheck.setUserName1(line.getUserName1());
                pieceCheck.setCheckTime1(new Date());
                pieceCheck.setWorkshop(line.getWorkshop());

                pieceChecks.add(pieceCheck);
            }
        }

        List<String> pieceNos = new ArrayList<>();
//        pieceCheckService.savePieceCheck(pieceChecks);
        if (pieceChecks.size() > 0) {
            pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片检验-新增");

            for (PieceCheck pieceCheck : pieceChecks) {
                // 同步更新晶段检验样片信息
                pieceCheckService.saveInspectDataBaseInfo(pieceCheck.getPieceNo());
                String fromMark = pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
                if (fromMark.matches("[A-Z]+")) {
                    pieceNos.add(pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
                } else {
                    pieceNos.add(pieceCheck.getPieceNo().substring(0, 12));
                }
//                try {
//                    fbFeignClients.synchronousUpdate(pieceCheck.getPieceNo().substring(0, 11));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }

        }
        updateService.updates(pieceNos);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "样片检验-碳氧寿命录入")
    @RequestMapping(value = "/createLifeTime", method = RequestMethod.POST)
    public @ResponseBody
    Result createLifeTime(@RequestBody @Valid List<PieceCheckLife> pieceCheckLives) {
        List<PieceCheck> pieceChecks = new ArrayList<>();
        if (pieceCheckLives != null && pieceCheckLives.size() > 0) {
            PieceCheck pieceCheck;
            for (PieceCheckLife life : pieceCheckLives) {
                if (StringUtils.isNotBlank(life.getPieceNo())) {
                    life.setPieceNo(life.getPieceNo().trim().toUpperCase());
                }
                List<PieceDetail> pieceMaterialDetails = this.pieceDetailDao.findByPieceNo(life.getPieceNo());
                if (pieceMaterialDetails == null || pieceMaterialDetails.size() <= 0) {
                    return ResultGenerator.fail("样片编号不存在");
                }
                PieceDetail pieceDetail = pieceMaterialDetails.get(0);
                pieceCheck = pieceCheckService.getByPieceNo(life.getPieceNo());
                if (pieceCheck == null) {
                    pieceCheck = new PieceCheck();
                    pieceCheck.setPieceNo(life.getPieceNo());

                    LongCrystal sectionDetail = this.longCrystalDao.findByPieceNo(life.getPieceNo());
                    if (sectionDetail != null) {
                        pieceCheck.setDeviceNo(sectionDetail.getEquipmentCode());
                        pieceCheck.setLotNo(sectionDetail.getLotNo());
                        pieceCheck.setMotherCrystalNo(sectionDetail.getCrystalNo());
                    }
                }

                if (pieceCheck.getcContents() != null || pieceCheck.getoContents() != null) {
                    return ResultGenerator.fail("此样片碳氧含量已经录入，不可重复录入！");
                }
                pieceCheck.setBackCut(pieceDetail.getBackCut());
                pieceCheck.setcContents(life.getcContents());
                //pieceCheck.setcBorderContents(life.getCBorderContents());  //20220726去除字段
                pieceCheck.setoContents(life.getoContents());
                //pieceCheck.setoBorderContents(life.getOBorderContents());  //20220726去除字段
                //pieceCheck.setLifeTime(life.getLifeTime());
                pieceCheck.setUserName2(life.getUserName2());
                pieceCheck.setRemark2(life.getRemark2());
                pieceCheck.setThickness(life.getThickness());
                pieceCheck.setCheckTime2(new Date());
                pieceCheck.setWorkshop(life.getWorkshop());
                pieceChecks.add(pieceCheck);
            }
        }
        // 同步圆棒检验数据库，以及方棒检验数据库
        pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片检验-新增");
        return ResultGenerator.success();
    }


    @ApiOperation(value = "新增样片”按钮：根据样片编号获取样片信息")
    @GetMapping("/{peaceNo}")
    public Result<ProductionPaintingLineDetail> get(@PathVariable @ApiParam(value = "样片编号") String peaceNo) {
        ProductionPaintingLineDetail paintingLineDetail = productionPaintingLineDetailService.findBySegmentNo(peaceNo);
        if (null == paintingLineDetail) {
            return ResultGenerator.fail("该样片划线记录不存在");
        }
        return ResultGenerator.success(paintingLineDetail);
    }


    @ApiOperation(value = "样片检验-退火电阻率")
    @PostMapping(value = "/createAnneal")
    public @ResponseBody
    Result createAnneal(@RequestBody @Valid List<PieceCheckAnneal> data) {

        List<PieceCheck> pieceChecks = new ArrayList<>();

        if (data != null && data.size() > 0) {
            PieceCheck pieceCheck;
            for (PieceCheckAnneal item : data) {
                List<PieceDetail> pieceMaterialDetails = this.pieceDetailDao.findByPieceNo(item.getPieceNo());
                if (pieceMaterialDetails == null || pieceMaterialDetails.size() <= 0) {
                    return ResultGenerator.fail("样片编号不存在");
                }

                pieceCheck = pieceCheckService.getByPieceNo(item.getPieceNo());
                if (pieceCheck == null) {
                    pieceCheck = new PieceCheck();
                    pieceCheck.setPieceNo(item.getPieceNo());

                    LongCrystal sectionDetail = this.longCrystalDao.findByPieceNo(item.getPieceNo());
                    if (sectionDetail != null) {
                        pieceCheck.setDeviceNo(sectionDetail.getEquipmentCode());
                        pieceCheck.setLotNo(sectionDetail.getLotNo());
                        pieceCheck.setMotherCrystalNo(sectionDetail.getCrystalNo());
                    }
                }
                pieceCheck.setBackCut(pieceMaterialDetails.get(0).getBackCut());
                pieceCheck.setCenterAnneal(item.getCenterAnneal());
                pieceCheck.setBorderAnneal(item.getBorderAnneal());
                pieceCheck.setAnnealRemark(item.getAnnealRemark());
                pieceCheck.setAnnealUser(item.getAnnealUser());
                pieceCheck.setAnnealTime(new Date());
                pieceCheck.setWorkshop(item.getWorkshop());
                pieceChecks.add(pieceCheck);
            }
        }

//        pieceCheckService.savePieceCheck(pieceChecks);
        List<String> pieceNos = new ArrayList<>();
        if (pieceChecks.size() > 0) {
            pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片检验-新增");

            for (PieceCheck pieceCheck : pieceChecks) {
                // 同步更新晶段检验样片信息
                pieceCheckService.saveInspectDataBaseInfo(pieceCheck.getPieceNo());
                String fromMark = pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
                if (fromMark.matches("[A-Z]+")) {
                    pieceNos.add(pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
                } else {
                    pieceNos.add(pieceCheck.getPieceNo().substring(0, 12));
                }
//                try {
//                    fbFeignClients.synchronousUpdate(pieceCheck.getPieceNo().substring(0, 11));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        }
        updateService.updates(pieceNos);
        return ResultGenerator.success();
    }


    @ApiOperation(value = "样片检验详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "样片检验ID", paramType = "path", dataType = "Integer"),
    })
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public Result preUpdate(@PathVariable Long id) {
        PieceCheck pieceCheck = pieceCheckService.get(id);
        return ResultGenerator.success(pieceCheck);
    }

//
//    @ApiOperation(value = "synchronousUpdate")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "synchronousUpdate", value = "sn", paramType = "path", dataType = "Integer"),
//    })
//    @RequestMapping(value = "/synchronousUpdate", method = RequestMethod.GET)
//    public Result synchronousUpdate() {
//        updateService.update("12312312");
//        return ResultGenerator.success();
//    }


    @ApiOperation(value = "更新样片检验")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public @ResponseBody
    Result update(@Valid @RequestBody PieceCheck pieceCheck) {

        pieceCheck.setUpdateUser(BaseContextHandler.getUsername());
        pieceCheck.setUpdateTime(new Date());
        pieceCheckService.saveOrUpdate(pieceCheck);
        // 同步更新晶段检验样片信息
        List<PieceCheck> pieceChecks = new ArrayList<>();
        pieceChecks.add(pieceCheck);
        this.pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片数据更新");
        String fromMark = pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
        if (fromMark.matches("[A-Z]+")) {
            updateService.update(pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
        } else {
            updateService.update(pieceCheck.getPieceNo().substring(0, 12));
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "获取样片检验")
    @RequestMapping(value = "/getSampleData/withFb", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<List<PieceCheckDto1>> getSampleData(String motherCrystalNo) {
        List<PieceCheck> countByMotherCrystalNo = pieceCheckService.findByMotherCrystalNo(motherCrystalNo);
        if (null != countByMotherCrystalNo && countByMotherCrystalNo.size() > 0) {
            List<PieceCheckDto1> dtos = countByMotherCrystalNo.stream().map(this::toLazyDto)
                    .collect(Collectors.toList());
            return ResultGenerator.success(dtos);
        }
        return ResultGenerator.success();
    }


    public PieceCheckDto1 toLazyDto(PieceCheck entity) {
        PieceCheckDto1 map = modelMapper.map(entity, PieceCheckDto1.class);
        return map;
    }

    @ApiOperation(value = "删除样片检验,单个删除")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public @ResponseBody
    Result delete(@PathVariable Long id) {
        PieceCheck pieceCheck = pieceCheckService.get(id);
        pieceCheckService.delete(id);


        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除样片检验，多选删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "样片检验ID", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public @ResponseBody
    Result deleteMany(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            PieceCheck pieceCheck = pieceCheckService.get(ids[i]);
            pieceCheckService.delete(pieceCheck.getId());

        }

        return ResultGenerator.success();
    }

    @ApiOperation(value = "分页查询样片检验列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_pieceNo", value = "样片编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_deviceNo", value = "设备号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_lotNo", value = "单晶编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_motherCrystalNo", value = "单晶编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_checkTime", value = "查询时间1", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_checkTime", value = "查询时间1", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<ResponsePage<PieceCheck>> list(ServletRequest request, RequestPage page) {
        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(request, PieceCheck.class);
        List<PieceCheck> pieceChecks = pieceCheckService.findByExample(specification, page);

        ResponsePage responsePage = new ResponsePage(pieceChecks, page.getTotal());

        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "样片检验详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "样片检验ID", paramType = "path", dataType = "Integer"),
    })
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public Result view(@PathVariable Long id) {
        PieceCheck pieceCheck = pieceCheckService.get(id);
        return ResultGenerator.success(pieceCheck);
    }

    @ApiOperation(value = "导入样片数据")
    @PostMapping("/excelImport")
    public @ResponseBody
    Result excelImport(MultipartFile file) throws Exception {
        List<StoreInputItemDto> list = null;
        if (!file.isEmpty()) {
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (!(StringUtils.equals(fileSuffix,".xlsx") || StringUtils.equals(fileSuffix,".xls"))){
                return ResultGenerator.fail("样片数据导入文件格式异常!");
            }
        }
        try {
            pieceCheckService.readExcelFile(file);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success("样片数据导入成功!");
    }

    @ApiOperation(value = "样片模板导出")
    @GetMapping("/exportTemplate")
    public void export(ServletRequest request, HttpServletResponse resp) {
        try {
            EasyExcelUtils.write(resp, PieceCheckTemplateDto.class, "样片导入模板", "样片导入模板", new ArrayList<>());
        } catch (Exception e) {
            throw new RuntimeException("样片模板导出失败，错误信息：" + e.getMessage());
        }
    }


    /**
     * 测试定时任务功能，拉取样片检验详细信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "测试定时任务功能，拉取样片检验详细信息")
    @RequestMapping(value = "/testForAutoIncert", method = RequestMethod.POST)
    public @ResponseBody
    Result testForAutoIncert(@ApiParam(value = "入参", type = "query") @RequestParam Long id) {

        log.info("样片自动拉取");

        //先从样片数据中间表拉取没有拉取过的记录
        List<ZhxxOperatePieceCheck> zhxxOperatePieceChecks = zhxxOperatePieceCheckService.pullAllNewRecord();
        List<ZhxxOperatePieceCheck> zhxxOperatePieceChecksGroup = zhxxOperatePieceCheckService.pullAllNewRecordGroupByPieceNo();
        if (null != zhxxOperatePieceChecksGroup && !CollectionUtils.isEmpty(zhxxOperatePieceChecksGroup)) {
            createLifeTimeForTest2(zhxxOperatePieceChecksGroup);
        }
        if (null != zhxxOperatePieceChecks && !CollectionUtils.isEmpty(zhxxOperatePieceChecks)) {
            List<Long> ids = zhxxOperatePieceChecks.stream().map(t -> t.getId()).collect(Collectors.toList());
            //将中间表状态回写为已拉取
            zhxxOperatePieceCheckService.updateStateForPieceBatch(ids);
            log.info("更新中间表的ids:" + ids.toString());
        }
        return ResultGenerator.success();
    }


    private void createLifeTimeForTest2(List<ZhxxOperatePieceCheck> zhxxOperatePieceChecks) {

        try {
            //组装批量插入样片数据的集合
            List<PieceCheck> pieceChecks = new ArrayList<>();

            for (ZhxxOperatePieceCheck zhxxOperatePieceCheck : zhxxOperatePieceChecks) {
                PieceCheckLife pieceCheckLife = modelMapper.map(zhxxOperatePieceCheck, PieceCheckLife.class);
                pieceCheckLife.setRemark2(zhxxOperatePieceCheck.getRemark());
                pieceCheckLife.setUserName2(zhxxOperatePieceCheck.getUserName());

                List<PieceDetail> pieceMaterialDetails = this.pieceDetailDao.findByPieceNo(pieceCheckLife.getPieceNo());
                if (pieceMaterialDetails == null || pieceMaterialDetails.size() <= 0) {
//                    throw new RuntimeException("样片编号不存在:"+pieceCheckLife.getPieceNo());
                    continue;
                }

                PieceCheck pieceCheck = pieceCheckService.getByPieceNo(pieceCheckLife.getPieceNo());
                if (pieceCheck == null) {
                    pieceCheck = new PieceCheck();
                    pieceCheck.setPieceNo(pieceCheckLife.getPieceNo());
                    LongCrystal sectionDetail = this.longCrystalDao.findByPieceNo(pieceCheckLife.getPieceNo());
                    if (sectionDetail != null) {
                        pieceCheck.setDeviceNo(sectionDetail.getEquipmentCode());
                        pieceCheck.setLotNo(sectionDetail.getLotNo());
                        pieceCheck.setMotherCrystalNo(sectionDetail.getCrystalNo());
                    }
                }
                if (pieceCheck.getcContents() != null || pieceCheck.getoContents() != null) {
//                    throw new RuntimeException("此样片碳氧含量已经录入，不可重复录入！:"+pieceCheckLife.getPieceNo());
                    continue;
                }
                pieceCheck.setcContents(pieceCheckLife.getcContents());
                pieceCheck.setoContents(pieceCheckLife.getoContents());
                pieceCheck.setUserName2(pieceCheckLife.getUserName2());
                pieceCheck.setRemark2(pieceCheckLife.getRemark2());
                pieceCheck.setThickness(pieceCheckLife.getThickness());
                pieceCheck.setCheckTime2(new Date());
                pieceCheck.setWorkshop(pieceCheckLife.getWorkshop());
                pieceChecks.add(pieceCheck);
//                ids.add(zhxxOperatePieceCheck.getId());
            }

            List<String> pieceNos = new ArrayList<>();
            if (pieceChecks.size() > 0) {
                pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片检验-新增");
                for (PieceCheck pieceCheck : pieceChecks) {
                    // 同步更新晶段检验样片信息
                    pieceCheckService.saveInspectDataBaseInfo(pieceCheck.getPieceNo());
                    String fromMark = pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.追溯标识.getBeginIndex(), SectionIndexRangeEnum.追溯标识.getEndIndex());
                    if (fromMark.matches("[A-Z]+")) {
                        pieceNos.add(pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
                    } else {
                        pieceNos.add(pieceCheck.getPieceNo().substring(0, 11));
                    }
                }
            }
            updateService.updates(pieceNos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
