package com.sw.mes.fls.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.MachineCapacityKfService;
import com.sw.mes.base.factory.inspect.entity.FbAppearRule;
import com.sw.mes.base.factory.inspect.entity.ProductAssemblyRule;
import com.sw.mes.base.factory.inspect.service.FbAppearRuleService;
import com.sw.mes.base.factory.inspect.service.ProductAssemblyConfigService;
import com.sw.mes.base.factory.inspect.service.ProductAssemblyRuleService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.DataInspectLogDto;
import com.sw.mes.core.dto.FlsYbIssueRecordDto;
import com.sw.mes.core.dto.GetFbInfoDto;
import com.sw.mes.core.dto.PlanWaterLineManageRecordDto;
import com.sw.mes.core.dto.mes.pc.yb.ProductionBindingTrayDto;
import com.sw.mes.core.dto.mes.pc.yb.YbInspectDataDto;
import com.sw.mes.core.entity.FbCheckOutData;
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.DateUtil;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.core.utils.NumberUtil;
import com.sw.mes.fb.aio.dto.RecutDto;
import com.sw.mes.fb.aio.entity.GrindingBlanking;
import com.sw.mes.fb.aio.service.GrindingBlankingService;
import com.sw.mes.fb.checkout.dao.RecutDetailDao;
import com.sw.mes.fb.checkout.dto.Flag4MDto;
import com.sw.mes.fb.checkout.entity.RecutDetail;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.checkout.service.FbCheckOutRecordService;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTray;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTrayItem;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayItemService;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayService;
import com.sw.mes.fls.dto.*;
import com.sw.mes.fls.entity.TempTurnstoreTray;
import com.sw.mes.fls.entity.TempTurnstoreTrayItem;
import com.sw.mes.fls.service.FlsToMesService;
import com.sw.mes.fls.service.ProductionBindingTrayService;
import com.sw.mes.fls.service.TempTurnstoreTrayItemService;
import com.sw.mes.fls.service.TempTurnstoreTrayService;
import com.sw.mes.mcs.dto.SquareBindingDto;
import com.sw.mes.mcs.service.MesToMcsService;
import com.sw.mes.mcs.utils.ResultDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Service
@Transactional
public class FlsToMesServiceImpl implements FlsToMesService {

    @Autowired
    private RecutDetailDao recutDetailDao;

    @Autowired
    private MesToMcsService mesToMcsService;

    @Autowired
    private ProductionBindingTrayService productionBindingTrayService;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private FbTurnstoreTrayService fbTurnstoreTrayService;

    @Autowired
    private FbTurnstoreTrayItemService fbTurnstoreTrayItemService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private FbCheckOutRecordService fbCheckOutRecordService;

    @Autowired
    private GrindingBlankingService grindingBlankingService;

    @Autowired
    private ProductAssemblyRuleService productAssemblyRuleService;
    /**
     * 圆棒检验数据库
     */
    @Autowired
    private YbFeignClients ybFeignService;

    @Autowired
    private MachineCapacityKfService machineCapacityKfService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FbAppearRuleService inspectAppearRuleService;

    @Autowired
    private TempTurnstoreTrayItemService tempTurnstoreTrayItemService;

    @Autowired
    private TempTurnstoreTrayService tempTurnstoreTrayService;

    @Autowired
    FlsToMesService findByTrayName;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private SysLogService sysLogService;

    @Override
    public Result bindingFbwithTray(BiddingFbWithTrayDto biddingFbWithTrayDto) {
        //数据验证

        //查询圆棒检验数据表
        // 通过方棒编号去追溯表中找到对应的圆棒id 编号信息
        RecutDetail bySectionNoFb = recutDetailDao.findBySectionNoFb(biddingFbWithTrayDto.getFbSectionNo());
        if (bySectionNoFb == null) {
            return ResultGenerator.fail("该方棒" + biddingFbWithTrayDto.getFbSectionNo() + "不存在，无法录入数据");
        }
//        GetFbInfoDto fbInfoById = ybFeignService.findFbInfoBySectionNoYb(bySectionNoFb.getSectionNo());
//        if (fbInfoById == null) {
//            return ResultGenerator.fail("该方棒对应圆棒:【" + bySectionNoFb.getSectionNo() + "】信息不存在,请先录入圆棒数据");
//        }

        Result<GetFbInfoDto> fbInfoByIdResult = ybFeignService.findFbInfoBySectionNoYb(bySectionNoFb.getSectionNo());
        if (fbInfoByIdResult.getCode() != ResultCode.SUCCESS.getCode()) {
            return ResultGenerator.fail(fbInfoByIdResult.getMessage());
        }
        GetFbInfoDto fbInfoById = fbInfoByIdResult.getData();
        //查询方棒检验数据库
        FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(biddingFbWithTrayDto.getFbSectionNo());

        //托盘方棒绑定

        //初始化绑定信息
        ProductionBindingTrayDto productionBindingTrayDto = new ProductionBindingTrayDto();
        productionBindingTrayDto.setCrystalNo(biddingFbWithTrayDto.getFbSectionNo());
        productionBindingTrayDto.setBindingPeople("SMCS");
        productionBindingTrayDto.setBindingSite("SMCS方棒托盘绑定");
        productionBindingTrayDto.setBindingTime(new Date());
        //自动绑定
        productionBindingTrayDto.setIsBinding(0);
        //只有一个工位，默认为空
        productionBindingTrayDto.setLocationNo("");
        productionBindingTrayDto.setTrayNo(biddingFbWithTrayDto.getTrayCode());
        productionBindingTrayDto.setType("方棒");

        //托盘解绑
        TrayUnBindingDto trayUnBindingDto = new TrayUnBindingDto();
        trayUnBindingDto.setTrayNo(biddingFbWithTrayDto.getTrayCode());
        trayUnBindingDto.setReason("检测口自动解绑单晶");
        trayUnBindingDto.setPoint("检测口");
        trayUnBindingDto.setSource("smcs");
        productionBindingTrayService.UnBinding(trayUnBindingDto);

        //托盘绑定
        Result result = productionBindingTrayService.bindingCrystalFb(productionBindingTrayDto);
        //绑定结果，200成功，其它失败
        if (result.getCode() != 200) {
            return ResultGenerator.fail("绑定异常：" + result.getMessage());
        }

        //推送mcs
        //单晶集合
        List<String> listSectionNo = new ArrayList<>();
        SquareBindingDto squareBindingDto = new SquareBindingDto();
        squareBindingDto.setTrayCode(biddingFbWithTrayDto.getTrayCode());
        Flag4MDto flag4MDto = fbCheckOutRecordService.whetherOrNotSampling(biddingFbWithTrayDto.getFbSectionNo());
        squareBindingDto.setCheckType(null != flag4MDto && flag4MDto.getFlagSizeCheck() ? "1" : "0");
        squareBindingDto.setSquareType(fbInfoById.getProductTypeSecond());
        listSectionNo.add(biddingFbWithTrayDto.getFbSectionNo());
        if (fbCheckOutData != null) {
            BigDecimal length = fbCheckOutData.getLength();
            if (fbCheckOutData.getSticksCount() != null && fbCheckOutData.getSticksCount() > 1) {
                listSectionNo = Arrays.asList(fbCheckOutData.getSectionCompose().split(","));
                length = fbCheckOutData.getSpellBarLength();
            }
            squareBindingDto.setSpec(fbCheckOutData.getSpecification());
            squareBindingDto.setCheckName(fbCheckOutData.getCheckoutName());
            squareBindingDto.setLength(length);
            squareBindingDto.setExperimentRank(fbCheckOutData.getFbExperiLevel());
            squareBindingDto.setProductRank(fbCheckOutData.getYbLevel());
        } else {
            BigDecimal length = fbInfoById.getLength();
            if (fbInfoById.getSticksCount() != null && fbInfoById.getSticksCount() > 1) {
                listSectionNo = Arrays.asList(fbInfoById.getSectionCompose().split(","));
                length = fbInfoById.getSpellBarLength();
            }
            squareBindingDto.setSpec(fbInfoById.getProductTypeSecond().equals("295") ? fbInfoById.getProductTypeSecond() + "*210" : fbInfoById.getProductTypeSecond() + "*182");
            squareBindingDto.setCheckName("一次检验");
            squareBindingDto.setLength(length);
            squareBindingDto.setExperimentRank(fbInfoById.getProductLevelExperiment());
            squareBindingDto.setProductRank(fbInfoById.getProductLevel());
        }
        //磨削下料记录
        GrindingBlanking grindingBlanking = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(biddingFbWithTrayDto.getFbSectionNo());
        if (grindingBlanking != null && grindingBlanking.getGrindingOrder() != null) {
            Integer processNum = null;
            try {
                processNum = Integer.parseInt(grindingBlanking.getGrindingOrder());
            } catch (NumberFormatException e) {

            }
            squareBindingDto.setProcessNum(processNum);
        }
        squareBindingDto.setSquareNo(listSectionNo.stream().collect(Collectors.joining("_")));
        ResultDto resultDto = mesToMcsService.squareBinding(squareBindingDto);
        return ResultGenerator.success();
    }

    @Override
    public Result palletTransfer(PalletTransferDto palletTransferDto) {
        //查询源托盘绑定信息
        String srcTrayCode = palletTransferDto.getSrcTrayCode();
        String destTrayCode = palletTransferDto.getDestTrayCode();
        List<String> crystalNoByTrayNo = productionBindingTrayService.findCrystalNoByTrayNo(srcTrayCode);
        if (CollectionUtils.isEmpty(crystalNoByTrayNo)) {
            return ResultGenerator.fail("源托盘信息不存在");
        }
        TrayUnBindingDto trayUnBindingDto = new TrayUnBindingDto();
        trayUnBindingDto.setTrayNo(srcTrayCode);
        trayUnBindingDto.setReason("方棒线托盘转移,托盘解绑");
        trayUnBindingDto.setPoint("检测口");
        trayUnBindingDto.setSource("smcs");
        productionBindingTrayService.UnBinding(trayUnBindingDto);

        //托盘绑定
        ProductionBindingTrayDto productionBindingTrayDto = new ProductionBindingTrayDto();
        productionBindingTrayDto.setCrystalNo(crystalNoByTrayNo.get(0));
        productionBindingTrayDto.setBindingPeople("SMCS");
        productionBindingTrayDto.setBindingSite("SMCS方棒托盘绑定");
        productionBindingTrayDto.setBindingTime(new Date());
        productionBindingTrayDto.setIsBinding(0);
        productionBindingTrayDto.setLocationNo("");
        productionBindingTrayDto.setTrayNo(destTrayCode);
        productionBindingTrayDto.setType("方棒");
        Result result = productionBindingTrayService.bindingCrystalFb(productionBindingTrayDto);
        if (result.getCode() != 200) {
            return ResultGenerator.fail("绑定异常：" + result.getMessage());
        }
        return ResultGenerator.success();
    }


    /**
     * @param fbSizingDto
     * @return 1直发2尺寸抽检 3反切
     */
    @Override
    public Result<Integer> fbSizingV2(FbSizingDto fbSizingDto) {
        //校验是晶棒是否存在
        String crystalNo = fbSizingDto.getCrystalNo();
        if (StringUtils.isEmpty(crystalNo)) {
            return ResultGenerator.fail("入参晶棒编号不能为空");
        }

        //优先返切
        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(crystalNo);
        if (dataByFbSectionNo == null) {
            return ResultGenerator.fail("晶棒检验数据库信息不存在");
        }
        //评级结果判断
        String productLevelFb = dataByFbSectionNo.getGradeType();
        if (StringUtils.equals(productLevelFb, "反切")) {
            return ResultGenerator.success(3);
        }

        //查询方棒返切记录
        Result resultReCut = ybFeignClients.getReCutBySectionNoFb(crystalNo);
        if (resultReCut != null && resultReCut.getCode() == ResultCode.SUCCESS.getCode()) {
            RecutDto recutDto = JSONObject.parseObject(JSONObject.toJSONString(resultReCut.getData()), RecutDto.class);
            if (recutDto != null) {
                Result result1 = ybFeignClients.getProductionPaintingLineDetail(recutDto.getId(), 4);
                if (result1 != null && result1.getCode() == ResultCode.SUCCESS.getCode() && null != result1.getData()) {
                    // 有画线信息 直接走反切
                    return ResultGenerator.success(3);
                }
            }
        }


        Boolean isFbSizeCheck = dataByFbSectionNo.getIsFbSizeCheck();
        Boolean isFbSizeCheckResult = false;
        String result = "是否抽检 : " + JSONObject.toJSONString(isFbSizeCheck) + "\nsn: " + crystalNo;
        //取页面抽检字段
        if (isFbSizeCheck) {
            return ResultGenerator.success(2);
        } else {
            //抽检规则判断
            GrindingBlanking grindingBlanking = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(crystalNo);
            if (grindingBlanking != null && null != grindingBlanking.getGrindingOrder()) {
                String equipNo = grindingBlanking.getEquipNo();
                if (StringUtils.isNotEmpty(equipNo)) {
                    result = result + "\nequipNo：" + equipNo;
                    //查询所有的外观抽检数据
                    List<FbAppearRule> fbAppearRuleList = inspectAppearRuleService.findAll();

                    if (fbAppearRuleList.size() > 0) {
                        for (FbAppearRule oldFbAppearRule : fbAppearRuleList) {
                            String series = oldFbAppearRule.getSeries();
                            if (equipNo.matches(series.replaceAll("\\*", "") + "\\w+")) {
                                if (oldFbAppearRule != null) {
                                    String piecesRule = oldFbAppearRule.getPiecesRule();
                                    if (piecesRule == null) {
                                        return ResultGenerator.success(1);
                                    }
                                    String[] dateSpilt = piecesRule.split(",");
                                    String startTime = dateSpilt[0];
                                    String endTime = dateSpilt[1];
                                    if (startTime == null || endTime == null) {
                                        return ResultGenerator.success(1);
                                    }
                                    boolean flag = false;
                                    try {
                                        Date startDate = DateUtil.toDate(startTime, "HH:mm:ss");
                                        Date endDate = DateUtil.toDate(endTime, "HH:mm:ss");
                                        Date curDate = DateUtil.toDate(grindingBlanking.getCreatedTime(), "HH:mm:ss");
                                        flag = DateUtil.isEffectiveDate(curDate, startDate, endDate);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    if (flag) {
                                        if (oldFbAppearRule.getPiecesNum() != null) {
                                            String piecesNum = com.sw.mes.core.utils.StringUtils.unwrap(oldFbAppearRule.getPiecesNum(), ",").replace("，", ",");
                                            String[] split = piecesNum.split(",");
                                            for (String num : split) {
                                                if (num.equals(grindingBlanking.getGrindingOrder())) {
                                                    isFbSizeCheckResult = true;
                                                }
                                            }
                                        }
                                    }
                                    result = result + "\n是否满足时间：" + flag;
                                    result = result + "\n磨面顺序号grindingOrder:" + grindingBlanking.getGrindingOrder() + "\n匹配外观检验规则：" + JSON.toJSONString(oldFbAppearRule);

                                }
                            }
                        }
                    }

                }
            }
            result = result + "\n结果 : " + isFbSizeCheckResult;

            SysLog syslog = new SysLog();
            syslog.setCreateTime(new Date());
            syslog.setType("info");
            syslog.setStatus(ResultCode.SUCCESS.getCode());
            syslog.setCreateUserId(BaseContextHandler.getUserID());
            syslog.setCreateUserName(BaseContextHandler.getUsername());
            syslog.setContent(crystalNo);
            syslog.setMethodName("方棒抽检");
            syslog.setName("匹配方棒是否抽检：" + crystalNo);
            syslog.setServerAddr("http://" + IpUtils.getLocalIP());
            syslog.setReqType("GET");
            syslog.setReqIp(IpUtils.getWebServiceReqIP());
            syslog.setResult(result);
            sysLogService.save(syslog);
            if (isFbSizeCheckResult) {
                return ResultGenerator.success(2);
            }
        }


        return ResultGenerator.success(1);
    }

    @Override
    public DeviceAbilityDto getMdDeviceBySectionNo(String sectionNo) {
        Result<YbInspectDataDto> result = ybFeignService.getInspectDataBaseBySectionNo(sectionNo);

        //判断返回
        if (result == null) {
            throw new RuntimeException("圆棒调用错误");
        }
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new RuntimeException("圆棒调用错误,原因：" + result.getMessage());
        }
        YbInspectDataDto dto = result.getData();
        if (dto == null) {
            throw new RuntimeException("晶棒[" + sectionNo + "]没有圆棒检验信息！");
        }

        //检查圆棒检验信息是否完整
        if (StringUtils.isBlank(dto.getConductiveType())
                || StringUtils.isBlank(dto.getProductTypeSecond())
                || StringUtils.isBlank(dto.getDopant())
//                || StringUtils.isBlank(dto.getProductType())
        ) {
            throw new RuntimeException("晶棒[" + sectionNo + "]圆棒检验信息不完整！");
        }
        if (StringUtils.isBlank(dto.getProductLevel())) {
            throw new RuntimeException("晶棒[" + sectionNo + "]没有评级信息！");
        }

//        List<MachineCapacityKf> kfFFreeDevice = new ArrayList<>();
        String productType = "%" + dto.getProductType() + "%";
        String sideLengthRange = null;
//        if(null != dto.getSideLengthRange()){
//            sideLengthRange = "%" + dto.getSideLengthRange() + "%";
//        }
        String zorientationind = dto.getZorientationind();
        List<MachineCapacityKf> kfFFreeDevice = machineCapacityKfService.getMdDevice(dto.getConductiveType(), dto.getProductTypeSecond(), dto.getDopant(), dto.getProductLevel(), productType, sideLengthRange, null, zorientationind);
//        if(null != kfFFreeDevice1 && kfFFreeDevice1.size() == 0){
//            kfFFreeDevice = machineCapacityKfService.getKfDevice(dto.getConductiveType(), dto.getProductTypeSecond(), dto.getDopant(), dto.getProductLevel(), null);
//        } else {
//            kfFFreeDevice.addAll(kfFFreeDevice1);
//        }
        //选取设备加工能力中边长范围字段为空的 或者不为空且与晶棒对应的边长字段匹配的设备
        //目前无边长匹配逻辑，此处需去除
/*        List<MachineCapacityKf> machineCapacityKfList = new ArrayList<>();
        for (MachineCapacityKf machineCapacityKf : kfFFreeDevice) {
            if (null != machineCapacityKf.getSideLengthRange() && !machineCapacityKf.getSideLengthRange().isEmpty() &&
                    null != dto.getSideLengthRange() && !dto.getSideLengthRange().isEmpty() && machineCapacityKf.getSideLengthRange().equals(dto.getSideLengthRange())) {
                machineCapacityKfList.add(machineCapacityKf);
            } else if (null == machineCapacityKf.getSideLengthRange() || (null != machineCapacityKf.getSideLengthRange() && machineCapacityKf.getSideLengthRange().equals(""))) {
                machineCapacityKfList.add(machineCapacityKf);
            }
        }*/

        //下发fls设备加工能力增加匹配圆棒产品等级字段逻辑
        //目前无圆棒等级匹配逻辑，此处需去除
/*        List<MachineCapacityKf> targetKfList = new ArrayList<>();
        for (MachineCapacityKf machineCapacityKf : machineCapacityKfList) {
            if (null != machineCapacityKf.getYbProductGrade() && StringUtils.isNotEmpty(machineCapacityKf.getYbProductGrade())){
                String ybProductGrade = machineCapacityKf.getYbProductGrade();
                String[] strings = ybProductGrade.split(",");
                for (String string : strings) {
                    if (dto.getProductLevel().trim().equals(string.trim())){
                        targetKfList.add(machineCapacityKf);
                    }
                }
            }
        }*/

        //目前无长度范围匹配逻辑，此处需去除
/*        List<MachineCapacityKf> kfFFreeDeviceList = new ArrayList<>();
        if (null != targetKfList && targetKfList.size() > 0) {
            for (MachineCapacityKf machineCapacityKf : targetKfList) {
                Integer lengthRangeMin = Integer.valueOf(machineCapacityKf.getLengthRangeMin());
                Integer lengthRangeMax = Integer.valueOf(machineCapacityKf.getLengthRangeMax());
                Integer integer = Integer.valueOf(String.valueOf(dto.getActualLength()));
                if (integer >= lengthRangeMin && integer <= lengthRangeMax) {
                    kfFFreeDeviceList.add(machineCapacityKf);
                }
                if (lengthRangeMin == 0 && lengthRangeMax == 0) {
                    kfFFreeDeviceList.add(machineCapacityKf);
                }
            }
        }*/

        List<String> devices = kfFFreeDevice.stream()
                .map(item -> Optional.ofNullable(item).map(MachineCapacityKf::getEquipment).map(Equipment::getCode).orElse(""))
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        DeviceAbilityDto deviceAbilityDto = new DeviceAbilityDto();
        deviceAbilityDto.setDeviceList(devices);
        deviceAbilityDto.setLength(Convert.toStr(dto.getActualLength(), null));
        //todo 剩余规格需要修改
        deviceAbilityDto.setSpec(dto.getProductTypeSecond().replace("吋", ""));
        deviceAbilityDto.setSectionNo(sectionNo);
        return deviceAbilityDto;
    }

    @Override
    public List<DeviceAbilityDto> getDeviceByBranchCode(String branchCode) {
        Result<List<FlsYbIssueRecordDto>> result = ybFeignService.queryYbIssueRecordByBranchCode(branchCode);
        List<DeviceAbilityDto> deviceAbilityDtoList = new ArrayList<>();
        if (null != result.getData() && result.getData().size() > 0) {
            List<FlsYbIssueRecordDto> list = result.getData();
            for (FlsYbIssueRecordDto flsYbIssueRecord : list) {
                if (null != flsYbIssueRecord && StringUtils.isNotEmpty(flsYbIssueRecord.getSectionNo()) && null != flsYbIssueRecord.getStatus() && 1 == flsYbIssueRecord.getStatus()) {
                 //获取开方列表,并自动过站
                    DeviceAbilityDto deviceAbility = this.getDeviceBySectionNo(flsYbIssueRecord.getSectionNo());
                    deviceAbility.setStatus(flsYbIssueRecord.getStatus());
                    deviceAbility.setNumNo(flsYbIssueRecord.getNumNo());
                    deviceAbilityDtoList.add(deviceAbility);
                }else if(null != flsYbIssueRecord && StringUtils.isNotEmpty(flsYbIssueRecord.getSectionNo()) && null != flsYbIssueRecord.getStatus() && 1 != flsYbIssueRecord.getStatus()){
                 //异常位的棒子不自动过站
                    DeviceAbilityDto deviceAbility = new DeviceAbilityDto();
                    deviceAbility.setStatus(flsYbIssueRecord.getStatus());
                    deviceAbility.setNumNo(flsYbIssueRecord.getNumNo());
                    deviceAbility.setSectionNo(flsYbIssueRecord.getSectionNo());
                    deviceAbilityDtoList.add(deviceAbility);
                }
            }
        }

        return deviceAbilityDtoList;
    }

    /**
     * @param fbSizingDto
     * @return 1直发2尺寸抽检 3反切
     */
    @Override
    public Result<Integer> fbSizing(FbSizingDto fbSizingDto) {
        //校验是晶棒是否存在
        String crystalNo = fbSizingDto.getCrystalNo();
        if (StringUtils.isEmpty(crystalNo)) {
            return ResultGenerator.fail("入参晶棒编号不能为空");
        }

        //优先返切
        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(crystalNo);
        if (dataByFbSectionNo == null) {
            return ResultGenerator.fail("晶棒检验数据库信息不存在");
        }

        //评级结果判断
        String productLevelFb = dataByFbSectionNo.getGradeType();
        if (StringUtils.equals(productLevelFb, "反切")) {
            return ResultGenerator.success(3);
        }


        //取页面抽检字段
        if (dataByFbSectionNo.getIsFbSizeCheck()) {
            return ResultGenerator.success(2);
        } else {
            //抽检规则判断
            GrindingBlanking grindingBlanking = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(crystalNo);
            if (grindingBlanking != null) {
                String equipNo = grindingBlanking.getEquipNo();
                if (StringUtils.isNotEmpty(equipNo)) {
                    //查询所有的外观抽检数据
                    List<FbAppearRule> allFbappearRule = inspectAppearRuleService.findAll();
                    Map<String, FbAppearRule> fbAppearRuleMap = allFbappearRule.stream().collect(Collectors.toMap(FbAppearRule::getSeries, Function.identity(), (v1, v2) -> v1));
                    FbAppearRule oldFbAppearRule = null;
                    for (Map.Entry<String, FbAppearRule> map : fbAppearRuleMap.entrySet()) {
                        String key = map.getKey();
                        if (equipNo.matches(key.replaceAll("\\*", "") + "\\w+")) {
                            oldFbAppearRule = map.getValue();
                            break;
                        }
                    }
                    if (oldFbAppearRule != null) {
                        String piecesRule = oldFbAppearRule.getPiecesRule();
                        if (piecesRule == null) {
                            return ResultGenerator.success(1);
                        }
                        String[] dateSpilt = piecesRule.split(",");
                        String startTime = dateSpilt[0];
                        String endTime = dateSpilt[1];
                        if (startTime == null || endTime == null) {
                            return ResultGenerator.success(1);
                        }
                        boolean flag = false;
                        try {
                            Date startDate = DateUtil.toDate(startTime, "HH:mm:ss");
                            Date endDate = DateUtil.toDate(endTime, "HH:mm:ss");
                            Date curDate = DateUtil.toDate(new Date(), "HH:mm:ss");
                            flag = DateUtil.isEffectiveDate(curDate, startDate, endDate);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        Integer fb_cj_num = (Integer) redisTemplate.opsForValue().get("fb_cj_num") == null ? 0 : (Integer) redisTemplate.opsForValue().get("fb_cj_num");
                        int piecesNum = Integer.parseInt(oldFbAppearRule.getPiecesNum());
                        if (piecesNum >= fb_cj_num) {
                            //判断当前时间是不是在规则时间内
                            if (flag) {
                                //重置为1
                                if (fb_cj_num == 0) {
                                    fb_cj_num = fb_cj_num + 1;
                                    redisTemplate.opsForValue().set("fb_cj_num", fb_cj_num);
                                    return ResultGenerator.success(2);
                                }
                                if (piecesNum == fb_cj_num) {
                                    redisTemplate.opsForValue().set("fb_cj_num", 0);
                                } else {
                                    fb_cj_num = fb_cj_num + 1;
                                    redisTemplate.opsForValue().set("fb_cj_num", fb_cj_num);
                                }
                            }
                        }
                    }
                }
            }

        }


        return ResultGenerator.success(1);
    }

    @Override
    @Transactional
    public Result productAssemblyInfoUpload(ProductAssemblyInfoDto productAssemblyInfoDto) {
        //组托晶段编号
        String sn = productAssemblyInfoDto.getSectionNo();

        //查询第一个单晶的检验信息，用与创建组托主表
        FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(sn);
        if (fbCheckOutData == null || null == fbCheckOutData.getYbLevel()) {
            return ResultGenerator.fail("【" + sn + "】当前晶段信息不存在或晶段暂未评级");
        }

        FbCheckOutData checkOutFrist = fbCheckOutData;
/*        //拼棒，每一颗都要校验，如果一颗是二类  一颗是正常的话，按照二类的
        if (fbCheckOutData.getSticksCount() != null && fbCheckOutData.getSticksCount() > 1) {
            List<FbCheckOutData> list = fbCheckOutDataService.findCheckOutDataByFbSectionNoIns(Arrays.asList(fbCheckOutData.getSectionCompose().split(",")));
            for (FbCheckOutData item : list) {
//                if("二类".equals(item.getProductLevelFb())){
                checkOutFrist = item;
                break;
//                }
            }
        }*/
        ProductAssemblyRule ruleByIssuePpoint = productAssemblyRuleService.findRuleByIssuePpoint(productAssemblyInfoDto.getTrayName());
//        List<FbTurnstoreTrayItem> trayItemList = fbTurnstoreTrayItemService.findBySectionNoValidate(sn);
        List<FbTurnstoreTrayItem> trayItemList = fbTurnstoreTrayItemService.findBySectionNoValidateAll(sn);
        if (null != trayItemList && !trayItemList.isEmpty()) {
            for (FbTurnstoreTrayItem trayItem : trayItemList) {
                if (9 == trayItem.getState()) {
                    return ResultGenerator.fail("该晶段已进行组托，不能重复组托,所在托号为: " + trayItem.getTrayNo());
                }
//                else if ("退料".equals(trayItem.getHasGone()) && 1 == trayItem.getState()) {
//                    return ResultGenerator.fail("该晶段已发起退料且接收，不能重复组托,所在托号为: " + trayItem.getTrayNo());
//                }
            }
        }


        //将组托信息保存到临时表，如果当前晶段能够判断为完成托，则返回。
        TempTurnstoreTray tempTurnstoreTray = tempTurnstoreTrayService.saveTemp(productAssemblyInfoDto);
        //该方法与当前方法不是同一个事务,目的：避免组托失败导致组托临时表数据回滚丢失。

        //如果判断为完成拖，则进行组托
        if (tempTurnstoreTray != null && tempTurnstoreTray.getFinished() == 1) {
            List<FbTurnstoreTrayItem> items = new ArrayList<>();

            List<TempTurnstoreTrayItem> itemList = tempTurnstoreTrayItemService.findByTrayId(tempTurnstoreTray.getId());
            //为了能读取到tempTurnstoreTrayService.saveTemp(productAssemblyInfoDto)（不是同一事务）已提交的最后一段明细，将该查询方法事务隔离级别调整为读已提交

            for (TempTurnstoreTrayItem item : itemList) {
                //组托详情
                FbCheckOutData checkOutDetail = fbCheckOutDataService.findDataByFbSectionNo(item.getSectionNo());
                List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = fbTurnstoreTrayService.groupItemList(checkOutDetail);
                //添加组托明细信息
                items.addAll(fbTurnstoreTrayItemList);
            }

            //组托主表信息
            FbTurnstoreTray fbTurnstoreTray = new FbTurnstoreTray();
//            fbTurnstoreTray.setPalletType("0");
            fbTurnstoreTray.setPalletType("非正常托");
            DictionaryItem factoryCate = dictionaryItemService.findByThemeValueAndValueAndEnable("FactoryCate", productAssemblyInfoDto.getFactoryName(), true);
            fbTurnstoreTray.setFactoryName(Optional.ofNullable(factoryCate).map(DictionaryItem::getName).orElse("3"));
//            fbTurnstoreTray.setFactoryName("3");
//            fbTurnstoreTray.setProductLevelSecond(checkOutFrist.getProductLevelFb());
            fbTurnstoreTray.setProductLevelSecond(ruleByIssuePpoint.getProductGrade());
            fbTurnstoreTray.setCount(items.size());
            fbTurnstoreTray.setStatus("满托");
            fbTurnstoreTray.setHasGone("综计WMS");
            fbTurnstoreTray.setState(9);
            fbTurnstoreTray.setUser("SMCS自动组托");
            fbTurnstoreTray.setOperationTime(new Date());
            fbTurnstoreTray.setTime(new Date());
            fbTurnstoreTray.setStation(ruleByIssuePpoint.getStation());
            fbTurnstoreTray.setSpecs(checkOutFrist.getSpecification());
            fbTurnstoreTray.setExperGrade(checkOutFrist.getProductLevelFb());
            fbTurnstoreTray.setSticksCount(checkOutFrist.getSticksCount().toString());
            //生成托号
            fbTurnstoreTrayService.createTrayNoMk(fbTurnstoreTray, ruleByIssuePpoint);
            List<DictionaryItem> sideLengthRange = dictionaryItemService.findItemByThemeValue("sideLengthRange", true);
            Map<String, String> collect = sideLengthRange.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue,(v1,v2)->v1));
            fbTurnstoreTray.setBorderWidthValue(collect.get(checkOutFrist.getSideLengthRange()));
            fbTurnstoreTray.setBorderWidthKey(checkOutFrist.getSideLengthRange());
            List<DictionaryItem> multipleSideLogic = dictionaryItemService.findItemByThemeValue("multipleSideLogic", true);
            Map<String, String> collect1 = multipleSideLogic.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getExtendValue1,(v1,v2)->v1));
            fbTurnstoreTray.setBorderWidth(collect1.get(checkOutFrist.getSideLengthRange()));
            //获取组托信息拼数
            String sticksCount = ruleByIssuePpoint.getSticksCount();
            //获取每层有几组
            List<DictionaryItem> fbMakeTrayFloorNum = dictionaryItemService.findItemByThemeValue("fbMakeTrayFloorNum", true);
            Map<String, String> collect2 = fbMakeTrayFloorNum.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue,(v1,v2)->v1));
            int zu = Integer.valueOf(collect2.get(checkOutFrist.getSpecification()));
            //生成组号
            generateGroupNo(items, zu, sticksCount);
            fbTurnstoreTrayService.createTray(ruleByIssuePpoint, fbTurnstoreTray, items);

            tempTurnstoreTray.setGrouped(1);//标记当前已组托
            tempTurnstoreTrayService.saveOrUpdate(tempTurnstoreTray);

            return ResultGenerator.success(fbTurnstoreTray.getTrayNo());
        }
        return ResultGenerator.success();
    }

    private void generateGroupNo(List<FbTurnstoreTrayItem> items, int zu, String sticksCount){
        List<String> bgList = new LinkedList<>();
        List<String> gList = new LinkedList<>();
        List<String> cengList = new LinkedList<>();
        //单包的层号及组号
        if(Integer.valueOf(sticksCount) == 1){
            int ceng = items.size() / zu;
            int groupNo = 1;
            for (int b = 1; b <= ceng; b++) {
                for (int c = 1; c <= zu; c++) {
                    bgList.add(groupNo + "-" + sticksCount);
                    gList.add(groupNo + "");
                    cengList.add(String.valueOf(b));
                    groupNo ++;
                }
            }
        } else {
            int ceng = items.size() / zu / Integer.valueOf(sticksCount);
            int groupNo = 1;
            for (int b = 1; b <= ceng; b++) {
                for (int c = 1; c <= zu; c++) {
                    for (int d = 0; d < Integer.valueOf(sticksCount); d++) {
                        bgList.add(groupNo + "-" + (d + 1));
                        gList.add(groupNo + "");
                        cengList.add(String.valueOf(b));
                    }
                    groupNo ++;
                }
            }
        }
        for (int a = 0; a < cengList.size(); a++) {
            items.get(a).setBatchNoGroup(bgList.get(a));
            items.get(a).setGroupNo(gList.get(a));
            items.get(a).setFloorNo(cengList.get(a));
        }
    }

    /**
     * 通过圆棒编号，找到合适加工能力的加工设备
     *
     * @param sectionNo
     * @return
     */
    @Override
    public DeviceAbilityDto getDeviceBySectionNo(String sectionNo) {
        Result<YbInspectDataDto> result = ybFeignService.getInspectDataBaseBySectionNo(sectionNo);

        //判断返回,信息异常棒不自动过站
        if (result == null) {
            DeviceAbilityDto deviceAbilityDto = new DeviceAbilityDto();
            deviceAbilityDto.setSectionNo(sectionNo);
            deviceAbilityDto.setMessage("圆棒调用错误");
            return deviceAbilityDto;
        }
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            DeviceAbilityDto deviceAbilityDto = new DeviceAbilityDto();
            deviceAbilityDto.setSectionNo(sectionNo);
            deviceAbilityDto.setMessage("圆棒调用错误,原因：" + result.getMessage());
            return deviceAbilityDto;
        }
        YbInspectDataDto dto = result.getData();
        if (dto == null) {
            DeviceAbilityDto deviceAbilityDto = new DeviceAbilityDto();
            deviceAbilityDto.setSectionNo(sectionNo);
            deviceAbilityDto.setMessage("晶棒[" + sectionNo + "]没有圆棒检验信息");
            return deviceAbilityDto;
        }

        //检查圆棒检验信息是否完整
        if (StringUtils.isBlank(dto.getConductiveType())
                || StringUtils.isBlank(dto.getProductTypeSecond())
                || StringUtils.isBlank(dto.getDopant())
//                || StringUtils.isBlank(dto.getProductType())  无产品类别
        ) {
            DeviceAbilityDto deviceAbilityDto = new DeviceAbilityDto();
            deviceAbilityDto.setSectionNo(sectionNo);
            deviceAbilityDto.setMessage("晶棒[" + sectionNo + "]没有圆棒检验信息");
            return deviceAbilityDto;
        }
        if (StringUtils.isBlank(dto.getProductLevel())) {
            DeviceAbilityDto deviceAbilityDto = new DeviceAbilityDto();
            deviceAbilityDto.setSectionNo(sectionNo);
            deviceAbilityDto.setMessage("晶棒[" + sectionNo + "]没有评级信息");
            return deviceAbilityDto;
        }

//        List<MachineCapacityKf> kfFFreeDevice = new ArrayList<>();
        //无产品类别及边长范围
//        String productType = "%" + dto.getProductType() + "%";
//        String sideLengthRange = null;
//        if(null != dto.getSideLengthRange()){
//            sideLengthRange = "%" + dto.getSideLengthRange() + "%";
//        }
        //电阻档位判断  目前无电阻档位的逻辑
/*        List<DictionaryItem> resistanceLevel = dictionaryItemService.findByThemeValueAndEnableOrderByPriority("resistanceLevel", true);
        String resLevel = null;
        for (DictionaryItem dictionaryItem : resistanceLevel) {
            String value = dictionaryItem.getValue();
            String[] split = value.split("-");
            if(split.length > 1){
                if(dto.getWRadialCentre().compareTo(new BigDecimal(split[0])) > 0 && dto.getWRadialCentre().compareTo(new BigDecimal(split[1])) <= 0){
                    resLevel = dictionaryItem.getName();
                    break;
                }
            } else {
                if(dto.getWRadialCentre().compareTo(new BigDecimal(dictionaryItem.getValue())) <= 0){
                    resLevel = dictionaryItem.getName();
                    break;
                }
            }
        }*/
        String zorientationind = dto.getZorientationind();
        List<MachineCapacityKf> kfFFreeDevice = machineCapacityKfService.getKfDevice(dto.getConductiveType(), dto.getProductTypeSecond(), dto.getDopant(), dto.getProductLevel(), null, null, null, zorientationind);
//        if(null != kfFFreeDevice1 && kfFFreeDevice1.size() == 0){
//            kfFFreeDevice = machineCapacityKfService.getKfDevice(dto.getConductiveType(), dto.getProductTypeSecond(), dto.getDopant(), dto.getProductLevel(), null);
//        } else {
//            kfFFreeDevice.addAll(kfFFreeDevice1);
//        }
        //选取设备加工能力中边长范围字段为空的 或者不为空且与晶棒对应的边长字段匹配的设备
        //目前无边长匹配逻辑需去除
/*        List<MachineCapacityKf> machineCapacityKfList = new ArrayList<>();

        for (MachineCapacityKf machineCapacityKf : kfFFreeDevice) {
            if (null != machineCapacityKf.getSideLengthRange() && !machineCapacityKf.getSideLengthRange().isEmpty() &&
                    null != dto.getSideLengthRange() && !dto.getSideLengthRange().isEmpty() && machineCapacityKf.getSideLengthRange().equals(dto.getSideLengthRange())) {
                machineCapacityKfList.add(machineCapacityKf);
            } else if (null == machineCapacityKf.getSideLengthRange() || (null != machineCapacityKf.getSideLengthRange() && machineCapacityKf.getSideLengthRange().equals(""))) {
                machineCapacityKfList.add(machineCapacityKf);
            }
        }*/

        //目前无长度范围匹配逻辑需去除
/*        List<MachineCapacityKf> kfFFreeDeviceList = new ArrayList<>();
        if (null != machineCapacityKfList && machineCapacityKfList.size() > 0) {
            for (MachineCapacityKf machineCapacityKf : machineCapacityKfList) {
                Integer lengthRangeMin = Integer.valueOf(machineCapacityKf.getLengthRangeMin());
                Integer lengthRangeMax = Integer.valueOf(machineCapacityKf.getLengthRangeMax());
                Integer integer = Integer.valueOf(String.valueOf(dto.getActualLength()));
                if (integer >= lengthRangeMin && integer <= lengthRangeMax) {
                    kfFFreeDeviceList.add(machineCapacityKf);
                }
                if (lengthRangeMin == 0 && lengthRangeMax == 0) {
                    kfFFreeDeviceList.add(machineCapacityKf);
                }
            }
        }*/

        List<String> devices = kfFFreeDevice.stream()
                .map(item -> Optional.ofNullable(item).map(MachineCapacityKf::getEquipment).map(Equipment::getCode).orElse(""))
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        DeviceAbilityDto deviceAbilityDto = new DeviceAbilityDto();
        deviceAbilityDto.setDeviceList(devices);
        deviceAbilityDto.setLength(Convert.toStr(dto.getActualLength(), null));
        //todo 剩余规格需修改
        deviceAbilityDto.setSpec(dto.getProductTypeSecond().replace("吋", ""));
        deviceAbilityDto.setSectionNo(sectionNo);

        //todo 以下内容根据实际情况在判断是否修改
        PlanWaterLineManageRecordDto planWaterLineManageRecord = null;
        Result<List<PlanWaterLineManageRecordDto>> listResult = ybFeignService.selectOrders(dto.getDopant(), dto.getConductiveType(), dto.getProductTypeSecond(), dto.getSideLengthRange(), dto.getProductLevel(), dto.getWRadialCentre());
        if (null == listResult || listResult.getCode() != ResultCode.SUCCESS.getCode()) {
            deviceAbilityDto.setWaterLineManageOrderNo("");
        } else {
            List<PlanWaterLineManageRecordDto> planWaterLineManageRecords = listResult.getData();
//            if (null != planWaterLineManageRecords && planWaterLineManageRecords.size() > 0) {
//                for (PlanWaterLineManageRecordDto waterLineManageRecord : planWaterLineManageRecords) {
//                    String realProductType = dto.getProductType();
//                    String[] split = waterLineManageRecord.getProductType().split(",");
//                    for (String s : split) {
//                        if (s.equals(realProductType)) {
//                            planWaterLineManageRecord = waterLineManageRecord;
//                            break;
//                        }
//                    }
//                }
//            }
            if (null != planWaterLineManageRecords && planWaterLineManageRecords.size() > 0) {
                deviceAbilityDto.setWaterLineManageOrderNo(planWaterLineManageRecords.get(0).getAufnr());
            } else {
                deviceAbilityDto.setWaterLineManageOrderNo("");
            }
//            if (planWaterLineManageRecord != null) {
//                deviceAbilityDto.setWaterLineManageOrderNo(planWaterLineManageRecord.getAufnr());
//            }else {
//                deviceAbilityDto.setWaterLineManageOrderNo("");
//            }
        }
        return deviceAbilityDto;
    }


    private Result<ProductAssemblyRule> matching(FbCheckOutData fbCheckOutData) {
        List<ProductAssemblyRule> ruleDto = productAssemblyRuleService.findRuleBySpecs(fbCheckOutData.getSpecification());
        ProductAssemblyRule productAssemblyRule = null;
        if (ruleDto.size() > 0) {
            lab:
            for (ProductAssemblyRule roundSpellRule : ruleDto) {
                boolean flag = false;
                boolean flag1 = true;
                //验证产品评级
                if (fbCheckOutData.getYbLevel() == null) {
                    return ResultGenerator.fail("错误," + fbCheckOutData.getFbSectionNo() + "单晶无产品评级");
                }

                if (roundSpellRule.getProductGrade() != null) {
                    String[] str1 = roundSpellRule.getProductGrade().split(",");
                    for (String s : str1) {
                        if (s.equals(fbCheckOutData.getYbLevel())) {
                            flag1 = false;
                            break;
                        }
                    }
                }
                if (flag1) {
                    continue lab;
                }
                //验证实验等级
                if (StringUtils.isNotBlank(roundSpellRule.getExperGrade()) && !roundSpellRule.getExperGrade().equals(fbCheckOutData.getExperiLevel())) {
                    continue lab;
                }
                //判断导电型号是否符合
                if (StringUtils.isNotBlank(roundSpellRule.getConductiveType()) && !roundSpellRule.getConductiveType().equals(fbCheckOutData.getConductionType())) {
                    continue lab;
                }
                //判断拼数是否符合
                if (StringUtils.isNotBlank(roundSpellRule.getSticksCount()) && NumberUtil.Object2Integer(roundSpellRule.getSticksCount(), 0) > 0 && !roundSpellRule.getSticksCount().contains(fbCheckOutData.getSticksCount().toString())) {
                    continue lab;
                }
                //判断入库类别是否符合
                if (StringUtils.isNotBlank(roundSpellRule.getInputType()) && !roundSpellRule.getInputType().equals(fbCheckOutData.getProductLevelFb())) {
                    continue lab;
                }

                //判断长度范围是否符合
                if (StringUtils.isNotBlank(roundSpellRule.getLength()) && !"非标".equals(roundSpellRule.getLength())) {
                    String length = roundSpellRule.getLength();
                    String lengthType = "不区分棒长";
                    if (!lengthType.equals(length) && null != fbCheckOutData.getLength()) {
                        String[] lengths = length.split(",");
                        for (String s : lengths) {
                            String[] split = s.split("-");
                            if (split.length != 2) {
                                continue;
                            }
                            double minLength = Double.parseDouble(split[0]);
                            double maxLength = Double.parseDouble(split[1]);
                            double actualLength;
                            if (null != fbCheckOutData.getSpellBarLength()) {
                                actualLength = fbCheckOutData.getSpellBarLength().doubleValue();
                            } else {
                                actualLength = fbCheckOutData.getLength().doubleValue();
                            }
                            if (minLength <= actualLength && actualLength <= maxLength) {
                                flag = true;
                            }
                        }
                    }
                }

                if (flag) {
                    productAssemblyRule = roundSpellRule;
                    break;
                }
            }
        } else {
            throw new RuntimeException("成品组托规则没找到，规格：" + fbCheckOutData.getSpecification());
        }


        return ResultGenerator.success(productAssemblyRule);
    }

    private void saveItemList(FbTurnstoreTray fbTurnstoreTray, List<FbTurnstoreTrayItem> items) {
        for (int i = 0; i < items.size(); i++) {
            if (9 == fbTurnstoreTray.getState()) {
                items.get(i).setState(fbTurnstoreTray.getState());
            }
            //序号
            if (null == items.get(i).getOrderNum()) {
                items.get(i).setOrderNum(i + 1);
            }
            //空操作人赋值
            if (null == items.get(i).getUser()) {
                if (null != fbTurnstoreTray.getUpdateUser()) {
                    items.get(i).setUser(fbTurnstoreTray.getUpdateUser());
                } else {
                    items.get(i).setUser(fbTurnstoreTray.getUser());
                }
            }
            items.get(i).setTrayId(fbTurnstoreTray.getId());
            items.get(i).setTrayNo(fbTurnstoreTray.getTrayNo());
            if (null != fbTurnstoreTray.getToWmsTime()) {
                items.get(i).setToWmsTime(fbTurnstoreTray.getToWmsTime());
            }
            if (null != fbTurnstoreTray.getTime()) {
                items.get(i).setTime(fbTurnstoreTray.getTime());
            }
            if (null != fbTurnstoreTray.getOperationTime()) {
                items.get(i).setOperationTime(fbTurnstoreTray.getOperationTime());
            }
            items.get(i).setFactoryName(fbTurnstoreTray.getFactoryName());
            fbTurnstoreTrayItemService.saveOrUpdate(items.get(i));
        }
    }
}
