package com.sw.mes.fb.checkout.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.erp.entity.ReportSapRecord;
import com.sw.mes.base.erp.service.ReportSapRecordService;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.factory.inspect.entity.SquareSpellRule;
import com.sw.mes.base.factory.inspect.service.SquareSpellRuleService;
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.StoreFeignClients;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.sap.ReportSapGoodsmvtDto;
import com.sw.mes.core.dto.store.WarehouseOutputBillBo;
import com.sw.mes.core.dto.store.WarehouseOutputBillDetailBo;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.enums.EnumValuesFactory;
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.fb.aio.entity.SpellInfo;
import com.sw.mes.fb.aio.service.SpellService;
import com.sw.mes.fb.checkout.dao.FbCheckOutDataDao;
import com.sw.mes.fb.checkout.dao.FbJoinDao;
import com.sw.mes.fb.checkout.dto.SpellValidationReturnDto;
import com.sw.mes.fb.checkout.entity.FbJoin;
import com.sw.mes.fb.checkout.entity.RecutDetail;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.checkout.service.FbDataSpellInfoService;
import com.sw.mes.fb.checkout.service.FbJoinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

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


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
@Slf4j
public class FbJoinServiceImpl extends BaseServiceImpl<FbJoin> implements FbJoinService {
    FbJoinDao dao;

    @Autowired
    public void setDao(FbJoinDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    private SpellService spellService;

    @Autowired
    private FbCheckOutDataDao checkOutDao;

    @Autowired
    private SquareSpellRuleService squareSpellRuleService;

    @Autowired
    private FbDataSpellInfoService fbDataSpellInfoService;

    @Autowired
    private WipStorageService wipStorageService;
    
    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private StoreFeignClients storeFeignClients;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private ReportSapRecordService reportSapRecordService;

    @Override
    public Result pasteStick(List<String> sectionNoFbList) {
        //如果已创建拼方棒直接返回成功
        FbJoin fbJoinBySectionNo = getFbJoinBySectionNo(sectionNoFbList.get(0));
        if(null != fbJoinBySectionNo){
            int count = 0;
            for (String s : sectionNoFbList) {
                if(!fbJoinBySectionNo.getSectionNoGroup().contains(s)){
                    count ++;
                }
            }
            if(count == 0){
                return ResultGenerator.success();
            } else {
                return ResultGenerator.fail(sectionNoFbList + "中已有存在拼棒信息的晶段");
            }
        }
        
        //验证是否可粘棒
        Result<SpellValidationReturnDto> result = spellValidation(sectionNoFbList);
        if (result == null || result.getCode() == null || !result.getCode().equals(200)) {
            return result;
        }
        SpellValidationReturnDto spellValidationReturnDto = result.getData();
        if (spellValidationReturnDto == null) {
            return ResultGenerator.fail("单晶无法拼棒，规则验证失败！");
        }

        //构造单晶圆棒编号组
        StringBuilder lengthGroup = new StringBuilder();
        for (String sectionNo : sectionNoFbList) {
            FbCheckOutData inspect = spellValidationReturnDto.getCheckOutList().stream().filter(o -> o.getFbSectionNo().trim().equalsIgnoreCase(sectionNo.trim())).findAny().orElse(null);
            if (inspect == null) {
                return ResultGenerator.fail("错误," + sectionNo + "单晶无检验信息");
            } else {
                lengthGroup.append(inspect.getLength().stripTrailingZeros().toPlainString()).append(",");
            }
        }
        if (lengthGroup.toString().contains(",")) {
            lengthGroup = new StringBuilder(lengthGroup.substring(0, lengthGroup.length() - 1));
        }
        //改变检验数据库拼数值
        checkOutDao.updateCheckOutFbSectionNoList(sectionNoFbList, sectionNoFbList.size(), StringUtils.join(sectionNoFbList, ","), spellValidationReturnDto.getTotalLength());
        //第一个单晶圆棒检验信息
        FbCheckOutData obj = spellValidationReturnDto.getCheckOutList().stream().filter(o -> o.getFbSectionNo().trim().equalsIgnoreCase(sectionNoFbList.
                get(0).trim())).findAny().orElse(null);

        //主表数据保存
        FbJoin fbJoinEntity = new FbJoin();
        fbJoinEntity.setSectionNoFb(sectionNoFbList.get(0));
        fbJoinEntity.setSectionNoGroup(StringUtils.join(sectionNoFbList, ","));
        if (obj != null) {
            fbJoinEntity.setProductLevelFb(obj.getProductLevel());
            fbJoinEntity.setConductionType(obj.getConductionType());
            fbJoinEntity.setSpecification(obj.getSpecification());
        }
        fbJoinEntity.setStickCount(sectionNoFbList.size());
        fbJoinEntity.setTotalLength(spellValidationReturnDto.getTotalLength());
        fbJoinEntity.setInStoreLengthFb(spellValidationReturnDto.getInStoreLengthFb());
        fbJoinEntity.setTheoryWeight(spellValidationReturnDto.getTheoryWeightFb());
        fbJoinEntity.setTheoryWeightFb(spellValidationReturnDto.getTheoryWeightFb());
        fbJoinEntity.setLengthGroup(String.valueOf(lengthGroup));
        fbJoinEntity.setGapTotal(spellValidationReturnDto.getGapTotal());
        fbJoinEntity.setBindUser(BaseContextHandler.getUsername());
        fbJoinEntity.setBindTime(new Date());
        fbJoinEntity.setState(0);
        dao.save(fbJoinEntity);
        //创建拼棒中间表
        createSpellInfoFb(Long.valueOf(fbJoinEntity.getId()), fbJoinEntity.getSectionNoGroup());

//        //需要判断下之前是否上报过
//        SwitchConfig config = GlobalSwitch.switchConfig(CODE_SWITCH, "pasteStickProfileWorker", false);
//        if(config.isEnable()){
//            for (String s : sectionNoFbList) {
//                ReportSapGoodsmvtDto data = getReportSapGoodsmvtDto(s);
//                ReportSapRecord reportSapRecordWeight = reportSapRecordService.findByFbSectionNoAndBwartAndProcNameAndPushType(s, "101", "刀剖收货", "报工");
//                if(null != data || null != reportSapRecordWeight){
//                    List<FbCheckOutData> dataByFbSectionNo = checkOutDao.findDataByFbSectionNo(s);
//                    if(null != dataByFbSectionNo && dataByFbSectionNo.size() > 0){
//                        checkOutDao.updateCheckOutFbSectionType(s, "标棒");
//                    } else {
//                        throw new RuntimeException("未查询到方棒检验数据：{}" + s);
//                    }
//                    Result sendSquareRodInfoResult;
//                    if(dataByFbSectionNo.get(0).getWeight().compareTo(new BigDecimal(0)) > 0){
//                        sendSquareRodInfoResult = ybFeignClients.sendSquareRodInfo(s, dataByFbSectionNo.get(0).getYbSectionNo(), dataByFbSectionNo.get(0).getWeight(), BaseContextHandler.getUsername());
//                    } else {
//                        sendSquareRodInfoResult = ybFeignClients.sendSquareRodInfo(s, dataByFbSectionNo.get(0).getYbSectionNo(), dataByFbSectionNo.get(0).getTheoryWeightFb(), BaseContextHandler.getUsername());
//                    }
//                    log.info("方棒上报SAP数据结果为:{}", JSONObject.toJSONString(sendSquareRodInfoResult));
//                    if (null == sendSquareRodInfoResult) {
//                        throw new RuntimeException("SAP产出返回为空！");
//                    }
//                    if (ResultCode.SUCCESS.getCode() != sendSquareRodInfoResult.getCode()) {
//                        throw new RuntimeException("SAP产出上报失败，异常信息为：" + sendSquareRodInfoResult.getMessage());
//                    }
//
//                    BigDecimal bigDecimal;
//                    if(dataByFbSectionNo.get(0).getWeight().compareTo(new BigDecimal(0)) > 0){
//                        bigDecimal = dataByFbSectionNo.get(0).getWeight();
//                    } else {
//                        bigDecimal = dataByFbSectionNo.get(0).getTheoryWeightFb();
//                    }
//                    saveReportSapRecordData(dataByFbSectionNo.get(0),"报工", "101", bigDecimal);
//                }
//            }
//        }

        return ResultGenerator.success();
    }

    /**
     * 验证拼棒规格
     */
    @Override
    public Result<SpellValidationReturnDto> spellValidation(List<String> sectionNoFbList) {
        //拼棒验证结果
        SpellValidationReturnDto spellValidationReturnDto = new SpellValidationReturnDto();
        //验证晶段编号重复
        Set<String> set = new HashSet<>(sectionNoFbList);
        boolean checkResult = sectionNoFbList.size() == set.size();
        if (!checkResult) {
            return ResultGenerator.fail("晶段编号重复");
        }
        //检查当前晶棒是否在粘方棒站点
        for (String value : sectionNoFbList) {
            wipStorageService.selectWipStorage(value, EnumValuesFactory.WipStorageCode.方棒检验.getKey(), true);
        }
        
        //默认拼缝长度
        double gapLength = 0;
        String GapLengthStr = dictionaryItemService.findValueByThemeValueAndItemName("SquareRodMatching","GapLength");
		if (StringUtils.isBlank(GapLengthStr)) {
			return ResultGenerator.fail("未配置数据字典方棒配棒[SquareRodMatching]中默认默认拼缝长度[GapLength]");
		}
		gapLength = Double.valueOf(GapLengthStr);
        
        //查询是否绑定过 - zhxx_fb_data_spell_info
        List<SpellInfo> spellInfoList = spellService.spellInfoFb(sectionNoFbList);
        if (spellInfoList != null && spellInfoList.size() > 0) {
            StringBuilder sectionNoError = new StringBuilder();
            for (SpellInfo entity : spellInfoList) {
                sectionNoError.append(entity.getSectionNo()).append(",");
            }
            return ResultGenerator.fail("错误," + sectionNoError + "单晶已绑定");
        }
        
        //从方棒检验表获取方棒检验信息
        List<FbCheckOutData> checkOutList = checkOutDao.findCheckOutDataByFbSectionNoIns(sectionNoFbList);
        if (checkOutList == null || checkOutList.size() == 0) {
            return ResultGenerator.fail("错误,根据单晶编号获取方棒检验信息失败");
        }
        Set<String> specsSet = new HashSet<>();
        List<String> list3 = new ArrayList<>();
        if (checkOutList.size() != sectionNoFbList.size()) {
            StringBuilder sectionNoFbError = new StringBuilder();
            for (FbCheckOutData str : checkOutList) {
                list3.add(str.getFbSectionNo());
                specsSet.add(str.getSpecification());
            }
            for (String s : sectionNoFbList) {
                if (!list3.contains(s)) {
                    sectionNoFbError.append(s).append(",");
                }
            }
            return ResultGenerator.fail("错误," + sectionNoFbError + "等单晶查不到方棒检验信息");
        }
        //获取方棒拼棒规则
        //已加了状态
        List<SquareSpellRule> squareSpellRules = squareSpellRuleService.findBySpecs(checkOutList.get(0).getSpecification());
        //计算拼棒总长
        BigDecimal totalLength = checkOutList.stream().map(e -> e.getLength() == null ? new BigDecimal(0) :
                e.getLength()).reduce(BigDecimal.ZERO, BigDecimal::add);

        //计算入库长度
        BigDecimal inStoreLengthFb = checkOutList.stream().map(e -> e.getInstoreLengthFb() == null ? new BigDecimal(0) :
                e.getInstoreLengthFb()).reduce(BigDecimal.ZERO, BigDecimal::add);
        inStoreLengthFb.add(BigDecimal.valueOf(2 * (sectionNoFbList.size() - 1)));

        //最大直径
        BigDecimal diameterMax = checkOutList.stream().max(Comparator.comparing(FbCheckOutData::getDiameterMax)).get().getDiameterMax();
        //最小直径
        BigDecimal diameterMin = checkOutList.stream().min(Comparator.comparing(FbCheckOutData::getDiameterMin)).get().getDiameterMin();
        //计算直径差
        BigDecimal diameter = diameterMax.subtract(diameterMin);
        //方棒重量
        BigDecimal weight = checkOutList.stream().map(e -> e.getWeight() == null ? new BigDecimal(0) :
                e.getWeight()).reduce(BigDecimal.ZERO, BigDecimal::add);

        //方棒理论重量（kg）
        BigDecimal theoryWeightFb = checkOutList.stream().map(e -> e.getTheoryWeightFb() == null ? new BigDecimal(0) :
                e.getTheoryWeightFb()).reduce(BigDecimal.ZERO, BigDecimal::add);

        SquareSpellRule ruleBySpecs = null;
        //todo 重写
        if (CollectionUtils.isEmpty(squareSpellRules)) {
            return ResultGenerator.fail("方棒拼棒规则不存在，请配置！");
        }
        String splitCode = ",";
        Map<String, List<SquareSpellRule>> squareSplleRuleMap = squareSpellRules.stream().collect(Collectors.groupingBy((t) -> {
//            return t.getSpecs() + splitCode + t.getProductGrade() + splitCode + t.getConductiveModel()+ splitCode + t.getConductiveModel();
            return t.getSpecs() + splitCode + t.getProductGrade() + splitCode + t.getLevelCode();
        }));
        //判断规则是否匹配的标记
        for (int i = 0; i < checkOutList.size(); i++) {
            FbCheckOutData fbCheckOutData = checkOutList.get(i);
            String fbSectionNo = fbCheckOutData.getFbSectionNo();
            String specification = fbCheckOutData.getSpecification();
            String ybLevel = fbCheckOutData.getYbLevel();
            String conductionType = fbCheckOutData.getConductionType();
            String levelCode = fbCheckOutData.getLevelCode();
            
            if(StringUtils.isBlank(specification)) {
            	throw new RuntimeException("晶段:"+fbSectionNo+" 方棒检验数据中规格为空");
            }else if(StringUtils.isBlank(ybLevel)) {
            	throw new RuntimeException("晶段:"+fbSectionNo+" 方棒检验数据中圆棒最终评级为空");
            }else if(StringUtils.isBlank(levelCode)) {
            	throw new RuntimeException("晶段:"+fbSectionNo+" 方棒检验数据中等级码为空");
            }
            
            // String sideLengthRange = fbCheckOutData.getSideLengthRange();
            String key = specification + splitCode + ybLevel + splitCode + levelCode;
            if (squareSplleRuleMap.containsKey(key)) {
                List<SquareSpellRule> squareSpellRulesList = squareSplleRuleMap.get(key);
                
                //实际应用规则
                SquareSpellRule squareSpellRule = judgmentStickCount(squareSpellRulesList, checkOutList.size()+"");
                if(squareSpellRule==null) {
                	throw new RuntimeException("规格:["+key+splitCode+"],拼数:"+checkOutList.size()+"的拼棒规则不存在,请配置");
                }
                
                boolean lengthFlag = judgmentLength(squareSpellRule, totalLength);

                if (!lengthFlag) {
                	throw new RuntimeException("晶段总长没有匹配上规则中的长度范围["+squareSpellRule.getLength()+"]:"+totalLength);
                }

                String productLevelFb = fbCheckOutData.getProductLevelFb();
                boolean productLevelFbFlag = false;
                if (i > 0) {
                    //大于一条数据时候,校验两颗棒子的方棒评级/入库类别
                    String previousProductLevelFb = checkOutList.get(i - 1).getProductLevelFb();
                    productLevelFbFlag = judgmentProductLevelFb(previousProductLevelFb, productLevelFb);
                    if (!productLevelFbFlag) {
                    	throw new RuntimeException("晶段:"+fbSectionNo + " 入库类别:[" + productLevelFb + "] 与 晶段:" + checkOutList.get(i - 1).getFbSectionNo() + "[入库类别:" + previousProductLevelFb + "]不同!");
                    }
                }
            } else {
                //没有找到符合的
            	throw new RuntimeException("在配棒规则中未找到相应的["+ key + "]配棒规则,请配置");
            }
        }
        spellValidationReturnDto.setCheckOutList(checkOutList);
        spellValidationReturnDto.setInStoreLengthFb(inStoreLengthFb);
        spellValidationReturnDto.setTheoryWeightFb(theoryWeightFb);
        spellValidationReturnDto.setWeight(weight);
        spellValidationReturnDto.setTotalLength(totalLength);
        spellValidationReturnDto.setGapTotal(new BigDecimal(gapLength*checkOutList.size()));
        return ResultGenerator.success(spellValidationReturnDto);
    }

    private SquareSpellRule judgmentStickCount(List<SquareSpellRule> squareSpellRulesList, String size) {
		for (SquareSpellRule squareSpellRule : squareSpellRulesList) {
			if(squareSpellRule.getStickCount().equals(size)) {
				return squareSpellRule;
			}
		}
		return null;
	}


	private boolean judgmentLength(SquareSpellRule squareSpellRule, BigDecimal totalLength) {
        String length = squareSpellRule.getLength();
        //判断长度范围
        if (length != null && !length.equals("")) {
            String[] str = length.split(",");
            for (String s : str) {
                List<String> list;
                String[] str1 = s.split("-");
                list = Arrays.asList(str1);
                if (totalLength.floatValue() >= Integer.parseInt(list.get(0)) && totalLength.floatValue() <= Integer.parseInt(list.get(1))) {
                    return true;
                }
            }
        }
        return false;

    }

    private boolean judgmentDiameter(List<SquareSpellRule> squareSpellRulesList, BigDecimal diameter) {
        boolean flag = false;
        for (int j = 0; j < squareSpellRulesList.size(); j++) {
            SquareSpellRule squareSpellRule = squareSpellRulesList.get(j);
            String diameterDifference = squareSpellRule.getDiameterDifference();
            //判断直径差
            if (diameter.compareTo(new BigDecimal(diameterDifference)) <= 0) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    private boolean judgmentProductType(List<SquareSpellRule> squareSpellRulesList, FbCheckOutData fbCheckOutData) {
        boolean flag = false;
        for (int j = 0; j < squareSpellRulesList.size(); j++) {
            SquareSpellRule squareSpellRule = squareSpellRulesList.get(j);
            String productType = squareSpellRule.getProductType();
            //判断产品类型
            if (productType.contains(fbCheckOutData.getProductType())) {
                flag = true;
                break;
            }
        }

        return flag;
    }


    /**
     * 判断不同晶棒的方棒等级/入库类型 是否相同
     * @param previousProductLevelFb
     * @param productLevelFb
     * @return
     */
    private boolean judgmentProductLevelFb(String previousProductLevelFb, String productLevelFb) {
        boolean flag = false;
        //判断入库类别
        if (StringUtils.isNotBlank(previousProductLevelFb) && StringUtils.isNotBlank(productLevelFb) && previousProductLevelFb.equals(productLevelFb)) {
            flag = true;
        }

        return flag;
    }

    /**
     * 判断拼棒的前后棒子的边长是否一致
     *
     * @param previousSideLengthRange
     * @param sideLengthRange
     * @return
     */
    private boolean judgmentFbSideLengthRange(String previousSideLengthRange, String sideLengthRange) {
        boolean flag = false;
        if (StringUtils.isNotBlank(previousSideLengthRange) && StringUtils.isNotBlank(sideLengthRange) && previousSideLengthRange.equals(sideLengthRange)) {
            flag = true;
        }

        return flag;
    }

//    /**
//     * 判断边长是否相同
//     *
//     * @param squareSpellRulesList
//     * @param fbCheckOutData
//     * @return
//     */
//    private boolean judgmentSideLengthRange(List<SquareSpellRule> squareSpellRulesList, FbCheckOutData fbCheckOutData) {
//        boolean flag = false;
//        for (int j = 0; j < squareSpellRulesList.size(); j++) {
//            SquareSpellRule squareSpellRule = squareSpellRulesList.get(j);
//            String sideLengthRange = squareSpellRule.getSideLengthRange();
//            //判断边长
//            if (null != sideLengthRange && !"".equals(sideLengthRange)) {
//                if (null != fbCheckOutData.getSideLengthRange() && !"".equals(fbCheckOutData.getSideLengthRange()) && !sideLengthRange.equals(fbCheckOutData.getSideLengthRange())) {
//                    flag = false;
//                } else {
//                    flag = true;
//                    break;
//                }
//            } else {
//                flag = true;
//                break;
//            }
//
//        }
//
//        return flag;
//    }


    @Override
    public void fbRelieve(Long id, String relieveReason) {
        //获取圆棒单晶编号list
        List<String> sectionNos = new ArrayList<>();
        FbJoin section = dao.getOne(Math.toIntExact(id));
        String[] sectionArray = section.getSectionNoGroup().split(",");
        Collections.addAll(sectionNos, sectionArray);
        //删除拼圆棒中间表
        fbDataSpellInfoService.deleteBySectionNos(sectionNos);
        //改变检验数据库拼数值
        checkOutDao.updateSticksCountFbSectionNoList(sectionNos, 1, null);
        //改变检验信息拼数值
        //checkOutDao.updateFbCheckOutRecordSticksCountFbSectionNoList(sectionNos, 1);
        //更新状态
        dao.UpdateState(Math.toIntExact(id), BaseContextHandler.getUsername(), new Date(), relieveReason);
//        SwitchConfig config = GlobalSwitch.switchConfig(CODE_SWITCH, "fbRelieveProfileWorker", false);
//        if(config.isEnable()){
//            for (String s : sectionArray) {
//                ReportSapGoodsmvtDto data = getReportSapGoodsmvtDto(s);
//                ReportSapRecord reportSapRecordWeight = reportSapRecordService.findByFbSectionNoAndBwartAndProcNameAndPushType(s, "101", "刀剖收货", "报工");
//
//                if(null != data || null != reportSapRecordWeight){
//                    String warehouseCode = null;
//                    Equipment byCode = equipmentService.findByCode(s.substring(6, 11));
//                    if (null != byCode) {
//                        DictionaryItem warehouseLocation = dictionaryItemService.findByThemeValueAndNameAndValueAndEnable("WarehouseLocation", byCode.getArea(), byCode.getSeries(), true);
//                        if (null != warehouseLocation) {
//                            warehouseCode = warehouseLocation.getExtendValue1();
//                        }
//                    }
//                    FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(s);
//                    if (null != dataByFbSectionNo) {
//
//                        BigDecimal bigDecimal;
//                        if(dataByFbSectionNo.getWeight().compareTo(new BigDecimal(0)) > 0){
//                            bigDecimal = dataByFbSectionNo.getWeight();
//                        } else {
//                            bigDecimal = dataByFbSectionNo.getTheoryWeightFb();
//                        }
//                        saveReportSapRecordData(dataByFbSectionNo, "冲销", "102", new BigDecimal(0).subtract(bigDecimal));
//
//                        WarehouseOutputBillBo warehouseOutputBillBo = new WarehouseOutputBillBo();
//                        warehouseOutputBillBo.setType("方棒返切冲销出库");
//                        warehouseOutputBillBo.setAutoAudit(true);
//                        List<WarehouseOutputBillDetailBo> warehouseOutputBillDetailBoList = new ArrayList<>();
//                        WarehouseOutputBillDetailBo warehouseOutputBillDetailBo = new WarehouseOutputBillDetailBo();
//                        warehouseOutputBillDetailBo.setBatchNo(dataByFbSectionNo.getBatchNo());
//                        warehouseOutputBillDetailBo.setMaterialModelCode(dataByFbSectionNo.getMaterialCode());
//                        warehouseOutputBillDetailBo.setWarehouseCode(warehouseCode);
//                        if(dataByFbSectionNo.getWeight().compareTo(new BigDecimal(0)) > 0){
//                            warehouseOutputBillDetailBo.setRequireCount(new BigDecimal(0).subtract(dataByFbSectionNo.getWeight()));
//                            warehouseOutputBillDetailBo.setOutputCount(new BigDecimal(0).subtract(dataByFbSectionNo.getWeight()));
//                        } else {
//                            warehouseOutputBillDetailBo.setRequireCount(new BigDecimal(0).subtract(dataByFbSectionNo.getTheoryWeightFb()));
//                            warehouseOutputBillDetailBo.setOutputCount(new BigDecimal(0).subtract(dataByFbSectionNo.getTheoryWeightFb()));
//                        }
//
//                        warehouseOutputBillDetailBo.setCrystalNo(s);
//                        warehouseOutputBillDetailBoList.add(warehouseOutputBillDetailBo);
//                        warehouseOutputBillBo.setOutputBillDetails(warehouseOutputBillDetailBoList);
//
//                        Result<String> stringResult = storeFeignClients.outputApply(warehouseOutputBillBo);
//                        if (stringResult.getCode() == ResultCode.SUCCESS.getCode()) {
//                            //sap冲销
//                            Result result = ybFeignClients.sendSquareWriteOffAccounts(s, dataByFbSectionNo.getYbSectionNo(), new BigDecimal(0).subtract(bigDecimal), BaseContextHandler.getUsername(), "102");
//                            log.info("方棒上报SAP数据结果为:{}", JSONObject.toJSONString(result));
//                            if (ResultCode.SUCCESS.getCode() != result.getCode()) {
//                                throw new RuntimeException("SAP产出上报失败，异常信息为：" + result.getMessage());
//                            }
//                            return;
//                        } else {
//                            throw new RuntimeException(s + "线边仓出库失败");
//                        }
//                    }
//                }
//            }
//        }
    }

//    private ReportSapGoodsmvtDto getReportSapGoodsmvtDto(String s) {
//        ReportSapGoodsmvtDto data = null;
//        Result<ReportSapGoodsmvtDto> byCrystalNoAndBwart = ybFeignClients.findByCrystalNoAndBwart(s, "101");
//        if (ResultCode.SUCCESS.getCode() != byCrystalNoAndBwart.getCode()) {
//            data = byCrystalNoAndBwart.getData();
//        }
//        return data;
//    }
//
//    public void  saveReportSapRecordData(FbCheckOutData fbCheckOutData, String pushType, String bwart,BigDecimal weight) {
//
//        ReportSapRecord reportSapRecord = new ReportSapRecord();
//        reportSapRecord.setBatcnNo(fbCheckOutData.getBatchNo());
//        reportSapRecord.setBwart(bwart);
//        reportSapRecord.setCount(weight);
//        reportSapRecord.setFbSectionNo(fbCheckOutData.getFbSectionNo());
//        reportSapRecord.setMaterialCode(fbCheckOutData.getMaterialCode());
//        reportSapRecord.setOrderNo(fbCheckOutData.getOrderNo());
//        reportSapRecord.setProcName("刀剖收货");
//        reportSapRecord.setPushTime(new Date());
//        reportSapRecord.setPushType(pushType);
//        reportSapRecord.setUnit("KG");
//        reportSapRecord.setUser(BaseContextHandler.getUsername());
//        reportSapRecordService.saveOrUpdate(reportSapRecord);
//    }

    @Override
    public void unPasteStick(List<String> sectionNos) {
        long id = 0L;
        //删除拼圆棒中间表
        fbDataSpellInfoService.deleteBySectionNos(sectionNos);
        //改变检验数据库拼数值
        checkOutDao.updateSticksCountFbSectionNoList(sectionNos, 1, null);
        //改变检验信息拼数值
        checkOutDao.updateFbCheckOutRecordSticksCountFbSectionNoList(sectionNos, 1);
        //根据单晶编号查询id
        String crystalNo = sectionNos.get(0);
        SpellInfo spellInfo = dao.getFbDataSpellInfoBySectionNo(crystalNo);
        if (spellInfo == null) {
            id = 0L;
        } else {
            id = spellInfo.getSectionId() == null ? 0 : spellInfo.getSectionId();
        }
        //更新状态
        dao.UpdateState(Math.toIntExact(id), BaseContextHandler.getUsername(), new Date(), "组托解绑");


    }

    @Override
    public void pdaRelieveBySectionNo(String sectionNo, String relieveReason) {
        SpellInfo info = fbDataSpellInfoService.findBySectionNo(sectionNo);
        if (info != null) {
            FbJoin section = dao.getOneBySectionId(Math.toIntExact(info.getSectionId()));
            //获取方棒单晶编号list
            List<String> sectionNos = new ArrayList<>();
            String[] sectionArray = section.getSectionNoGroup().split(",");
            Collections.addAll(sectionNos, sectionArray);
            //删除拼方棒中间表
            fbDataSpellInfoService.deleteBySectionNos(sectionNos);
            //改变检验数据库拼数值
            checkOutDao.updateSticksCountFbSectionNoList(sectionNos, 1, null);
            //改变检验信息拼数值
            checkOutDao.updateFbCheckOutRecordSticksCountFbSectionNoList(sectionNos, 1);
            dao.UpdateState(section.getId(), BaseContextHandler.getUsername(), new Date(), relieveReason);
        } else {
            throw new RuntimeException("错误，该晶段没有绑定记录");
        }
    }

    @Override
    public FbJoin getFbJoinBySectionNo(String sectionNoFb) {
        return dao.findByGroupNoAndState(sectionNoFb, 0);
        // return dao.getFbJoinBySectionNo(sectionNoFb);
    }

    @Override
    public List<FbJoin> getFbJoinDaoList(String[] ids) {
        return dao.getFbJoinDaoList(ids);
    }

    @Override
    public void updateIsSend(Integer id, int i) {
        dao.updateIsSend(id, i);
    }

    @Override
    public void deleteById(Integer id) {
        FbJoin section = dao.getOne(Math.toIntExact(id));
        //获取圆棒单晶编号list
        List<String> sectionNos = new ArrayList<>();
        String[] sectionArray = section.getSectionNoGroup().split(",");
        Collections.addAll(sectionNos, sectionArray);
        //删除拼圆棒中间表
        fbDataSpellInfoService.deleteBySectionNos(sectionNos);
        //改变检验数据库拼数值
        checkOutDao.updateSticksCountFbSectionNoList(sectionNos, 1, null);
        //改变检验信息拼数值
        checkOutDao.updateFbCheckOutRecordSticksCountFbSectionNoList(sectionNos, 1);
        dao.deleteById(id);
    }

    private void createSpellInfoFb(Long sectionId, String noGroup) {
        if (StringUtils.isNotBlank(noGroup)) {
            List<String> nos = Arrays.asList(noGroup.split(","));
            if (nos.size() > 1) {
                for (String no : nos) {
                    SpellInfo info = fbDataSpellInfoService.findBySectionNo(no);
                    if (info == null) {
                        info = new SpellInfo();
                    }
                    info.setSectionId(sectionId);
                    info.setSectionNo(no);
                    fbDataSpellInfoService.saveOrUpdate(info);
                }
            }
        }
    }
}