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

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.factory.init.entity.CrystalMaterialRelation;
import com.sw.mes.base.factory.init.service.CrystalMaterialRelationService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.SwitchConfig;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.constant.Constants;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.BackcutInspectionDto;
import com.sw.mes.core.dto.GetFbInfoDto;
import com.sw.mes.core.dto.OxygenCarbonDto;
import com.sw.mes.core.dto.sap.ReportSapChargItemDto;
import com.sw.mes.core.dto.sap.ReportSapGoodsmvtDto;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.enums.EnumValuesFactory;
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.enumvalue.EnumValuesFbServer;
import com.sw.mes.fb.aio.entity.GrindingBlanking;
import com.sw.mes.fb.aio.service.EapGrindingMachineService;
import com.sw.mes.fb.aio.service.GrindingBlankingService;
import com.sw.mes.fb.checkout.dto.FbCheckOutRecordDto;
import com.sw.mes.fb.checkout.dto.FieldExtensionShowDto;
import com.sw.mes.fb.checkout.dto.FieldShowDto;
import com.sw.mes.fb.checkout.dto.SquareRodNumberDto;
import com.sw.mes.fb.checkout.entity.*;
import com.sw.mes.fb.checkout.service.*;
import com.sw.mes.fb.turnstore.dao.RecheckInspectReceiveDetailDao;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTrayItem;
import com.sw.mes.fb.turnstore.entity.RecheckInspectReceiveDetail;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayItemService;
import com.sw.mes.fb.turnstore.service.RecheckInspectReceiveDetailService;
import com.sw.mes.fls.service.ProductionBindingTrayService;
import com.sw.mes.mcs.dto.GainTrayNoResultDto;
import com.sw.mes.mcs.enent.EventPublishService;
import com.sw.mes.mcs.service.MesToMcsService;
import com.sw.mes.plan.entity.FbProductionOrder;
import com.sw.mes.plan.service.FbProductionOrderService;
import com.sw.mes.utils.ExcelUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

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

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


/**
 * @Author
 * @Description：FbCheckOutRecord
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/FbCheckOutRecord")
@Slf4j
@Api(description = "方棒检验接口")
public class FbCheckOutRecordController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FbCheckOutRecordService fbCheckOutRecordService;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    RecheckInspectReceiveDetailDao recheckInspectReceiveDetailDao;

    @Autowired
    FbProductionOrderService fbProductionOrderService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private MesToMcsService mesToMcsService;

    @Autowired
    private ProductionBindingTrayService productionBindingTrayService;
    @Autowired
    private DictionaryItemService dictionaryItemService;
    @Autowired
    private SquareRodNumberService squareRodNumberService;

    @Autowired
    private EapGrindingMachineService eapGrindingMachineService;

    @Autowired
    private GrindingBlankingService grindingBlankingService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private CooperateDataService cooperateDataService;

    @Autowired
    YbFeignClients ybFeignService;

    @Autowired
    private FieldExtensionRecordService fieldExtensionRecordService;


    @Autowired
    private FieldExtensionTableService fieldExtensionTableService;

    @Autowired
    private CrystalMaterialRelationService crystalMaterialRelationService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private RecheckInspectReceiveDetailService receiveDetailService;

    @Autowired
    private FbTurnstoreTrayItemService fbTurnstoreTrayItemService;

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

    @ApiOperation(value = "分页查询方棒检验列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<FbCheckOutRecordDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
//        //高新建修改===========================
//        Specification<FbCheckOutData> specification = DynamicSpecifications.bySearchFilter(request, FbCheckOutData.class);
//        Page<FbCheckOutData> page = fbCheckOutDataService.findByExample(specification, PageUtil.createPageable(requestPage));
//        List<FbCheckOutRecordDto> dtos = page.getContent().stream()
//                .map(entity -> modelMapper.map(entity, FbCheckOutRecordDto.class))
//                .collect(Collectors.toList());
        //高新建修改===========================
        Specification<FbCheckOutRecord> specification = DynamicSpecifications.bySearchFilter(request, FbCheckOutRecord.class);
        Page<FbCheckOutRecord> page = fbCheckOutRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
        Map<String, FieldExtensionTable> fieldExtensionTableMap = fieldExtensionTableService.findMapByExtendTable("zhxx_operate_check_out");
        List<FbCheckOutRecordDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDtoNew(entity, fieldExtensionTableMap))
                .collect(Collectors.toList());
        dtos.stream().forEach(t -> {
            //磨削下料记录
            GrindingBlanking topByFbSectionNoOrderByIdDesc = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(t.getFbSectionNo());
            if (topByFbSectionNoOrderByIdDesc != null) {
                //赋边长和直径
                t.setEapDiameterMax(topByFbSectionNoOrderByIdDesc.getEapDiameterMax());
                t.setEapDiameterMin(topByFbSectionNoOrderByIdDesc.getEapDiameterMin());
//                List<BigDecimal> sides = Arrays.asList(topByFbSectionNoOrderByIdDesc.getEapSide1(), topByFbSectionNoOrderByIdDesc.getEapSide2(), topByFbSectionNoOrderByIdDesc.getEapSide3(), topByFbSectionNoOrderByIdDesc.getEapSide4(), topByFbSectionNoOrderByIdDesc.getEapSide5(), topByFbSectionNoOrderByIdDesc.getEapSide6());
                BigDecimal maxSide = topByFbSectionNoOrderByIdDesc.getBeforhud12();
                BigDecimal minSide = topByFbSectionNoOrderByIdDesc.getBeforhdd12();
                t.setEapSideMin(minSide);
                t.setEapSideMax(maxSide);
            }
        });

        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有方棒检验信息")
    @GetMapping("/listAll")
    public Result<List<FbCheckOutRecordDto>> listAll(ServletRequest request) {
        Specification<FbCheckOutRecord> specification = DynamicSpecifications.bySearchFilter(request, FbCheckOutRecord.class);
        List<FbCheckOutRecord> fbCheckOutRecords = fbCheckOutRecordService.findByExampleSort(specification, null);
        List<FbCheckOutRecordDto> fbCheckOutRecordDtos = fbCheckOutRecords.stream()
                .map(fbCheckOutRecord -> toLazyDto(fbCheckOutRecord))
                .collect(Collectors.toList());
        fbCheckOutRecordDtos.stream().forEach(t -> {
            //磨削下料记录
            GrindingBlanking topByFbSectionNoOrderByIdDesc = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(t.getFbSectionNo());
            if (topByFbSectionNoOrderByIdDesc != null) {
                //赋边长和直径
                t.setEapDiameterMax(topByFbSectionNoOrderByIdDesc.getEapDiameterMax());
                t.setEapDiameterMin(topByFbSectionNoOrderByIdDesc.getEapDiameterMin());
//                List<BigDecimal> sides = Arrays.asList(topByFbSectionNoOrderByIdDesc.getEapSide1(), topByFbSectionNoOrderByIdDesc.getEapSide2(), topByFbSectionNoOrderByIdDesc.getEapSide3(), topByFbSectionNoOrderByIdDesc.getEapSide4(), topByFbSectionNoOrderByIdDesc.getEapSide5(), topByFbSectionNoOrderByIdDesc.getEapSide6());
                BigDecimal maxSide = topByFbSectionNoOrderByIdDesc.getBeforhud12();
                BigDecimal minSide = topByFbSectionNoOrderByIdDesc.getBeforhdd12();
                t.setEapSideMin(minSide);
                t.setEapSideMax(maxSide);
            }
        });
        return ResultGenerator.success(fbCheckOutRecordDtos);
    }

    @ApiOperation(value = "方棒检验详细信息")
    @GetMapping("/{id}")
    public Result<FbCheckOutRecordDto> get(@PathVariable @ApiParam(value = "FbCheckOutRecordid") Integer id) {
        FbCheckOutRecord fbCheckOutRecord = fbCheckOutRecordService.get(id);
        if (null == fbCheckOutRecord)
            return ResultGenerator.fail("该FbCheckOutRecord不存在");
        return ResultGenerator.success(toEagerDto(fbCheckOutRecord));
    }

    @ApiOperation(value = "更新方棒检验反切标志")
    @GetMapping("/updateIsCutBack")
    public Result<FbCheckOutRecordDto> updateIsCutBack(@RequestParam int isCutBack, @RequestParam String sectionNo) {
        fbCheckOutRecordService.updateIsCutBack(isCutBack, sectionNo);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据晶编号查询方棒信息")
    @GetMapping("/findBySectionNoList")
    public Result<List<FbCheckOutRecordDto>> findBySectionNoList(@RequestParam List<String> sectionNoList) {
        ArrayList<FbCheckOutRecordDto> checkOutRecordDtoArrayList = new ArrayList<>();
        List<FbCheckOutRecord> fbCheckOutRecordList = fbCheckOutRecordService.findBySectionNoList(sectionNoList);
        for (FbCheckOutRecord fbCheckOutRecord : fbCheckOutRecordList) {
            FbCheckOutRecordDto dto = modelMapper.map(fbCheckOutRecord, FbCheckOutRecordDto.class);
            checkOutRecordDtoArrayList.add(dto);
        }
        return ResultGenerator.success(checkOutRecordDtoArrayList);
    }

    @ApiOperation(value = "修改方棒检验信息")
    @PostMapping("/saveOrUpdateFbCheckOutRecord")
    public Result saveOrUpdateFbCheckOutRecord(@RequestBody List<FbCheckOutRecordDto> fbCheckOutRecordList) {
        for (FbCheckOutRecordDto fbCheckOutRecordDto : fbCheckOutRecordList) {
            FbCheckOutRecord fbCheckOutRecord = modelMapper.map(fbCheckOutRecordDto, FbCheckOutRecord.class);
            fbCheckOutRecordService.saveOrUpdate(fbCheckOutRecord);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建方棒检验")
    @PostMapping("/create")
//    @TokenNotValidation
    public Result create(@RequestBody @Valid @ApiParam(value = "方棒检验信息对象") List<FbCheckOutRecordDto> fbCheckOutRecordDtos, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            for (FbCheckOutRecordDto fbCheckOutRecordDto : fbCheckOutRecordDtos) {
                List<SquareRodNumber> squareRodNumbersBySectionNo = squareRodNumberService.getSquareRodNumbersBySectionNo(fbCheckOutRecordDto.getFbSectionNo());
                String point = null;
                if (null != squareRodNumbersBySectionNo && squareRodNumbersBySectionNo.size() > 0) {
                    point = squareRodNumbersBySectionNo.get(0).getPoint();
                    List<SquareRodNumber> squareRodNumbers = squareRodNumberService.getSquareRodNumbers(squareRodNumbersBySectionNo.get(0).getPoint());
//                    redisTemplate.opsForValue().set(squareRodNumbers.get(0).getPoint(), squareRodNumbers.get(0).getCrystalNo());
                    redisTemplate.opsForValue().set(squareRodNumbers.get(0).getPoint(), fbCheckOutRecordDto.getFbSectionNo());
                    for (SquareRodNumber squareRodNumber : squareRodNumbers) {
                        squareRodNumberService.delete(squareRodNumber.getId());
                    }
                }
                String returnWorkOrder = null;
                if ("退货复检".equals(fbCheckOutRecordDto.getCheckoutName())) {
                    //1. 查询退货复检工单
                    // 查询条件 时间范围内
                    //`gltrp` datetime DEFAULT NULL COMMENT 'plan end date\r\n计划结束时间',
                    // `gstrp` datetime NOT NULL COMMENT 'plan start date\r\n计划开始时间',
                    // status REL 未关单的工单
                    // 未查到报错
                    String status = "REL";
                    List<DictionaryItem> dictionaryItemList = dictionaryItemService.findByThemeValueAndEnable("return_work_order", true);
                    if (CollectionUtils.isEmpty(dictionaryItemList)) {
                        throw new RuntimeException("未在数据字典中维护退货工单，词条值为:return_work_order");
                    }
                    List<String> auartList = dictionaryItemList.stream().map(DictionaryItem::getName).collect(Collectors.toList());
                    List<FbProductionOrder> fbProductionOrderList = fbProductionOrderService.findByGstrpAndGltrpAndStatusAndAuart(auartList, status);
                    if (CollectionUtils.isEmpty(fbProductionOrderList)) {
                        throw new RuntimeException("未查询到退货复检工单");
                    }
                    FbTurnstoreTrayItem fbTurnstoreTrayItemDb = fbTurnstoreTrayItemService.findBySectionNo3(fbCheckOutRecordDto.getFbSectionNo());
                    if (Objects.isNull(fbTurnstoreTrayItemDb)){
                        throw new RuntimeException("该方棒编号"+fbCheckOutRecordDto.getFbSectionNo()+"未在方棒组托明细中查询到数据");
                    }
                    FbProductionOrder order= fbProductionOrderService.findByAufnr(fbTurnstoreTrayItemDb.getOrderNo());
                    if (Objects.isNull(order)){
                        throw new RuntimeException("该工单号"+fbTurnstoreTrayItemDb.getOrderNo()+"未在方棒生产订单中查询到数据");
                    }
                    FbProductionOrder newOrder = null;
                    for (FbProductionOrder sOrder : fbProductionOrderList) {
                        if (order.getZorientationind() == null || StringUtils.isEmpty(order.getZorientationind()) || "非定向".equals(order.getZorientationind())
                            && (sOrder.getZorientationind() == null || StringUtils.isEmpty(sOrder.getZorientationind()) || "非定向".equals(sOrder.getZorientationind()))){
                            newOrder=sOrder;
                            break;
                        }else if (order.getZorientationind().equals(sOrder.getZorientationind())){
                            newOrder=sOrder;
                            break;
                        }
                    }
                    if (Objects.isNull(newOrder)){
                        throw new RuntimeException("未查询到退货复检工单");
                    }
                    returnWorkOrder = newOrder.getAufnr();
                    fbCheckOutRecordDto.setMaterialCode(newOrder.getMatnr());
                    fbCheckOutRecordDto.setOrderNo(newOrder.getAufnr());
                    fbCheckOutRecordDto.setWorkOrderNo(newOrder.getAufnr());
                    fbCheckOutRecordDto.setWorkOrderType(newOrder.getAuart());
                    fbCheckOutRecordDto.setZorientationind(newOrder.getZorientationind());
                } else {
                    //处理料号
                    CrystalMaterialRelation bySectionNo = crystalMaterialRelationService.findBySectionNo(fbCheckOutRecordDto.getYbSectionNo());
                    if (null != bySectionNo) {
                        fbCheckOutRecordDto.setMaterialCode(bySectionNo.getMaterialCode());
                        fbCheckOutRecordDto.setOrderNo(bySectionNo.getOrderNo());

                        if (StringUtils.isNotBlank(bySectionNo.getOrderNo())) {
                            FbProductionOrder fbProductionOrder = fbProductionOrderService.findByAufnr(bySectionNo.getOrderNo());
                            if (null != fbProductionOrder) {
                                fbCheckOutRecordDto.setZorientationind(fbProductionOrder.getZorientationind());
                            }
                        }
                    }
                }


                //添加批次号锁定校验
                Result result = ybFeignService.judgeCrystalNoIsLock(null, fbCheckOutRecordDto.getFbSectionNo(), false);
                if (null == result || ResultCode.SUCCESS.getCode() != result.getCode()) {
                    throw new RuntimeException("批次号判断是否锁定调用圆棒服务失败：" + JSONObject.toJSONString(result));
                }
                //查询方棒检验数据库
                FbCheckOutRecord fbCheckOutRecord = fbCheckOutRecordService.findFbCheckOutRecord(fbCheckOutRecordDto.getFbSectionNo());
                if (fbCheckOutRecord == null) {
                    fbCheckOutRecord = new FbCheckOutRecord();
                }
                // 检验数据提交判断是否在方棒检验待进站状态
                wipStorageService.selectWipStorage(fbCheckOutRecordDto.getFbSectionNo(), EnumValuesFactory.WipStorageCode.方棒检验.getKey(), false);
                //fbCheckOutRecord = modelMapper.map(fbCheckOutRecordDto, FbCheckOutRecord.class);
                BeanUtil.copyBeanPropWithOutNullValue(fbCheckOutRecord, fbCheckOutRecordDto, "id");
                fbCheckOutRecord.setPoint(point);
                // 查询配棒信息
                CooperateData byCooperateNo = cooperateDataService.findByCooperateNo(fbCheckOutRecord.getFbSectionNo());
                if (null != byCooperateNo) {
                    // 查询有配棒信息 默认不检测
                    fbCheckOutRecord.setIsFbSizeCheck(false);
                }
//                if (fbCheckOutRecord.getYbSectionNo().startsWith("B") && (null == fbCheckOutRecord.getHeadOxygenContents() || null == fbCheckOutRecord.getTailOxygenContents())) {
//                    Result<YbInspectDataDto> inspectDataBaseBySectionNo = ybFeignService.getInspectDataBaseBySectionNo(fbCheckOutRecord.getYbSectionNo());
//                    //代工数据查询圆棒检验数据
//                    if (inspectDataBaseBySectionNo.getCode() == ResultCode.SUCCESS.getCode()) {
//                        YbInspectDataDto data = inspectDataBaseBySectionNo.getData();
//                        if (null != data) {
//                            BigDecimal oxygenContentHead = data.getOxygenContentHead();
//                            BigDecimal oxygenContentTail = data.getOxygenContentTail();
//                            fbCheckOutRecord.setHeadOxygenContents(oxygenContentHead);
//                            fbCheckOutRecord.setTailOxygenContents(oxygenContentTail);
//                        }
//                    }
//                }

                //获取是否是外发,存在数据则是外发单晶
                Result resultIsOutgo = ybFeignService.judgeCrystalNoIsOutgo(fbCheckOutRecordDto.getFbSectionNo());
                if (ResultCode.SUCCESS.getCode() == resultIsOutgo.getCode() && null != resultIsOutgo.getData()) {
                    fbCheckOutRecord.setOutGoing(1);
                }
                //处理重量
                BigDecimal weight = this.handleWeigth(fbCheckOutRecord);
                fbCheckOutRecordService.saveOrUpdateFbCheckOutRecord(fbCheckOutRecord, false, false);

             /*   if (null != fbCheckOutRecord.getId()){
                    this.handleFieldExtensionRecord(Long.valueOf(fbCheckOutRecord.getId()),fbCheckOutRecordDto.getFieldExtensionShowDtoList());
                }*/

               /* //报工
                ThreadManager.getThreadPollProxy().execute(() -> {
                    try {
                       ybFeignService.sendSquareRodInfo(fbSectionNo,ybSectionNo, weight);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });*/
                try {
                    fbCheckOutDataService.sendFbSectionAndIp(fbCheckOutRecordDto.getFbSectionNo(), fbCheckOutRecordDto.getPoint());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //方棒工时报工：
                try {
                    SwitchConfig config = GlobalSwitch.switchConfig(CODE_SWITCH, "squareWorkHour", false);
                    if (config.isEnable()) {
                        fbCheckOutDataService.sendNewSapWorkHour(fbCheckOutRecordDto, returnWorkOrder);
                    }
//                    else {
//                        fbCheckOutDataService.sendSapWorkHour(fbCheckOutRecordDto.getFbSectionNo());
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("刀剖工时：" + e.getMessage());
                }

//               检验类型是退货复检报工
                if ("退货复检".equals(fbCheckOutRecordDto.getCheckoutName())) {
//1.调拨出库 出32A  311 现在不调拨出库只报消耗
//                        ReportSapGoodsmvtDto reportSapGoodsmvtDto = new ReportSapGoodsmvtDto();
//                        List<ReportSapChargItemDto> reportSapChargItemDtos = new ArrayList<>();
//                        ReportSapChargItemDto reportSapChargItemDto = new ReportSapChargItemDto();
////        reportSapChargItemDto.setAtnam("P01");
////        reportSapChargItemDto.setAtwrt("JK1");
//                        reportSapChargItemDtos.add(reportSapChargItemDto);
//                        reportSapGoodsmvtDto.setChargItems(reportSapChargItemDtos);
//                        reportSapGoodsmvtDto.setAufnr(fbCheckOutRecordDto.getOrderNo());
//                        reportSapGoodsmvtDto.setCharg(fbCheckOutRecordDto.getBatchNo());
//                        reportSapGoodsmvtDto.setBwart("311");
//                        reportSapGoodsmvtDto.setWerks("5041");
//                        reportSapGoodsmvtDto.setUmcha(fbCheckOutRecordDto.getBatchNo());
//                        reportSapGoodsmvtDto.setUmwrk("5041");
//                        RecheckInspectReceiveDetail recheckInspectReceiveDetailDb = receiveDetailService.findByCrystalNoAndState(fbCheckOutRecordDto.getFbSectionNo(), 1);
//                        if (null == recheckInspectReceiveDetailDb) {
//                            throw new RuntimeException("该方棒晶编" + fbCheckOutRecordDto.getFbSectionNo() + "未在退货复检明细中中查到数据,请检查数据");
//                        }
//                        reportSapGoodsmvtDto.setMenge(recheckInspectReceiveDetailDb.getWeight() == null ? "0" : String.valueOf(recheckInspectReceiveDetailDb.getWeight()));
////                       物料主数据查询
//                        MaterialModel materialModelDb = materialModelService.findByCode(fbCheckOutRecordDto.getMaterialCode());
//                        if (null == materialModelDb) {
//                            throw new RuntimeException("该物料号" + fbCheckOutRecordDto.getMaterialCode() + "未从物料主数据查询到信息");
//                        }
//                        reportSapGoodsmvtDto.setMatnr(materialModelDb.getCode());
//                        reportSapGoodsmvtDto.setMeins(materialModelDb.getUnit().getName());
//                        reportSapGoodsmvtDto.setZfcpFlag("");
//                        reportSapGoodsmvtDto.setLgort(recheckInspectReceiveDetailDb.getWarehouseCode());
//                        reportSapGoodsmvtDto.setProcName(EnumValuesFactory.OrderProgress.退货复检调拨.getValue());
//                        reportSapGoodsmvtDto.setUmlgo("P32A");
//                        reportSapGoodsmvtDto.setCrystalNo(fbCheckOutRecordDto.getFbSectionNo());
//
//                        ybFeignClients.sendSapGoodsmvt(reportSapGoodsmvtDto);
//2.调消耗  出32A   261
                    RecheckInspectReceiveDetail recheckInspectReceiveDetailDb = receiveDetailService.findByCrystalNoAndState(fbCheckOutRecordDto.getFbSectionNo(), 1);
                    if (null == recheckInspectReceiveDetailDb) {
                        throw new RuntimeException("该方棒晶编" + fbCheckOutRecordDto.getFbSectionNo() + "未在退货复检明细中中查到数据,请检查数据");
                    }
//                       物料主数据查询
                    MaterialModel materialModelDb = materialModelService.findByCode(fbCheckOutRecordDto.getMaterialCode());
                    if (null == materialModelDb) {
                        throw new RuntimeException("该物料号" + fbCheckOutRecordDto.getMaterialCode() + "未从物料主数据查询到信息");
                    }
                    ReportSapGoodsmvtDto reportSapGoodsmvtDto1 = new ReportSapGoodsmvtDto();
                    List<ReportSapChargItemDto> reportSapChargItemDtos1 = new ArrayList<>();
                    ReportSapChargItemDto reportSapChargItemDto1 = new ReportSapChargItemDto();
//        reportSapChargItemDto1.setAtnam("P01");
//        reportSapChargItemDto1.setAtwrt("JK1");
                    reportSapChargItemDtos1.add(reportSapChargItemDto1);
                    reportSapGoodsmvtDto1.setChargItems(reportSapChargItemDtos1);
                    reportSapGoodsmvtDto1.setBwart("261");
                    reportSapGoodsmvtDto1.setProcName(EnumValuesFactory.OrderProgress.退货复检消耗.getValue());
                    reportSapGoodsmvtDto1.setAufnr(fbCheckOutRecordDto.getOrderNo());
                    reportSapGoodsmvtDto1.setMatnr(materialModelDb.getCode());
                    reportSapGoodsmvtDto1.setMeins(materialModelDb.getUnit().getName());
                    reportSapGoodsmvtDto1.setCharg(fbCheckOutRecordDto.getBatchNo());
                    reportSapGoodsmvtDto1.setMenge(recheckInspectReceiveDetailDb.getWeight() == null ? "0" : String.valueOf(recheckInspectReceiveDetailDb.getWeight()));
                    reportSapGoodsmvtDto1.setDeviceNo(fbCheckOutRecordDto.getDeviceNo());
                    reportSapGoodsmvtDto1.setRemark("退货复检-" + recheckInspectReceiveDetailDb.getId());
                    reportSapGoodsmvtDto1.setWerks("5041");
                    reportSapGoodsmvtDto1.setUmwrk("5041");
                    reportSapGoodsmvtDto1.setZfcpFlag("");
                    reportSapGoodsmvtDto1.setLgort("P32A");
                    ybFeignClients.sendSapGoodsmvt(reportSapGoodsmvtDto1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    private BigDecimal handleWeigth(FbCheckOutRecord fbCheckOutRecord) {
        if (null == fbCheckOutRecord) {
            return null;
        }
        //处理重量
        BigDecimal weight = fbCheckOutRecord.getWeight();
        if (null == weight || weight.compareTo(BigDecimal.ZERO) <= 0 && StringUtils.isNotBlank(fbCheckOutRecord.getSpecification())) {
            List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.THEORETICAL_WEIGHT_COEFFICIENTFB, fbCheckOutRecord.getSpecification(), true);
            if (!CollectionUtils.isEmpty(dictionaryItems)) {
                BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                    if (null != fbCheckOutRecord.getLength()) {
                        weight = fbCheckOutRecord.getLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP);
                        fbCheckOutRecord.setTheoryWeightFb(weight);
                    }
                }
            }
        }
        return weight;
    }

    private void handleReportSapGoodsmvtDto(String fbSectionNo, String ybSectionNo, String weight) {
       /* //查询是否先报过
        Result<ReportSapGoodsmvtDto> byMatnrAndBwart = ybFeignService.findByMatnrAndBwart(fbSectionNo, "101");
        if(null != byMatnrAndBwart && ResultCode.SUCCESS.getCode() == byMatnrAndBwart.getCode() && null != byMatnrAndBwart.getData()){
            ReportSapGoodsmvtDto byMatnrAndBwartData = byMatnrAndBwart.getData();
            byMatnrAndBwartData.setMenge(weight);
            ybFeignService.sendSapGoodsmvt(byMatnrAndBwartData);
            return;
        }*/
        ReportSapGoodsmvtDto reportSapGoodsmvtDto = new ReportSapGoodsmvtDto();
        Result<ReportSapGoodsmvtDto> result = ybFeignService.findByMatnrAndBwart(ybSectionNo, "261");
        if (null != result && ResultCode.SUCCESS.getCode() == result.getCode() && null != result.getData()) {
            ReportSapGoodsmvtDto data = result.getData();
            reportSapGoodsmvtDto.setAufnr(data.getAufnr());
            reportSapGoodsmvtDto.setCharg(data.getCharg());
        }
        reportSapGoodsmvtDto.setBwart("101");
        reportSapGoodsmvtDto.setKostl("5041");
        reportSapGoodsmvtDto.setMatnr(fbSectionNo);
        reportSapGoodsmvtDto.setMenge(weight);
        reportSapGoodsmvtDto.setMeins("KG");
        ybFeignService.sendSapGoodsmvt(reportSapGoodsmvtDto);
    }

    private void handleFieldExtensionRecord(Long fbCheckOutId, List<FieldExtensionShowDto> fieldExtensionShowDtoList) {
        if (null == fbCheckOutId || CollectionUtils.isEmpty(fieldExtensionShowDtoList)) {
            return;
        }
        Date date = new Date();
        List<FieldExtensionRecord> fbCheckOutRecordList = new ArrayList<>();
        for (FieldExtensionShowDto fieldExtensionShowDto : fieldExtensionShowDtoList) {
            if (null != fieldExtensionShowDto.getFieldShowDtoList()) {
                for (FieldShowDto fieldShowDto : fieldExtensionShowDto.getFieldShowDtoList()) {
                    FieldExtensionRecord fieldExtensionRecord = new FieldExtensionRecord();
                    fieldExtensionRecord.setAssociatedId(fbCheckOutId);
                    fieldExtensionRecord.setFieldName(fieldShowDto.getEnglishName());
                    fieldExtensionRecord.setFieldValue(fieldShowDto.getValue());
                    fieldExtensionRecord.setOrderNo(fieldShowDto.getOrderNo());
                    fieldExtensionRecord.setGmtCreate(date);
                    fbCheckOutRecordList.add(fieldExtensionRecord);
                }
            }
        }
        if (fbCheckOutRecordList.size() != 0) {
            fieldExtensionRecordService.saveAll(fbCheckOutRecordList);
        }

    }

//    @ApiOperation(value = "测试")
//    @PostMapping("/test")
//    public Result test(@RequestBody @ApiParam(value = "FbCheckOutRecord") FbRatingResultDto fbRatingResultDto) {
//        try {
//            publishService.publishEvent(new SquareRankEvent(this, fbRatingResultDto));
//        } catch (Exception e) {
//
//        }
//        return ResultGenerator.success();
//
//    }


    @ApiOperation(value = "更新方棒检验")
    @PostMapping("/update")
    public Result update(@RequestBody @ApiParam(value = "FbCheckOutRecord") FbCheckOutRecordDto dto) {

        try {
            //查询方棒检验数据库
            FbCheckOutRecord fbCheckOutRecord = fbCheckOutRecordService.findFbCheckOutRecord(dto.getFbSectionNo());
            if (fbCheckOutRecord == null) {
                fbCheckOutRecord = new FbCheckOutRecord();
            }
            BeanUtil.copyBeanPropWithOutNullValue(fbCheckOutRecord, dto, "id");
            wipStorageService.selectWipStorage(dto.getFbSectionNo(), EnumValuesFactory.WipStorageCode.方棒检验.getKey(), null);
            fbCheckOutRecordService.saveOrUpdateFbCheckOutRecord(fbCheckOutRecord, true, false);
            //处理关联异常数据，先删除，后保存
           /* if (null != fbCheckOutRecord.getId()){
                fieldExtensionRecordService.deleteByAssociatedId(Long.valueOf(fbCheckOutRecord.getId()));
                this.handleFieldExtensionRecord(Long.valueOf(fbCheckOutRecord.getId()),dto.getFieldExtensionShowDtoList());
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();

    }

    @ApiOperation(value = "圆棒样片更新数据同时更新方棒检验")
    @GetMapping("/synchronousUpdate")
    public Result synchronousUpdate(@RequestParam String sectionNo) {

        try {
            sectionNo = sectionNo + "%";
            List<FbCheckOutRecord> allFbCheckOutRecord = fbCheckOutRecordService.findAllFbCheckOutRecord(sectionNo);
            if (null != allFbCheckOutRecord && allFbCheckOutRecord.size() > 0) {
                for (FbCheckOutRecord fbCheckOutRecord : allFbCheckOutRecord) {
                    try {
                        fbCheckOutRecordService.saveOrUpdateFbCheckOutRecord(fbCheckOutRecord, true, false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();

    }

    @ApiOperation(value = "删除方棒检验")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
//        return ResultGenerator.fail("删除失败，请联系管理员");
        Result result = this.fbCheckOutRecordService.deleteFbInspect(ids);
        for (Long id : ids) {
            fieldExtensionRecordService.deleteByAssociatedId(id);
        }
        return result;
    }


    @ApiOperation(value = "修改时获取方棒检验数据库信息的检验类型以及领料来源")
    @GetMapping("/updateGetCheckType")
    public Result updateGetCheckType(@RequestParam String sectionNoFb) {
        return this.fbCheckOutRecordService.updateGetCheckType(sectionNoFb);
    }


    @ApiOperation(value = "通过方棒编号找到圆棒数据信息")
    @GetMapping("/findFbInfoById")
    public Result findByInfoBySectionNoFb(@RequestParam String sectionNoFb) {
        // 检验数据提交判断是否在方棒检验待进站状态
        wipStorageService.selectWipStorage(sectionNoFb, EnumValuesFactory.WipStorageCode.方棒检验.getKey(), false);
        System.out.println(sectionNoFb + "：通过方棒编号找到圆棒数据信息1");
        return this.fbCheckOutRecordService.getFbInfoBySectionNofb(sectionNoFb);
    }

    @ApiOperation(value = "通过方棒编号找到圆棒数据信息")
    @GetMapping("/findFbCheckOutDataByFbSectionNo")
    public Result findFbCheckOutDataByFbSectionNo(@RequestParam String sectionNoFb) {
        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(sectionNoFb);
        return ResultGenerator.success(dataByFbSectionNo);
    }

    @ApiOperation(value = "通过方棒检验信息数据id获取信息")
    @GetMapping("/findFbCheckOutRecordInfoById")
    public Result<FbCheckOutRecordDto> findFbCheckOutRecordInfoById(@RequestParam Long id) {
        Result<FbCheckOutRecordDto> fbCheckOutRecordInfoById = fbCheckOutRecordService.findFbCheckOutRecordInfoById(id);
       /* Map<String, FieldExtensionTable> fieldExtensionTableMap = fieldExtensionTableService.findMapByExtendTable("zhxx_operate_check_out");
        this.handlefieldExtensionTable(id,fieldExtensionTableMap,fbCheckOutRecordInfoById.getData());*/
        return fbCheckOutRecordInfoById;
    }

    @ApiOperation(value = "更新退库的单晶信息")
    @PostMapping("/updateOrderTypeByFbSectionNoList")
    public Result updateOrderTypeByFbSectionNoList(@RequestBody List<String> sectionNoFbList) {

        fbCheckOutDataService.updateOrderTypeByFbSectionNoList(sectionNoFbList, EnumValuesFbServer.ProductionOrderType.返工.getKey(), "复检");
        return ResultGenerator.success();
    }


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

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

    @ApiOperation(value = "模板文件下载")
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        String path = "template/方棒检验模板下载.xls";
        ExcelUtil.download1(path, response);
    }

    @ApiOperation(value = "获取托盘编号")
    @PostMapping("/gainTrayNo")
    public Result<GetFbInfoDto> gainTrayNo() {
        GainTrayNoResultDto gainTrayNoResultDto = null;
        try {
            //请求mcs获取托盘编号（现场固定ip，用ip确定当前检验线）
            gainTrayNoResultDto = mesToMcsService.gainTrayNo();
            if (gainTrayNoResultDto == null || gainTrayNoResultDto.getTrayRfid() == null) {
                return ResultGenerator.fail("获取托盘信息失败！");
            }
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }

        //获取托盘绑定的方棒
        List<String> crystalNoByTrayNo = productionBindingTrayService.findCrystalNoByTrayNo(gainTrayNoResultDto.getTrayRfid());
        if (crystalNoByTrayNo == null || crystalNoByTrayNo.size() < 1) {
            return ResultGenerator.fail("获取托盘【" + gainTrayNoResultDto.getTrayRfid() + "】,未查询到晶棒绑定信息！");
        }

        String sectionNoFb = crystalNoByTrayNo.get(0);
        // 检验数据提交判断是否在方棒检验待进站状态
        try {
            wipStorageService.selectWipStorage(sectionNoFb, EnumValuesFactory.WipStorageCode.方棒检验.getKey(), false);
        } catch (Exception e) {
            return ResultGenerator.fail("【" + sectionNoFb + "】" + e.getMessage());
        }
        Result<GetFbInfoDto> fbInfoBySectionNofb = this.fbCheckOutRecordService.getFbInfoBySectionNofb(sectionNoFb);
        if (fbInfoBySectionNofb != null && fbInfoBySectionNofb.getData() != null) {
            fbInfoBySectionNofb.getData().setTrayCode(gainTrayNoResultDto.getTrayRfid());
            fbInfoBySectionNofb.getData().setCheckLineNo(gainTrayNoResultDto.getLineNo());
        }
        return fbInfoBySectionNofb;
    }

    @ApiOperation(value = "mcs获取url")
    @PostMapping("/getUrl")
    public Result getUrl(@RequestBody @Valid @ApiParam(value = "获取url") JSONObject text) {
        List<DictionaryItem> urls = dictionaryItemService.findItemByThemeValue("url", true);
        if (null == urls || urls.size() == 0) {
            return ResultGenerator.fail("数据字典缺少URL配置");
        }
        String code = text.getString("code");
        List<DictionaryItem> collect = urls.stream().filter(dictionaryItem -> dictionaryItem.getName().equals(code)).collect(Collectors.toList());
        if (null == collect || collect.size() == 0) {
            return ResultGenerator.fail("该约定功能URL未配置");
        }
        return ResultGenerator.success(collect.get(0).getValue());
    }

    @ApiOperation(value = "MCS获取编号线体点位信息")
    @PostMapping("/getResult")
    public Result getResult(@RequestBody @Valid @ApiParam(value = "查询编号及点位") JSONObject text) {
        String point = text.getString("point");
        String sectionNo = null;
        if (redisTemplate.hasKey(point)) {
            sectionNo = redisTemplate.opsForValue().get(point).toString();
        }
        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(sectionNo);
        SquareRodNumberDto squareRodNumberDto = new SquareRodNumberDto();
        squareRodNumberDto.setPoint(point);
        squareRodNumberDto.setCrystalNo(sectionNo);
        if (null != dataByFbSectionNo) {
            squareRodNumberDto.setIsException(true);
            if (redisTemplate.hasKey(point)) {
                redisTemplate.delete(point);
                return ResultGenerator.success(JSONObject.toJSONString(squareRodNumberDto));
            } else {
                return ResultGenerator.fail(JSONObject.toJSONString("未提交检验数据"));
            }
        }
        return ResultGenerator.fail(JSONObject.toJSONString("未提交检验数据"));
    }

//    @ApiOperation(value = "记录方棒编号和点位")
//    @PostMapping("/recordNumberPoint")
//    public Result recordNumberPoint(@RequestBody SquareRodNumberDto squareRodNumberDto){
//
//        if(!StringUtils.isBlank(squareRodNumberDto.getPoint()) && !StringUtils.isBlank(squareRodNumberDto.getCrystalNo())){
//            SquareRodNumber squareRodNumber = new SquareRodNumber();
//            squareRodNumber.setPoint(squareRodNumberDto.getPoint());
//            squareRodNumber.setCrystalNo(squareRodNumberDto.getCrystalNo());
//            squareRodNumberService.saveData(squareRodNumber);
//            return ResultGenerator.success();
//        }
//        return ResultGenerator.fail("晶棒编号或点位为空");
//    }

    @ApiOperation(value = "记录方棒编号和点位")
    @PostMapping("/recordNumberPoint")
    public Result recordNumberPoint1(@RequestBody @Valid @ApiParam(value = "查询编号及点位") JSONObject text) {
        String sectionNoFb = text.getString("sectionNoFb");
        String point = text.getString("point");
        if (!StringUtils.isBlank(point) && !StringUtils.isBlank(sectionNoFb)) {
            List<SquareRodNumber> squareRodNumbers = squareRodNumberService.getSquareRodNumbers(point);

            if (null != squareRodNumbers && squareRodNumbers.size() > 0) {
//                for (SquareRodNumber squareRodNumber : squareRodNumbers) {
//                    squareRodNumberService.delete(squareRodNumber.getId());
//                }
                SquareRodNumber squareRodNumber = new SquareRodNumber();
                squareRodNumber.setPoint(point);
                squareRodNumber.setCrystalNo(sectionNoFb);
                redisTemplate.opsForValue().set(point, sectionNoFb);
                squareRodNumberService.saveData(squareRodNumber);
            } else {
                SquareRodNumber squareRodNumber = new SquareRodNumber();
                squareRodNumber.setPoint(point);
                squareRodNumber.setCrystalNo(sectionNoFb);
                redisTemplate.opsForValue().set(point, sectionNoFb);
                squareRodNumberService.saveData(squareRodNumber);
            }
            return ResultGenerator.success();
        }
        return ResultGenerator.fail("晶棒编号或点位为空");
    }

    @ApiOperation(value = "新的晶棒到位时清空点位绑定信息")
    @PostMapping("/deletePointData")
    public Result deletePointData(@RequestBody @Valid @ApiParam(value = "新的晶棒到位时清空点位绑定信息") JSONObject text) {
        String point = text.getString("point");
        if (redisTemplate.hasKey(point)) {
            redisTemplate.delete(point);
        }
        List<SquareRodNumber> all = squareRodNumberService.findAll();
        if (!CollectionUtils.isEmpty(all)) {
            for (SquareRodNumber squareRodNumber : all) {
                if (squareRodNumber.getCrystalNo().length() > 15) {
                    squareRodNumberService.delete(squareRodNumber.getId());
                    break;
                }
            }
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据点位查询晶棒编号")
    @GetMapping("/getFbSectionNo")
    public Result getFbSectionNo(String point) {

        String dataByFbSectionNo1 = fbCheckOutDataService.findDataByFbSectionNo1(point);
        if (null != dataByFbSectionNo1) {
            return ResultGenerator.success(dataByFbSectionNo1);
        }
        return ResultGenerator.fail("当前点位不存在到位单晶");
    }

    @ApiOperation(value = "方棒SAP上报调试接口")
    @GetMapping("/reportSquareSap")
    public Result reportSquareSap(@RequestParam String fbSectionNo) {
        FbCheckOutRecord fbCheckOutRecord = fbCheckOutRecordService.findFbCheckOutRecord(fbSectionNo);
        if (null == fbCheckOutRecord) {
            return ResultGenerator.fail("单晶方棒检验不存在！");
        }
        log.info("方棒SAP上报调试接口，处理的方棒单晶:{}", JSONObject.toJSONString(fbCheckOutRecord));
        BigDecimal weight = this.handleWeigth(fbCheckOutRecord);
        Result sendSquareRodInfoResult = ybFeignService.sendSquareRodInfo(fbCheckOutRecord.getFbSectionNo(), fbCheckOutRecord.getFbSectionNo(), weight, BaseContextHandler.getUsername());
        log.info("方棒SAP上报调试接口，方棒上报SAP数据结果为:{}", JSONObject.toJSONString(sendSquareRodInfoResult));
        if (null == sendSquareRodInfoResult) {
            throw new RuntimeException("方棒SAP上报调试接口，SAP产出返回为空！");
        }
        if (ResultCode.SUCCESS.getCode() != sendSquareRodInfoResult.getCode()) {
            throw new RuntimeException("方棒SAP上报调试接口，SAP产出上报失败，异常信息为：" + sendSquareRodInfoResult.getMessage());
        }
        return ResultGenerator.fail("当前点位不存在到位单晶");
    }

    @ApiOperation(value = "方棒碳氧值更新")
    @PostMapping("/updateOxygenCarbonByYbSectionNoList")
    public Result updateOxygenCarbonByYbSectionNoList(@RequestBody @ApiParam(value = "方棒碳氧值更新") OxygenCarbonDto oxygenCarbonDto) {

        try {
            fbCheckOutRecordService.updateOxygenCarbonByYbSectionNoList(oxygenCarbonDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }


    @ApiOperation(value = "返切创建检验数据")
    @PostMapping("/saveBackcutInspection")
    public Result saveBackcutInspection(@RequestBody @ApiParam(value = "创建返切检验数据") List<BackcutInspectionDto> backcutInspectionDtos) {

        try {
            fbCheckOutRecordService.saveBackcutInspection(backcutInspectionDtos);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    public FbCheckOutRecordDto toLazyDto(FbCheckOutRecord entity) {
        return modelMapper.map(entity, FbCheckOutRecordDto.class);
    }

    public FbCheckOutRecordDto toLazyDtoNew(FbCheckOutRecord entity, Map<String, FieldExtensionTable> fieldExtensionTableMap) {
        FbCheckOutRecordDto fbCheckOutRecordDto = modelMapper.map(entity, FbCheckOutRecordDto.class);
       /* if (null != fieldExtensionTableMap){
            this.handlefieldExtensionTable(Long.valueOf(entity.getId()),fieldExtensionTableMap,fbCheckOutRecordDto);
        }*/
        return fbCheckOutRecordDto;
    }

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


    public FbCheckOutRecord fromDto(FbCheckOutRecordDto dto) {
        return modelMapper.map(dto, FbCheckOutRecord.class);
    }

    private void handlefieldExtensionTable(Long associatedId, Map<String, FieldExtensionTable> fieldExtensionTableMap, FbCheckOutRecordDto fbCheckOutRecordDto) {
        if (null == fbCheckOutRecordDto) {
            return;
        }
        List<FieldExtensionRecord> byAssociatedId = fieldExtensionRecordService.findByAssociatedId(associatedId);
        Map<String, FieldExtensionShowDto> extensionShowDtoMap = new HashMap<>();

        for (FieldExtensionRecord fieldExtensionRecord : byAssociatedId) {
            if (StringUtils.isNotBlank(fieldExtensionRecord.getFieldName()) && fieldExtensionTableMap.containsKey(fieldExtensionRecord.getFieldName())) {
                FieldExtensionTable fieldExtensionTable = fieldExtensionTableMap.get(fieldExtensionRecord.getFieldName());
                FieldShowDto fieldShowDto = new FieldShowDto();
                fieldShowDto.setOrderNo(fieldExtensionRecord.getOrderNo());
                fieldShowDto.setEnglishName(fieldExtensionRecord.getFieldName());
                fieldShowDto.setName(fieldExtensionTable.getName());
                fieldShowDto.setValue(fieldExtensionRecord.getFieldValue());
                if (extensionShowDtoMap.containsKey(fieldExtensionTable.getTopicName())) {
                    FieldExtensionShowDto fieldExtensionShowDto = extensionShowDtoMap.get(fieldExtensionTable.getTopicName());
                    if (null != fieldExtensionShowDto.getFieldShowDtoList()) {
                        List<FieldShowDto> fieldShowDtoList = fieldExtensionShowDto.getFieldShowDtoList();
                        fieldShowDtoList.add(fieldShowDto);
                        fieldExtensionShowDto.setFieldShowDtoList(fieldShowDtoList);
                    } else {
                        List<FieldShowDto> fieldShowDtoList = new ArrayList<>();
                        fieldShowDtoList.add(fieldShowDto);
                        fieldExtensionShowDto.setFieldShowDtoList(fieldShowDtoList);
                    }
                } else {
                    FieldExtensionShowDto fieldExtensionShowDto = new FieldExtensionShowDto();
                    fieldExtensionShowDto.setTopicName(fieldExtensionTable.getTopicName());
                    fieldExtensionShowDto.setOrderNo(fieldExtensionTable.getOrderNo());
                    List<FieldShowDto> fieldShowDtoList = new ArrayList<>();
                    fieldShowDtoList.add(fieldShowDto);
                    fieldExtensionShowDto.setFieldShowDtoList(fieldShowDtoList);
                    extensionShowDtoMap.put(fieldExtensionTable.getTopicName(), fieldExtensionShowDto);
                }
            }
        }
        List<FieldExtensionShowDto> result = new ArrayList<>();
        extensionShowDtoMap.forEach((key, value) -> result.add(value));
        result.sort(Comparator.comparing(FieldExtensionShowDto::getOrderNo));
        fbCheckOutRecordDto.setFieldExtensionShowDtoList(result);
    }

}
