package com.sw.mes.yb.plan.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sw.mes.base.factory.init.dao.MachineCapacityInfoDao;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.entity.FactoryModel;
import com.sw.mes.base.factory.init.entity.MachineCapacityInfo;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.factory.init.service.FactoryModelService;
import com.sw.mes.base.factory.init.service.MachineCapacityInfoService;
import com.sw.mes.base.factory.init.service.MachineCapacityService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.annotation.ServiceLogs;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.core.dto.erp.ErpOrderDto;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.NumberUtil;
import com.sw.mes.base.factory.material.entity.MaterialType;
import com.sw.mes.base.factory.product.entity.ProductModel;
import com.sw.mes.base.factory.product.service.ProductModelService;
import com.sw.mes.third.entity.RequestLog;
import com.sw.mes.third.service.RequestLogService;
import com.sw.mes.third.service.SendWebService;
import com.sw.mes.yb.plan.dao.ProductionOrderDao;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.entity.ProductionSchedule;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;

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


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Slf4j
@Transactional
public class ProductionOrderServiceImpl extends BaseServiceImpl<ProductionOrder> implements ProductionOrderService {
    @Autowired
    private SendWebService sendWebService;

    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private MachineCapacityService machineCapacityService;
    @Autowired
    private MachineCapacityInfoService machineCapacityInfoService;
    @Autowired
    private ProductionScheduleService productionScheduleService;
    @Autowired
    private RequestLogService requestLogService;
    @Autowired
    private DictionaryItemService dictionaryItemService;
    @Autowired
    private FactoryModelService factoryModelService;

    ProductionOrderDao dao;

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

    @Autowired
    private ProductModelService productModelService;
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private MachineCapacityInfoDao machineCapacityInfoDao;

    @Override
    public void close(ProductionOrder sapProductionOrder) {
        dao.save(sapProductionOrder);
        //向SAP发送订单关闭信息
//        try {
//            List<Teco> list = new ArrayList<>();
//            Teco teco = new Teco();
//            teco.setZMESID(UUID.randomUUID().toString());
//            teco.setWERKS("1011");
//            teco.setSTATUS("1");
//            teco.setCOMMENT("");
//            teco.setAUART(sapProductionOrder.getAuart());
//            teco.setAUFNR(sapProductionOrder.getAufnr());
//            teco.setMATNR(sapProductionOrder.getMatnr());
//            teco.setISSUEDATE(WbServiceUtils.getSapDate(new Date()));//日期 yyyymmdd
//            teco.setISSUETIME(WbServiceUtils.getSapTime(new Date()));//时间 HHmmss
//            list.add(teco);
//            Map map = sendWebService.mesToSap(list, WebServiceUri.WSDL_URL, WebServiceApiName.TECO, 4000);
//            String sapResult = map.get(new QName("ZTYPE")).toString();
//            if (!"S".equals(sapResult)) {
//                String sapError = map.get(new QName("ZMESSAGE")).toString();
//                throw new RuntimeException("向SAP发送订单关闭信息异常:" + sapError);
//            }
//        } catch (Exception e) {
//            log.error("向SAP发送订单关闭信息异常:" + e.getMessage());
//            throw new RuntimeException("向SAP发送订单关闭信息异常:" + e.getMessage());
//        }
    }

    @Override
    public ProductionOrder findByAufnr(String code) {
        List<ProductionOrder> list = dao.findByAufnr(code);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }


    @ServiceLogs(description = "匹配圆棒入库料号")
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, rollbackFor = Exception.class)
    public String matchProductModel(String sectionNo, String diamDecide, String grade, String specifications, String conductiveType, String dopant, Integer sticksCount, BigDecimal actualLength, String sectionType) {
        diamDecide = StringUtils.trim(diamDecide);
        ProductModel productModel;
        //先判断直径判定是否有异常
        if (StringUtils.isNotBlank(diamDecide)) {
            productModel = productModelService.findByProductModel(grade, specifications, conductiveType, dopant, sticksCount, "圆(扭细)%");
        } else {
            //如果没有异常，则判断是否是非标
            if ("标棒".equals(sectionType)) {
                productModel = productModelService.findByProductModelNotDiamDecide(grade, specifications, conductiveType, dopant);
            } else {
                productModel = productModelService.findByProductModelNotDiamDecideFb(grade, specifications, conductiveType, dopant);
            }
        }
        if (productModel != null) {
            return productModel.getCode();
        }
        return null;
    }

    @ServiceLogs(description = "匹配圆棒入库订单编号")
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, rollbackFor = Exception.class)
    public String matchOrder(String sectionNo, String planMaterialCode, String planOrderType, String orderType, String planOrderNo, String checkoutName) {
//        if (orderType != null && orderType.equals(planOrderType)) {
//            return planOrderNo;
//        }
        if (StringUtils.isNotBlank(planMaterialCode)) {
            String field2 = "SPREWORK";
            List<ProductionOrder> productionOrders;
            if (checkoutName != null && checkoutName.contains("复检")) {
                productionOrders = dao.findByProductModelCode(planMaterialCode, DateUtil.toDate(new Date(), DateUtil.longFormat), orderType, field2);
                if (productionOrders.size() == 0) {
                    Integer materialTypeId = Optional.ofNullable(productModelService.findByCode(planMaterialCode)).map(ProductModel::getMaterialType).map(MaterialType::getId).orElse(null);
                    if (materialTypeId != null) {
                        productionOrders = dao.findByMaterialTypeId(materialTypeId, DateUtil.toDate(new Date(), DateUtil.longFormat), orderType, field2);
                    }
                }
            } else {
                productionOrders = dao.findByProductModelCodeV2(planMaterialCode, DateUtil.toDate(new Date(), DateUtil.longFormat), orderType, field2);
                if (productionOrders.size() == 0) {
                    Integer materialTypeId = Optional.ofNullable(productModelService.findByCode(planMaterialCode)).map(ProductModel::getMaterialType).map(MaterialType::getId).orElse(null);
                    if (materialTypeId != null) {
                        productionOrders = dao.findByMaterialTypeIdV2(materialTypeId, DateUtil.toDate(new Date(), DateUtil.longFormat), orderType, field2);
                    }
                }
            }
//            if (productionOrders.size() == 0) {
//                ProductModel productModel = productModelService.findByCode(planMaterialCode);
//                if (productModel != null) {
//                    if (checkoutName != null && checkoutName.contains("复检")) {
//                        productionOrders = dao.findByMaterialTypeId(productModel.getMaterialType().getId(), DateUtil.toDate(new Date(), DateUtil.longFormat), orderType, field2);
//                    } else {
//                        productionOrders = dao.findByMaterialTypeIdV2(productModel.getMaterialType().getId(), DateUtil.toDate(new Date(), DateUtil.longFormat), orderType, field2);
//                    }
//                }
//            }
            if (productionOrders.size() > 0) {
                List<String> orderNos = new ArrayList<>();
                productionOrders.forEach(productionOrder -> {
                    orderNos.add(productionOrder.getAufnr());
                });
                if (planOrderNo != null && orderNos.contains(planOrderNo)) {
                    return planOrderNo;
                } else {
                    return productionOrders.get(0).getAufnr();
                }
            }
        }
        return null;
    }


    /**
     * 匹配订单编号
     *
     * @param sectionNo
     * @param inspectMap
     * @return
     */
    @Override
    public String matchOrder(String sectionNo, Map<String, Object> inspectMap) {
        //订单类型
        String orderType = NumberUtil.object2String(inspectMap.get("order_type"), null);
        //计划订单类型
        String planOrderType = NumberUtil.object2String(inspectMap.get("plan_order_type"), null);
        //计划订单号
        String planOrderNo = NumberUtil.object2String(inspectMap.get("plan_order_no"), null);
        //检验名称
        String checkoutName = NumberUtil.object2String(inspectMap.get("checkout_name"), null);
        //计划料号
        String planMaterialCode = NumberUtil.object2String(inspectMap.get("plan_material_code"), null);
        //匹配订单编号

        return matchOrder(sectionNo, planMaterialCode, planOrderType, orderType, planOrderNo, checkoutName);
    }

    /**
     * 如果产出时间超出订单计划时间，则返回符合计划时间和加工能力的订单
     * @param oldProductionOrder
     * @param gmtCreate 产出时间
     * @return
     */
    @Override
    public ProductionOrder changeOrder(ProductionOrder oldProductionOrder, Date gmtCreate, String lotNo) {
        String oldFromMark = oldProductionOrder.getFromMark();
        String series;
        String equipCode;
        //追溯改造
        if (com.sw.mes.utils.StringUtils.isNotEmpty(oldFromMark) && oldFromMark.matches("[A-Z]+")) {
            series = lotNo.substring(SectionIndexRangeEnum.炉区号.getBeginIndex(), SectionIndexRangeEnum.炉区号.getEndIndex());
            equipCode = lotNo.substring(SectionIndexRangeEnum.炉区号.getBeginIndex(), SectionIndexRangeEnum.炉台序号.getEndIndex());
        } else {
            series = lotNo.substring(2, 3);
            equipCode = lotNo.substring(2, 6);
        }
        List<String> bySeries = equipmentService.getArea(series);
        String region = bySeries.get(0);
        Integer machineCapacityId = oldProductionOrder.getMachineCapacityId();
        if (oldProductionOrder.getGltrp().getTime() < gmtCreate.getTime()){
            List<ProductionOrder> list = findByMachineCapacityIdAndStatusAndProductionStatusAndGmtCreateTime(machineCapacityId, "REL", true, gmtCreate);
            if (list.size() > 0){
                //查询坩埚高度  34P1972
                //查询研发标识
                Equipment byCode = equipmentService.findByCode(equipCode);
                String height = byCode.getHotHeight().toString().substring(0, 3);
                String rdonlylogo = machineCapacityService.findByEquipmentId(byCode.getId()).getRdonlylogo();
                List<ProductionOrder> orderList = new ArrayList<>();
                if(StringUtils.isBlank(rdonlylogo) && !StringUtils.isBlank(height)){
                    orderList = list.stream().filter(productionOrder -> productionOrder.getAuart().equals("常规") && productionOrder.getAufnr().endsWith(height)).collect(Collectors.toList());
                } else if(!StringUtils.isBlank(height)){
                    orderList = list.stream().filter(productionOrder -> productionOrder.getAuart().equals("研发") && productionOrder.getAufnr().endsWith(height)).collect(Collectors.toList());
                } else {
                    orderList.addAll(list);
                }
                for (ProductionOrder productionOrder : orderList) {
                    //todo:等8月1号规范订单编号YMK开头再切换
                    //暂时YN开头
                    String fromMark = productionOrder.getFromMark();
                    if (StringUtils.isNotEmpty(fromMark) && fromMark.matches("[A-Z]+")) {
                        if ("一车间".equals(productionOrder.getWorkShop()) && "一车间".equals(region)) {
                            return productionOrder;  //超出计划时间，有新的
                        }
                        if ("二车间".equals(productionOrder.getWorkShop()) && "二车间".equals(region)) {
                            return productionOrder;  //超出计划时间，有新的
                        }
                        if ("三车间".equals(productionOrder.getWorkShop()) && "三车间".equals(region)) {
                            return productionOrder;  //超出计划时间，有新的
                        }
                        if ("四车间".equals(productionOrder.getWorkShop()) && "四车间".equals(region)) {
                            return productionOrder;  //超出计划时间，有新的
                        }
                    } else {
                        if ("1".equals(productionOrder.getAufnr().substring(9, 10)) && "一车间".equals(region)) {
                            //超出计划时间，有新的
                            return productionOrder;
                        }
                        if ("2".equals(productionOrder.getAufnr().substring(9, 10)) && "二车间".equals(region)) {
                            return productionOrder;  //超出计划时间，有新的
                        }
                        if ("3".equals(productionOrder.getAufnr().substring(9, 10)) && "三车间".equals(region)) {
                            return productionOrder;  //超出计划时间，有新的
                        }
                        if ("4".equals(productionOrder.getAufnr().substring(9, 10)) && "四车间".equals(region)) {
                            return productionOrder;  //超出计划时间，有新的
                        }
                    }
                }
                return null;
            }else {
                return null;      //超出计划时间，没有新的
            }
        }else {
            return oldProductionOrder; //没超出计划时间
        }
    }

    @Override
    public List<ProductionOrder> findByMachineCapacityIdAndStatusAndProductionStatusAndGmtCreateTime(Integer machineCapacityId, String status, Boolean productionStatus, Date gmtCreate) {
        return dao.findByMachineCapacityIdAndStatusAndProductionStatusAndGmtCreateTime(machineCapacityId, status, productionStatus, gmtCreate);
    }

    @Override
    public List<ProductionOrder> findByProductCodeAndTime(String matnr, Date gstrp, Date gltrp) {
        return dao.findByStatusAndProductCodeAndTime(true, matnr, gstrp, gltrp);
    }

    @Override
    public List<ProductionOrder> findByWorkTypeAndTimeAndStatus(Integer workType, Date gstrp, Date gltrp, String status) {
        return dao.findByWorkTypeAndTimeAndStatus(workType, gstrp, gltrp, status);
    }

    @Override
    public ProductionOrder findByeErpOrderNo(String code) {
        List<ProductionOrder> list = dao.findByErpOrderNo(code);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }


    @Override
    public ProductionOrder findByFbOrderNo(String code) {
        List<ProductionOrder> list = dao.findByFbOrderNo(code);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }



    @Override
    public void handleErpOrder(List<ErpOrderDto> ybErpOrderDto, List<ErpOrderDto> fbErpOrderDto) {
        /**
         *   1、接收订单状态为 3(审核) 的订单用于排产；接收订单状态为 4(关闭) 的订单用于关闭订单，其他状态的订单不接收；如果mes中订单已经关闭，则不处理对应订单数据。
         *   2、如果mes中不存在此订单就接收；
         *   3、如果mes中已存在且已排产，不再更新。
         *   4、如果mes中已存在且未排产，更新数量
         */
        /**
         * 变态的逻辑
         * 拿到圆棒订单号后去字典找对应的方棒订单单号(一对多)，再去找方棒订单的边长和数量，
         * 多少个对应的方棒订单就拆分多少个圆棒订单，圆棒订单边长和数量来自对应的方棒订单
         * 圆棒订单号取erp圆棒订单号加上边长
         */
        StringBuilder sb = new StringBuilder();
        for(ErpOrderDto dto:ybErpOrderDto){
            Integer status = dto.getStatus();
            String mocode = dto.getMocode();
            //从字典表找对应关系
            List<String> fbOderNos = dictionaryItemService.findValuesByThemeValueAndItemName("ybToFbOderList ",mocode);
            if(CollectionUtil.isEmpty(fbOderNos)){
                sb.append("订单号"+dto.getMocode()+"未维护圆方棒订单对应关系; ");
                continue;
            }else{
                for(String fbOderNo:fbOderNos){
                    for(ErpOrderDto dto1:fbErpOrderDto){
                        if (fbOderNo.equals(dto1.getMocode())) {
                            String bc = fbOderNo.substring(SectionIndexRangeEnum.方棒订单号截取边长.getBeginIndex(),SectionIndexRangeEnum.方棒订单号截取边长.getEndIndex());
                            String ybOderNo = mocode + "-" + bc;
                            ProductionOrder oldOder = this.findByAufnr(ybOderNo);
                            BigDecimal num = dto1.getQty();
                            if(3 == status){
                                //新增
                                if(oldOder == null){
                                    StringBuilder sb1 = new StringBuilder();
                                    ProductionOrder order;
                                    try {
                                        order = packageOrder(dto,sb1,num,ybOderNo,bc,fbOderNo);
                                        if (sb1.length() == 0 && order!=null) {
                                            saveOrUpdate(order);
                                        }else{
                                            sb.append(sb1);
                                            break;
                                        }
                                    } catch (Exception e) {
                                        sb.append("订单"+dto.getMocode()+"异常:"+e.getMessage()+"; ");
                                        e.printStackTrace();
                                        break;
                                    }
                                    //如果未排产，更新数量
                                }else{
                                    List<ProductionSchedule> productionSchedules = productionScheduleService.findByOderId(oldOder.getId());
                                    if(CollectionUtil.isEmpty(productionSchedules)){
                                        oldOder.setMenge(num);
                                        saveOrUpdate(oldOder);
                                    }
                                }
                            }else if(4 == status){
                                if(oldOder != null){
                                    oldOder.setStatus("CLOSE");
                                    saveOrUpdate(oldOder);
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }

        //记录异常日志
        if(sb.length() > 0){
            RequestLog log = new RequestLog();
            log.setContent("圆棒订单异常信息:"+sb.toString());
            log.setCreateTime(new Date());
            requestLogService.saveOrUpdate(log);
        }

    }

    private ProductionOrder packageOrder(ErpOrderDto dto,StringBuilder sb,BigDecimal num,String ybOrderNo,String bc,String fbOrderNo) {
        ProductionOrder order = new ProductionOrder();
        order.setTid(dto.getMoid() == null ? null : dto.getMoid().toString());
        order.setAufnr(ybOrderNo);
        order.setErpOrderNo(dto.getMocode());
        order.setFbOrderNo(fbOrderNo);
        String type = dto.getMocode().substring(SectionIndexRangeEnum.订单类型.getBeginIndex(),SectionIndexRangeEnum.订单类型.getEndIndex());

        if("A".equals(type)){
            order.setAuart("研发");
        }else if("B".equals(type)){
            order.setAuart("实验");
        }else if("C".equals(type)){
            order.setAuart("常规");
        }
        order.setMatnr(dto.getInvcode());
        order.setModid(dto.getModid() == null ? null : dto.getModid().toString());
        order.setMenge(num);
        order.setAprio("1");
        order.setGltrp(dto.getDuedate());
        order.setGstrp(dto.getStartdate());
        order.setCreateDate(new Date());
        order.setStatus("REL");
        String cdepname = dto.getCdepname();
        if(StringUtils.isNotBlank(cdepname) && cdepname.length() > SectionIndexRangeEnum.车间.getEndIndex()) {
            String workShop = cdepname.substring(SectionIndexRangeEnum.车间.getBeginIndex(), SectionIndexRangeEnum.车间.getEndIndex());
            //车间
            order.setField1(workShop);
            order.setWorkShop(workShop);
        }
        //溯源标识
        String fromMark = dto.getMocode().substring(SectionIndexRangeEnum.订单溯源标识.getBeginIndex(),SectionIndexRangeEnum.订单溯源标识.getEndIndex());
        order.setFromMark(fromMark);
        order.setDeptCode(dto.getMdeptcode());
//        String cinvstd = dto.getCinvstd();
        //产品类别
        //如果溯源标识为 D、J，则型号为D、J；其他：则从工单中规格型号（cinvstd），截取第一位 - 转换规则：P转成T，N转成H
//        String productType = null;
//        if(StringUtils.isNotBlank(fromMark)) {
//            if ("D".equals(fromMark) || "J".equals(fromMark)) {
//                productType = fromMark + fromMark;
//            } else if(StringUtils.isNotBlank(cinvstd)){
//                String type1 = cinvstd.substring(SectionIndexRangeEnum.规格型号截取类型.getBeginIndex(),SectionIndexRangeEnum.规格型号截取类型.getEndIndex());
//                if("P".equals(type1)){
//                    type1 = "T";
//                }else if("N".equals(type1)){
//                    type1 = "H";
//                }
//                productType = fromMark + type1;
//            }
//        }
//        order.setField2(productType);
//        order.setProductType(productType);
        //产品信息
        ProductModel productModel = productModelService.findByCode(dto.getInvcode());
        if(productModel != null){
            order.setProductModel(productModel);
            MachineCapacityInfo machineCapacityInfo = machineCapacityInfoService.getMachineCapacityInfo(productModel.getConductionType(), productModel.getSpecs(), productModel.getDopant());
            if(machineCapacityInfo != null ){
                order.setMachineCapacityId(machineCapacityInfo.getId());
            }else{
                sb.append("订单"+dto.getMocode()+"的"+dto.getInvcode()+"未匹配到设备加工能力; ");
                return null;
            }
        }else{
            sb.append("订单"+dto.getMocode()+"的"+dto.getInvcode()+"未匹配到产品模型; ");
            return null;
        }
        order.setProductionStatus(false);
        order.setRdonlylogo(dto.getCitemcode());
        order.setBaseMark("Y");
//        String [] parts = cinvstd.split(",|，");
//        if(parts.length>1) {
//            order.setResistanceType(parts[1]);
//        }
        order.setSideLengthRange(bc);
        return order;
    }

	@Override
	public ProductionOrder findByAufnrAndMatnr(String code,String matnr) {
		List<ProductionOrder> list = dao.findByAufnrAndMatnr(code,matnr);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
	}

    /**
     * 查询 定向标识以及车间转换后的号码
     *
     * @param aufnr
     * @return
     */
    @Override
    public Map<String, String> getWorkShopValue(String aufnr) {

        HashMap<String, String> hashMap = new HashMap<>();
        ProductionOrder productionOrder = this.findByAufnr(aufnr);
        //成本中心
        String kostl = "";
        //车间:例如:一车间
        String workShop = "";
        //车间编码名称:例如SXLJ1
        String workShopName = "";
        //车间转换前的值
        String workShopBeforeValue = "";
        //车间转换后的值
        String workShopValue = "";
        //片区
        String field4 = "";
        //定向标识
        String directionalSign = "";
        //定向标识转换值
        String directionalSignValue = "";
        if (null == productionOrder) {
            throw new RuntimeException("工单:" + aufnr + "查询异常!");
        } else {
            kostl = String.valueOf(productionOrder.getWorkType());
            field4 = productionOrder.getField4();
            directionalSign = productionOrder.getZorientationind();
        }
        if (StringUtils.isBlank(directionalSign)) {
            directionalSign = "非定向";
        }
        DictionaryItem warehouseLocationResult = dictionaryItemService.findNameByThemeValueAndItemValue("WarehouseLocation", field4);
        if (null != warehouseLocationResult) {
            workShopName = warehouseLocationResult.getName();
        } else {
            throw new BusinessException("详情: 关键字[WarehouseLocation]中的[工作中心编码]: " + field4 + " 未配置");
        }
        //通过workShopName查找车间模型车间号
        FactoryModel factoryModel = factoryModelService.findNameByCodeAndTypeName(workShopName, "区域/车间");
        if (null == factoryModel) {
            throw new BusinessException("该工厂模型[区域/车间]不存在code为:[" + workShopName + " ]配置值");
        }
        workShop = factoryModel.getName();
        switch (workShop) {
            case "一车间":
                workShopBeforeValue = "1";
                break;
            case "二车间":
                workShopBeforeValue = "2";
                break;
            case "三车间":
                workShopBeforeValue = "3";
                break;
            case "四车间":
                workShopBeforeValue = "4";
                break;
            case "五车间":
                workShopBeforeValue = "5";
                break;
            case "六车间":
                workShopBeforeValue = "6";
                break;
            case "七车间":
                workShopBeforeValue = "7";
                break;
            case "八车间":
                workShopBeforeValue = "8";
                break;
        }
        DictionaryItem dictionaryItemDtoResult = dictionaryItemService.findFirstValueByThemeValueAndEnableAndItemValueAndItemExtendValue("SapFabCode", true, kostl, workShopBeforeValue);

        if (null != dictionaryItemDtoResult) {
            workShopValue = dictionaryItemDtoResult.getExtendValue1();
        } else {
            throw new BusinessException("字典关键字[SapFabCode]词条:成本中心代码[" + kostl + "]车间:[" + workShopValue + "未配置完整!");
        }

        DictionaryItem directionalSignValueResult = dictionaryItemService.findByThemeValueAndNameAndEnable("creatCrystalNo", directionalSign, true);
        if (null != directionalSignValueResult) {
            if (directionalSignValueResult.getValue().length() > 1) {
                throw new BusinessException("字典关键字[creatCrystalNo]词条:实际值 [" + directionalSign + "配置值异常,必须一位字符!");
            }
            directionalSignValue = directionalSignValueResult.getValue();
        } else {
            throw new BusinessException("字典关键字[creatCrystalNo]词条:实际值 [" + directionalSign + "未配置!");
        }

        if (StringUtils.isBlank(workShopValue)) {
            throw new BusinessException("请检查车间维护值!");
        }
        if (StringUtils.isBlank(directionalSignValue)) {
            throw new BusinessException("请检查定向标识值!");
        }
        hashMap.put("kostl", kostl);
        hashMap.put("workShopValue", workShopValue);
        hashMap.put("directionalSign", directionalSign);
        hashMap.put("directionalSignValue", directionalSignValue);
        return hashMap;
    }

    @Override
    public List<Map<String, Object>> findByWorkOrderMarginMonitor() {
        return dao.findByWorkOrderMarginMonitor();
    }

    @Override
    public List<ProductionOrder> findByAufnrs(List<String> aufnrs) {
        return dao.findByAufnrs(aufnrs);
    }

    /**
     * 根据工作类型、状态和副产品工单号(包含的定向标识)获取生产订单列表。
     *
     * @param workType 工作类型
     * @param status 状态
     * @param byProductAufnr 副产品工单号
     * @return 符合条件的生产订单列表
     * @throws BusinessException 如果指定的副产品工单不存在，则抛出业务异常
     */
    @Override
    public List<ProductionOrder> getListByWorkTypeAndAufnr(String workType, String status, String byProductAufnr) {
        ProductionOrder byProductionOrder = this.findByAufnr(byProductAufnr);
        if (null == byProductionOrder) {
            throw new BusinessException("副产品工单" + byProductAufnr + "不存在!");
        }
        //副产品产出工单定向标识
        String zorientationind = byProductionOrder.getZorientationind();
        //硅料主产品工单
        List<ProductionOrder> productionOrders = dao.findByWorkTypeAndZorientationind(workType, status);
        //返回数据
        List<ProductionOrder> cleanProductionOrders = new ArrayList<>();
        if (null != productionOrders && productionOrders.size() > 0) {
            for (ProductionOrder productionOrder : productionOrders) {
                if (StringUtils.isBlank(zorientationind)) {
                    //非定向特殊处理
                    if (StringUtils.isBlank(productionOrder.getZorientationind()) || productionOrder.getZorientationind().equals("非定向")) {
                        cleanProductionOrders.add(productionOrder);
                    }
                } else {
                    if (zorientationind.equals(productionOrder.getZorientationind())) {
                        cleanProductionOrders.add(productionOrder);
                    }
                }
            }
        }
        return cleanProductionOrders;
    }
}
