package com.foreverwin.mesnac.dispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.util.ExceptionUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.dispatch.dto.RouterDTO;
import com.foreverwin.mesnac.dispatch.mapper.ShopOrderReleaseMapper;
import com.foreverwin.mesnac.dispatch.model.SfcDispatch;
import com.foreverwin.mesnac.dispatch.model.ShopOrderRelease;
import com.foreverwin.mesnac.dispatch.service.SfcDispatchService;
import com.foreverwin.mesnac.dispatch.service.ShopOrderReleaseService;
import com.foreverwin.mesnac.meapi.mapper.BomComponentMapper;
import com.foreverwin.mesnac.meapi.model.*;
import com.foreverwin.mesnac.meapi.service.*;
import com.foreverwin.mesnac.meapi.util.StringUtils;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.meext.MEServices;
import com.sap.me.demand.ReleaseShopOrderRequest;
import com.sap.me.demand.ReleaseShopOrderResponse;
import com.sap.me.demand.ReleasedSfc;
import com.sap.me.demand.ShopOrderServiceInterface;
import com.sap.me.nonconformance.NCProductionServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static com.foreverwin.modular.core.meext.PapiServiceEnum.NCProductionService;

/**
 *
 * ClassName: ShopOrderReleaseServiceImpl
 *
 * @author Leon
 *
 * Copyright (C) 2018-2019 上海昊声电子信息技术有限公司.
 *
 * All Rights Reserved
 *
 * http://www.foreverwin.com.cn
 *
 * Create Time: 2021/06/02
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class ShopOrderReleaseServiceImpl implements ShopOrderReleaseService {


    @Autowired
    private SfcService sfcService;
    @Autowired
    private RouterService routerService;
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private WorkCenterService workCenterService;
    @Autowired
    private SfcDispatchService sfcDispatchService;
    @Autowired
    private ShopOrderReleaseMapper shopOrderReleaseMapper;
    @Autowired
    private CustomFieldsService customFieldsService;
    @Autowired
    private BomComponentService bomComponentService;
    @Autowired
    private BomService bomService;

    @Override
    public List<RouterDTO> selectShopOrderRouter(String routerBo) {
        return shopOrderReleaseMapper.selectShopOrderRouter(routerBo);
    }

    @Override
    public List<ShopOrderRelease> findShopOrderList(ShopOrderRelease shopOrderRelease) {
        return shopOrderReleaseMapper.findShopOrderList(shopOrderRelease);
    }

    @Override
    public void shopOrderBomComponentUpdate(String site, String user, List<ShopOrderRelease> shopOrderList) {
        if (shopOrderList == null || shopOrderList.size() <= 0) {
            throw new BaseException("请至少选择一笔需要更新的工单");
        }
        for (ShopOrderRelease shopOrderReleaseModel : shopOrderList) {
            Bom bom = isUpdateBomComponent(shopOrderReleaseModel, true);
            if (bom==null){
                continue;
            }
            //查询工单信息
            String shopOrder = shopOrderReleaseModel.getShopOrder();
            String shopOrderBo = shopOrderReleaseModel.getShopOrderBo();
            ShopOrder shopOrderModel = shopOrderService.getById(shopOrderBo);
            if (shopOrderModel == null) {
                throw new BaseException("工单[" + shopOrder + "]不存在");
            }
            /*if (!"H".equals(bom.getBomType())){
                throw BusinessException.build("工单["+shopOrder+"]的计划物料清单["+plannedBomBo+"]的类型不是'工单'!");
            }*/
            Double qtyToBuild = shopOrderModel.getQtyToBuild();
            // 更新工单BOM的组件数据
            List<BomComponent> bomComponents = bomComponentService.listByBomBo(bom.getHandle());
            List<BomComponent> bomComponentList = new ArrayList<>();
            for (BomComponent bomComponent:bomComponents) {
                try{
                    BigDecimal bomComponentQty = new BigDecimal(bomComponent.getQty());
                    BigDecimal qty = new BigDecimal(qtyToBuild);
                    BigDecimal resultQty = bomComponentQty.divide(qty,4,BigDecimal.ROUND_DOWN);
                    bomComponent.setQty(resultQty.doubleValue());
                }catch (Exception e){
                    throw BusinessException.build("工单组件数量除以工单数量时出现异常，请查看工单["+shopOrder+"]，工单BOM["+bom.getBom()+"]组件的数量!");
                }
                bomComponent.setModifiedDateTime(LocalDateTime.now());
                bomComponentList.add(bomComponent);
            }
            bomComponentService.saveOrUpdateBatch(bomComponentList);

            CustomFields customFields = new CustomFields();
            customFields.setHandle(bom.getHandle());
            customFields.setAttribute("IS_CHANGE_QTY");
            customFields.setValue("TRUE");
            customFields.setCreatedDateTime(new Date());
            customFieldsService.save(customFields);
        }
    }
    @Override
    public Boolean shopOrderRelease(String site, String user,StringBuffer message,ShopOrderRelease shopOrderRelease) {
        //工单标准服务
        ShopOrderServiceInterface shopOrderServiceInterface = null;
        try {
            shopOrderServiceInterface = MEServices.create("com.sap.me.demand", "ShopOrderService", site);
        } catch (ClassNotFoundException ex) {
            throw BusinessException.build("获取ME标准服务失败");
        }

        //查询工单信息
        String shopOrder = shopOrderRelease.getShopOrder();
        String shopOrderBo = shopOrderRelease.getShopOrderBo();
        ShopOrder shopOrderModel = shopOrderService.getById(shopOrderBo);
        int seq = 0;
        Boolean flag = true;
        if (shopOrderModel == null) {
            throw new BaseException("工单[" + shopOrder + "]不存在");
        }

        // 校验工单对应的工单BOM是否更新了组件数据
        isUpdateBomComponent(shopOrderRelease,false);
        String statusBo = shopOrderModel.getStatusBo();
        String routerBo = shopOrderModel.getPlannedRouterBo();
        BigDecimal qtyToBuild = new BigDecimal(shopOrderModel.getQtyToBuild());
        BigDecimal qtyReleased = new BigDecimal(shopOrderModel.getQtyReleased());
        if (!"501".equals(StringUtils.trimHandle(statusBo))) {
                throw new BaseException("工单[" +shopOrder+ "]不是可下达状态");
        }
        if (qtyReleased.compareTo(qtyToBuild) >= 0) {
                throw new BaseException("工单[" +shopOrder+ "]没有可用下达数量");
        }
        BigDecimal qtyToRelease = qtyToBuild.subtract(qtyReleased);

        //查询工艺路线
        Router routerModel = routerService.getCurrentRouter(routerBo);
        if (routerModel == null) {
                throw new BaseException("工艺路线[" +StringUtils.trimHandle(routerBo)+ "]不存在");
        }
        routerBo = routerModel.getHandle();

        //查询工艺路线详细
        List<RouterDTO> routerList = shopOrderReleaseMapper.selectShopOrderRouter(routerBo);
        if (routerList == null || routerList.size() <= 0) {
                throw new BaseException("工艺路线[" +StringUtils.trimHandle(routerBo)+ "]主数据不完整，请确认");
        }

        //工单下达
        ReleaseShopOrderResponse response = null;
        ReleaseShopOrderRequest request = new ReleaseShopOrderRequest();
        request.setShopOrderRef(shopOrderBo);
        request.setQuantityToRelease(qtyToRelease);
        try {
            response = shopOrderServiceInterface.releaseShopOrder(request);
        } catch (Exception e) {
            throw new BaseException(ExceptionUtil.getExceptionMsg(e));
        }
//                ExceptionUtil.throwException(e);

        if (response == null) {
                throw new BaseException("工单下达失败：调用标准接口处理异常");
        }

        List<ReleasedSfc> sfcList = response.getReleasedSfcList();
        if (sfcList == null || sfcList.size() <= 0) {
                throw new BaseException("工单下达失败：获取生产批次清单为空");
        }

        //组装派工数据
        for (int i = 0 ; i < sfcList.size(); i++) {
            ReleasedSfc releasedSfc = sfcList.get(i);

            Sfc sfcModel = new Sfc();
            sfcModel.setSfc(releasedSfc.getSfc());
            sfcModel.setQty(releasedSfc.getQuantity().doubleValue());
            sfcDispatch(site, user, shopOrderModel, sfcModel, routerList);
        }
      return flag;
    }


    //------------------------------------------------------------------------------------------------------------------
    /**派工--按工序**/
    @Override
    public void sfcDispatch(String site, String user, ShopOrder shopOrderModel, Sfc sfcModel, List<RouterDTO> routerList) {
        LocalDateTime nowDate = LocalDateTime.now();

        String router = routerList.get(0).getRouter();
        String routerBo = routerList.get(0).getRouterBo();
        String entryRouterStepBo = routerList.get(0).getEntryRouterStepBo();
        //参数二次处理，定义MAP以步骤标识为KEY
        Map<String, RouterDTO> map = new HashMap<>();
        for (int i = 0; i < routerList.size(); i++) {
            RouterDTO routerDTO = routerList.get(i);
            map.put(routerDTO.getRouterStepBo(), routerDTO);
        }
        if (map == null || map.size() <= 0) {
            return;
        }
        if (StringUtils.isBlank(entryRouterStepBo)) {
            throw BusinessException.build("工艺路线["  + router +"]没有入口步骤");
        }

        String sfc = sfcModel.getSfc();
        String shopOrder = shopOrderModel.getShopOrder();
        String stepId = "";
        String nextStepBo = "";
        String operation = "";
        String routerStepBo = entryRouterStepBo;
        //首工序计划开始时间为工单计划开始时间
        //LocalDateTime plannedStartDate = shopOrderModel.getPlannedStartDate();
        //LocalDateTime plannedCompleteDate = shopOrderModel.getPlannedStartDate();

        //前置步骤&工序
        String prepositionStepId = null;
        String prepositionOperation = null;

        //派工表集合
        List<SfcDispatch> sfcDispatchList = new ArrayList<>();
        //--------------------------------------------------------------------------------------------------------------
        //循环步骤标识记录派工数据
        for (int m = 0 ; m < map.size(); m++) {
            RouterDTO routerDTO = map.get(routerStepBo);
            if (routerDTO == null) {
                break;
            }
            operation = routerDTO.getOperation();
            if (StringUtil.isBlank(operation)) {
                continue;
            }

            stepId = routerDTO.getStepId();
            nextStepBo = routerDTO.getNextStepBo();
            if (StringUtils.isBlank(nextStepBo) && m != map.size() -1) {
                continue;
            }
            String isFirstOperation = (m == 0) ? Constants.BOOL_TRUE : Constants.BOOL_FALSE;

            Double prodHours = new Double(this.prodHoursCl(operation, routerDTO.getProdHours()));
            //计算完成时间
            //plannedCompleteDate = plannedStartDate.plusMinutes(prodHours.longValue());

            //查询工序所属车间
            String workCenter = null;
            if (operation.contains("_")) {
                workCenter = operation.split("_")[0];
            } else {
                workCenter = operation;
            }
            String workCenterBo = HandleEnum.WORK_CENTER.getHandle(site, workCenter);
            WorkCenter workCenterModel = workCenterService.getById(workCenterBo);
            if (workCenterModel == null) {
                throw BusinessException.build("生产车间【" +workCenter+ "】不存在");
            }

            //派工数据
            String dispatchNo = sfc + "-" + stepId;
            SfcDispatch sfcDispatchModel = new SfcDispatch();
            sfcDispatchModel.setHandle(HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));
            sfcDispatchModel.setSite(site);
            sfcDispatchModel.setShopOrder(shopOrder);
            sfcDispatchModel.setSfc(sfc);
            sfcDispatchModel.setDispatchSeq((m + 1)+"");
            sfcDispatchModel.setDispatchNo(dispatchNo);
            sfcDispatchModel.setDispatchStatus(Constants.STATUS_NEW);
            sfcDispatchModel.setDrawingsNo("");
            sfcDispatchModel.setDrawingsRevision("");
            sfcDispatchModel.setIsLock(Constants.STATUS_N);
            sfcDispatchModel.setRouterBo(routerBo);
            sfcDispatchModel.setStepId(stepId);
            sfcDispatchModel.setOperation(operation);
            sfcDispatchModel.setResourceType(routerDTO.getResourceType());
            sfcDispatchModel.setWorkCenter(workCenter);
            sfcDispatchModel.setDispatchQty(sfcModel.getQty());
            sfcDispatchModel.setProdHours(prodHours);
            sfcDispatchModel.setTurnOperation("false");
            //sfcDispatchModel.setPlannedStartDate(plannedStartDate);
            //sfcDispatchModel.setPlannedCompleteDate(plannedCompleteDate);
            sfcDispatchModel.setSoReleasedDate(nowDate);
            sfcDispatchModel.setIsDispatch(Constants.BOOL_FALSE);
            sfcDispatchModel.setIsImport(Constants.BOOL_FALSE);
            sfcDispatchModel.setIsFirstOperation(isFirstOperation);
            sfcDispatchModel.setPrepositionStepId(prepositionStepId);
            sfcDispatchModel.setPrepositionOperation(prepositionOperation);
            sfcDispatchModel.setCreateUser(user);
            sfcDispatchModel.setCreatedDateTime(nowDate);
            sfcDispatchModel.setModifyUser(user);
            sfcDispatchModel.setModifiedDateTime(nowDate);
            sfcDispatchModel.setOther1("false");
            sfcDispatchList.add(sfcDispatchModel);

            //计划开始时间累加
            //plannedStartDate = plannedCompleteDate;

            //赋值下一步骤
            routerStepBo = routerDTO.getNextStepBo();

            //前置工序&步骤赋值
            prepositionStepId = stepId;
            prepositionOperation = operation;
        }

        //批量插入工位&人员派工数据
        sfcDispatchService.saveBatch(sfcDispatchList);
    }

    //------------------------------------------------------------------------------------------------------------------
    @Override
    public void dispatchRefresh(String site, String user, List<ShopOrderRelease> shopOrderList) {
        if (shopOrderList == null || shopOrderList.size() <= 0) {
            throw new BaseException("请至少选择一笔需要下达的工单");
        }

        //--------------------------------------------------------------------------------------------------------------
        for (ShopOrderRelease shopOrderReleaseModel : shopOrderList) {
            String shopOrder = shopOrderReleaseModel.getShopOrder();

            //查询工单信息
            String shopOrderBo = shopOrderReleaseModel.getShopOrderBo();
            ShopOrder shopOrderModel = shopOrderService.getById(shopOrderBo);
            if (shopOrderModel == null) {
                throw new BaseException("工单[" + shopOrder + "]不存在");
            }
            if (shopOrderModel.getQtyReleased() <= 0) {
                throw new BaseException("工单[" + shopOrder + "]还未下达, 不允许刷新动作");
            }

            //----------------------------------------------------------------------------------------------------------
            //查询工单下的生产批次清单
            List<Sfc> sfcList = sfcService.getSfcListByShopOrderBo(shopOrderBo);
            if (sfcList == null || sfcList.size() <= 0) {
                continue;
            }

            for (int i = 0 ; i < sfcList.size(); i++) {
                Sfc sfcModel = sfcList.get(i);

                //如果生产批次还没做下达，不处理
                List<SfcDispatch> sfcDispatchList = sfcDispatchService.findSfcDispatch(site, sfcModel.getSfc(), null, null);
                if (sfcDispatchList == null || sfcDispatchList.size() <= 0) {
                    continue;
                }

                //校验工艺路线
                Router routerModel = routerService.getRouterBySfcBo(sfcModel.getHandle());
                if (routerModel == null) {
                    throw new BaseException("生产批次[" +sfcModel.getSfc()+ "]没有找到工艺路线");
                }

                String routerBo = routerModel.getHandle();
                //----------------------------------------------------------------------------------------------------------
                //查询工艺路线详细
                List<RouterDTO> routerList = shopOrderReleaseMapper.selectShopOrderRouter(routerBo);
                if (routerList == null || routerList.size() <= 0) {
                    throw new BaseException("工艺路线[" +StringUtils.trimHandle(routerBo)+ "]不存在");
                }
                sfcDispatchRefresh(site, user, shopOrderModel, sfcModel, routerList);
            }//end for -- sfcList

        }// end for -- shopOrderList
    }

    //------------------------------------------------------------------------------------------------------------------

    /**
     * 离散派工-刷新派工单
     * 1.新建状态的派工单删除 重新建
     * 2.非新建状态的派工单，不做出来
     *
     * @param site
     * @param user
     * @param shopOrderModel
     * @param sfcModel
     * @param routerList
     */
    public void sfcDispatchRefresh(String site, String user, ShopOrder shopOrderModel, Sfc sfcModel, List<RouterDTO> routerList) {
        LocalDateTime nowDate = LocalDateTime.now();

        String router = routerList.get(0).getRouter();
        String routerBo = routerList.get(0).getRouterBo();
        String entryRouterStepBo = routerList.get(0).getEntryRouterStepBo();
        //参数二次处理，定义MAP以步骤标识为KEY
        Map<String, RouterDTO> map = new HashMap<>();
        for (int i = 0; i < routerList.size(); i++) {
            RouterDTO routerDTO = routerList.get(i);
            map.put(routerDTO.getRouterStepBo(), routerDTO);
        }
        if (map == null || map.size() <= 0) {
            return;
        }
        if (StringUtils.isBlank(entryRouterStepBo)) {
            throw BusinessException.build("工艺路线["  + router +"]没有入口步骤");
        }

        String sfc = sfcModel.getSfc();
        String shopOrder = shopOrderModel.getShopOrder();
        String stepId = "";
        String nextStepBo = "";
        String operation = "";
        String routerStepBo = entryRouterStepBo;
        //首工序计划开始时间为工单计划开始时间
        //LocalDateTime plannedStartDate = shopOrderModel.getPlannedStartDate();
        //LocalDateTime plannedCompleteDate = shopOrderModel.getPlannedStartDate();

        //派工表集合
        List<SfcDispatch> addSfcDispatchList = new ArrayList<>();
        List<SfcDispatch> updateSfcDispatchList = new ArrayList<>();

        //先删除所有新建状态的派工单
        QueryWrapper<SfcDispatch> queryWrapper = new QueryWrapper<>();
        SfcDispatch deleteSfcDispatch = new SfcDispatch();
        deleteSfcDispatch.setSite(site);
        deleteSfcDispatch.setSfc(sfc);
        deleteSfcDispatch.setDispatchStatus(Constants.STATUS_NEW);
        queryWrapper.setEntity(deleteSfcDispatch);
        sfcDispatchService.remove(queryWrapper);

        //--------------------------------------------------------------------------------------------------------------
        //循环步骤标识记录派工数据
        for (int m = 0 ; m < map.size(); m++) {
            RouterDTO routerDTO = map.get(routerStepBo);
            if (routerDTO == null) {
                break;
            }
            operation = routerDTO.getOperation();
            if (StringUtil.isBlank(operation)) {
                continue;
            }

            stepId = routerDTO.getStepId();
            nextStepBo = routerDTO.getNextStepBo();
            if (StringUtils.isBlank(nextStepBo) && m != map.size() -1) {
                continue;
            }
            String isFirstOperation = (m == 0) ? Constants.BOOL_TRUE : Constants.BOOL_FALSE;

            Double prodHours = new Double(this.prodHoursCl(operation, routerDTO.getProdHours()));
            //计算完成时间
            //plannedCompleteDate = plannedStartDate.plusMinutes(prodHours.longValue());

            //查询工序所属车间
            String workCenter = null;
            if (operation.contains("_")) {
                workCenter = operation.split("_")[0];
            } else {
                workCenter = operation;
            }
            String workCenterBo = HandleEnum.WORK_CENTER.getHandle(site, workCenter);
            WorkCenter workCenterModel = workCenterService.getById(workCenterBo);
            if (workCenterModel == null) {
                throw BusinessException.build("生产车间【" +workCenter+ "】不存在");
            }


            //SFC+Operation+stepID是否已经存在派工数据
            List<SfcDispatch> list = sfcDispatchService.findSfcDispatch(site, sfc, operation, stepId);
            if (list == null || list.size() <= 0) {
                //工艺路线新增的工序，直接增加派工数据
                String dispatchNo = sfc + "-" + stepId;
                SfcDispatch sfcDispatchModel = new SfcDispatch();
                sfcDispatchModel.setHandle(HandleEnum.SFC_DISPATCH.getHandle(site, dispatchNo));
                sfcDispatchModel.setSite(site);
                sfcDispatchModel.setShopOrder(shopOrder);
                sfcDispatchModel.setSfc(sfc);
                sfcDispatchModel.setDispatchSeq((m + 1)+"");
                sfcDispatchModel.setDispatchNo(dispatchNo);
                sfcDispatchModel.setDispatchStatus(Constants.STATUS_NEW);
                sfcDispatchModel.setDrawingsNo("");
                sfcDispatchModel.setDrawingsRevision("");
                sfcDispatchModel.setIsLock(Constants.STATUS_N);
                sfcDispatchModel.setRouterBo(routerBo);
                sfcDispatchModel.setStepId(stepId);
                sfcDispatchModel.setOperation(operation);
                sfcDispatchModel.setResourceType(routerDTO.getResourceType());
                sfcDispatchModel.setWorkCenter(workCenter);
                sfcDispatchModel.setDispatchQty(sfcModel.getQty());
                sfcDispatchModel.setProdHours(prodHours);
                sfcDispatchModel.setTurnOperation("false");
                //sfcDispatchModel.setPlannedStartDate(plannedStartDate);
                //sfcDispatchModel.setPlannedCompleteDate(plannedCompleteDate);
                sfcDispatchModel.setSoReleasedDate(nowDate);
                sfcDispatchModel.setIsDispatch(Constants.BOOL_FALSE);
                sfcDispatchModel.setIsImport(Constants.BOOL_FALSE);
                sfcDispatchModel.setIsFirstOperation(isFirstOperation);
                sfcDispatchModel.setCreateUser(user);
                sfcDispatchModel.setCreatedDateTime(nowDate);
                sfcDispatchModel.setModifyUser(user);
                sfcDispatchModel.setModifiedDateTime(nowDate);
                sfcDispatchModel.setOther1("false");
                addSfcDispatchList.add(sfcDispatchModel);
            } else {
                //已经存在的更新
                SfcDispatch sfcDispatchModel = list.get(0);
                sfcDispatchModel.setDispatchSeq((m + 1)+"");
                sfcDispatchModel.setModifyUser(user);
                sfcDispatchModel.setModifiedDateTime(nowDate);
                updateSfcDispatchList.add(sfcDispatchModel);
            }

            //计划开始时间累加
            //plannedStartDate = plannedCompleteDate;

            //赋值下一步骤
            routerStepBo = routerDTO.getNextStepBo();
        }

        //批量插入派工数据
        if (addSfcDispatchList != null && addSfcDispatchList.size() > 0) {
            sfcDispatchService.saveBatch(addSfcDispatchList);
        }

        //批量更新派工数据
        if (updateSfcDispatchList != null && updateSfcDispatchList.size() > 0) {
            sfcDispatchService.updateBatchById(updateSfcDispatchList);
        }
    }

    //------------------------------------------------------------------------------------------------------------------
    /**加工工时校验以及处理**/
    public String prodHoursCl(String operation, String prodHours) {
        if (StringUtils.isBlank(prodHours)) {
            throw BusinessException.build("工艺路线工序[" +operation+ "]的自定义字段加工工时没维护");
        } else if (!StringUtils.isNumeric(prodHours)) {
            throw BusinessException.build("工艺路线工序[" +operation+ "]的自定义字段加工工时不是数值");
        }

        return prodHours;
    }

    /** 校验工单BOM是否已更新 **/
    public Bom isUpdateBomComponent(ShopOrderRelease shopOrderRelease,Boolean bl){
        String shopOrder = shopOrderRelease.getShopOrder();
        String shopOrderBo = shopOrderRelease.getShopOrderBo();
        ShopOrder shopOrderModel = shopOrderService.getById(shopOrderBo);
        if (shopOrderModel == null) {
            throw new BaseException("工单[" + shopOrder + "]不存在");
        }
        String statusBo = shopOrderModel.getStatusBo();
        if (!"501".equals(StringUtils.trimHandle(statusBo)) && bl) {
            throw BusinessException.build("工单[" +shopOrder+ "]不是可下达状态，无法更新工单BOM");
        }
        String plannedBomBo = shopOrderModel.getPlannedBomBo();
        String bomNo = plannedBomBo.split(",")[1];
        Bom bom = new Bom();
        bom.setBom(bomNo);
        bom.setCurrentRevision("true");
        List<Bom> boms = bomService.selectList(bom);
        if (boms == null || boms.isEmpty()){
            throw BusinessException.build("工单["+shopOrder+"]的计划物料清单["+plannedBomBo+"]不存在，请维护主数据!");
        }
        if (boms.size() > 1){
            throw BusinessException.build("工单["+shopOrder+"]的计划物料清单["+plannedBomBo+"]存在多个当前版本，请修改主数据!");
        }
        String handle = boms.get(0).getHandle();
        String customFieldsValue = customFieldsService.getCustomFieldsValue(handle, "IS_CHANGE_QTY");
        if ("TRUE".equals(customFieldsValue)){
            return null;
        }else {
            if (bl){
                return boms.get(0);
            }
            throw BusinessException.build("工单[" +shopOrder+ "]未更新工单BOM，不能点击下达；请先更新工单BOM后，再下达工单！");
        }
    }
}
