public without sharing class LexSaleOrderController {
  public static boolean isRunning = false;
  public static String barcode { get; set; }
  public static Consumable_order__c coc { get; set; }
  public static List<ConsumableorderdetailsInfo> consumableorderdetailsRecords {
    get;
    set;
  }
  @AuraEnabled
  public static List<Consumable_order_details2__c> consumableorderdetails2Nobox {
    get;
    set;
  }
  @AuraEnabled
  public static List<ConsumableorderdetailsInfo> consumableorderdetailsRecordserror {
    get;
    set;
  }
  public static Map<String, String> existIdMap { get; set; }
  public static Map<String, String> errorIdMap { get; set; }
  public static Map<String, String> allMap { get; set; }
  public static Map<String, String> orderpieceorboxMap { get; set; }
  public static Map<String, Decimal> orderpriceMap { get; set; }
  public static Map<String, Decimal> orderagencypriceMap { get; set; }
  public static Map<String, Decimal> orderdetCountMap { get; set; }
  public static Map<String, Integer> BarcodeCntMap { get; set; }
  public static String baseUrl { get; private set; }
  public static String ESetId { get; set; }
  public static String accountName { get; set; }
  public static String userWorkLocation { get; set; }
  public static Boolean hasSpecialHos { get; set; }
  public static Map<String, Integer> msiMap { get; set; }
  public static List<Consumable_orderdetails__c> orderdetails { get; set; }
  public static String accountid { get; set; }

  @AuraEnabled
  public static ResponseBodyLWC GoodsDeliveryInit(String ESetId) {
    System.debug('LexSaleOrderController GoodsDeliveryInit');
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;

    String UserName = UserInfo.getUserId();
    user useracc = [
      SELECT Accountid, Work_Location__c
      FROM user
      WHERE id = :UserName
    ];
    accountid = useracc.Accountid;
    userWorkLocation = useracc.Work_Location__c;
    Account accountInfo = [SELECT Name FROM account WHERE id = :accountid];
    accountName = accountInfo.Name;
    consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
    consumableorderdetailsRecordserror = new List<ConsumableorderdetailsInfo>();
    coc = new Consumable_order__c();
    List<Consumable_order_details2__c> arriveDat = new List<Consumable_order_details2__c>();
    orderpieceorboxMap = new Map<String, String>();
    orderdetails = new List<Consumable_orderdetails__c>();
    orderagencypriceMap = new Map<String, Decimal>();
    orderpriceMap = new Map<String, Decimal>();
    orderdetCountMap = new Map<String, Decimal>();
    if (String.isNotBlank(ESetId)) {
      coc = [
        SELECT
          Id,
          Name,
          NoConfirmedPrice__c,
          Order_ForDealer__r.Name,
          Summons_Order_type__c,
          Order_status__c,
          Dealer_Info__c,
          Dealer_Info__r.Name,
          SummonsStatus_c__c,
          Deliver_date__c,
          Order_Reason__c,
          Order_date__c,
          Order_ForHospital__c,
          SummonsForDirction__c,
          Arrive_Order__c,
          Arrive_Order__r.IsShipment__c,
          Outbound_Date__c,
          Billed_Status__c,
          ShipmentAccount__c,
          Order_ForCustomerText__c,
          OutPattern__c
        FROM Consumable_order__c
        WHERE Id = :ESetId
      ];
      // update end by vivek 2019-7-16
      if (coc.Arrive_Order__c != null) {
        arriveDat = [
          SELECT
            Id,
            Name,
            recordtypeid,
            Used_account__c,
            Product_Pattern__c,
            Consumable_Product__r.Name,
            Sterilization_limit__c,
            Deliver_date__c,
            Bar_Code__c,
            Arrive_date__c,
            Send_Date__c,
            Consumable_order_minor__r.Name,
            Consumable_order_minor__c,
            Intra_Trade_List_RMB__c,
            Asset_Model_No__c,
            Isoverdue__c,
            Guarantee_period_for_products__c,
            Box_Piece__c,
            // gzw add 20210308 报错修复
            hospitalSpecialOffer__c
          FROM Consumable_order_details2__c
          WHERE Consumable_ZS_order__c = :ESetId
        ];
        for (Integer j = 0; j < arriveDat.size(); j++) {
          consumableorderdetailsRecords.add(
            new ConsumableorderdetailsInfo(arriveDat[j])
          );
        }
      }

      orderdetails = [
        SELECT
          Id,
          Name,
          Product_Pattern__c,
          Consumable_product__r.Name,
          Shipment_Count__c,
          Box_Piece__c,
          Delivery_List_RMB__c,
          Unitprice_To_agency__c,
          isOutPattern__c
        FROM Consumable_orderdetails__c
        WHERE
          Consumable_order__c = :ESetId
          AND Order_Owner_WorkLocal__c = :userWorkLocation
      ];

      for (Integer i = 0; i < orderdetails.size(); i++) {
        orderpieceorboxMap.put(
          orderdetails[i].Product_Pattern__c,
          orderdetails[i].Box_Piece__c
        );
        if (
          orderdetails[i].Unitprice_To_agency__c != null &&
          orderdetails[i].Unitprice_To_agency__c != 0
        ) {
          orderagencypriceMap.put(
            orderdetails[i].Product_Pattern__c,
            orderdetails[i].Unitprice_To_agency__c
          );
        }
        orderpriceMap.put(
          orderdetails[i].Product_Pattern__c,
          orderdetails[i].Delivery_List_RMB__c
        );
        orderdetCountMap.put(
          orderdetails[i].Product_Pattern__c,
          orderdetails[i].Shipment_Count__c
        );
      }
      List<hospitalprice__c> hlist = [
        SELECT id
        FROM hospitalprice__c
        WHERE hospital__c = :coc.ShipmentAccount__c AND account__c = :accountid
      ];
      if (hlist == null || hlist.size() == 0) {
        hasSpecialHos = false;
      } else {
        hasSpecialHos = true;
      }
    }
    data.put('consumableorderdetailsRecords', consumableorderdetailsRecords);
    data.put(
      'consumableorderdetailsRecordserror',
      consumableorderdetailsRecordserror
    );
    data.put('coc', coc);
    data.put('accountName', accountName);
    data.put('userWorkLocation', userWorkLocation);
    data.put('accountid', accountid);
    data.put('orderdetails', orderdetails);
    data.put('orderpieceorboxMap', orderpieceorboxMap);
    data.put('orderpriceMap', orderpriceMap);
    data.put('orderagencypriceMap', orderagencypriceMap);
    res.status = 'Success';
    res.code = 200;
    System.debug('res = ' + res);
    return res;
  }

  @AuraEnabled
  public static ResponseBodyLWC SearchPro(
    Consumable_order__c cocLwc,
    String barcodeLwc,
    String accountName,
    String userWorkLocation,
    String accountid,
    List<Consumable_orderdetails__c> orderdetails,
    Map<String, String> orderpieceorboxMap
  ) {
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;
    coc = cocLwc;
    orderdetails = orderdetails;
    barcode = barcodeLwc;
    accountName = accountName;
    userWorkLocation = userWorkLocation;
    accountid = accountid;
    orderdetails = orderdetails;
    orderpieceorboxMap = orderpieceorboxMap;
    //判断是否和订单联动
    if (coc.Arrive_Order__c != null) {
      //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'无需到货确认，请直接出库。'));
      //    return;
      return new ResponseBodyLWC('Error', 500, '无需到货确认，请直接出库', '');
    }
    //判断barcode是否为空
    if (barcode == null || barcode == '') {
      //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'请输BarCode号。'));
      //    return;
      return new ResponseBodyLWC('Error', 500, '请输BarCode号', '');
    }
    list<String> exitlist = new List<String>();
    list<String> notexitlist = new List<String>();
    existIdMap = new Map<String, String>();
    errorIdMap = new Map<String, String>();
    allMap = new Map<String, String>();
    consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
    consumableorderdetailsRecordserror = new List<ConsumableorderdetailsInfo>();
    List<String> barCodeListP = new List<String>();
    List<Consumable_order_details2__c> reSet = new List<Consumable_order_details2__c>();
    List<Consumable_order_details2__c> reSet1 = new List<Consumable_order_details2__c>();

    //BarCodelist做成
    barCodeListP = ParseBarCode(barcode);
    System.debug('barCodeListP:' + barCodeListP);
    //针对所有商品到货确认
    reSet1 = [
      SELECT
        Id,
        Name,
        recordtypeid,
        Used_account__c,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        Intra_Trade_List_RMB__c,
        Asset_Model_No__c,
        Isoverdue__c,
        Box_Piece__c,
        ProductPacking_list_manual__c,
        Guarantee_period_for_products__c,
        hospitalSpecialOffer__c,
        exchangeOutPattern__c
      FROM Consumable_order_details2__c
      WHERE
        Dealer_Arrive__c = TRUE
        AND Dealer_Returned__c = FALSE
        AND Bar_Code__c != NULL
        AND Dealer_Info_text__c = :accountName
        AND Bar_Code__c IN :barCodeListP
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
      ORDER BY RemoveBox_No__c DESC
    ];
    System.debug('reSet1:' + reSet1);
    List<Consumable_order_details2__c> newdet2 = new List<Consumable_order_details2__c>();
    Set<Id> proIds = new Set<Id>();

    for (String barcode : barCodeListP) {
      Integer idx = 0;
      for (Consumable_order_details2__c cod2 : reSet1) {
        if (cod2.Bar_Code__c == barcode) {
          System.debug('cod2.Bar_Code__c:' + cod2.Bar_Code__c);
          newdet2.add(cod2);
          reSet1.remove(idx);
          proIds.add(cod2.Consumable_product__c);
          break;
        }
        idx++;
      }
    }
    Map<String, String> proHosMap = new Map<String, String>();
    Map<String, String> proIdMap = new Map<String, String>();
    List<hospitalprice__c> hpList = [
      SELECT id, hospital__c, product__c
      FROM hospitalprice__c
      WHERE account__c = :accountid
    ];
    if (hpList != null && hpList.size() > 0) {
      for (hospitalprice__c hp : hpList) {
        if (
          hp.product__c != null &&
          String.valueof(hp.product__c).length() >= 15
        ) {
          proIdMap.put(('' + hp.product__c).subString(0, 15) + '是', '');
          if (hp.hospital__c == coc.Order_ForHospital__c) {
            proHosMap.put(('' + hp.product__c).subString(0, 15) + '是', '');
          }
        }
      }
    }
    for (Integer i = 0; i < orderdetails.size(); i++) {
      for (Integer j = 0; j < newdet2.size(); j++) {
        if (
          newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c &&
          newdet2[j].Box_Piece__c != orderdetails[i].Box_Piece__c
        ) {
          String str = '该商品出货单位错误';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(newdet2[j], str)
          );
          errorIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
        }
        if (coc.OutPattern__c == true) {
          System.debug(
            'testPattern:' +
              newdet2[j].Product_Pattern__c +
              '---' +
              orderdetails[i].Product_Pattern__c
          );
          if (
            newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c
          ) {
            //add by rentx 2021-03-22 start
            if (newdet2[j].exchangeOutPattern__c == true) {
              //如果当前经销商下没有维护对应的特价产品 报错
              if (!proIdMap.containsKey(newdet2[j].Product_Pattern__c)) {
                String str = '没有维护该产品的特价医院';
                consumableorderdetailsRecordserror.add(
                  new ConsumableorderdetailsInfo(newdet2[j], str)
                );
                errorIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
              }
            }
            //add by rentx 2021-03-22 end

            if (hpList != null && hpList.size() > 0) {
              if (proHosMap.containsKey(newdet2[j].Product_Pattern__c)) {
                continue;
              } else if (!proIdMap.containsKey(newdet2[j].Product_Pattern__c)) {
                continue;
              } else {
                String str = '该商品出库医院错误';
                consumableorderdetailsRecordserror.add(
                  new ConsumableorderdetailsInfo(newdet2[j], str)
                );
                errorIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
              }
            }
          }
        }
      }
    }

    //管理编码为空时，报错
    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        Arrive_Owner_Work_Location__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Bar_Code__c IN :barCodeListP
        AND Bar_Code__c != NULL
        AND Dealer_Arrive__c = TRUE
        AND Dealer_Info_text__c = :accountName
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
        AND (TracingCode__c = NULL
        OR TracingCode__c = '')
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          String str = '该产品没有管理编码，无法出库，请与特约经销商管理部人员联系，修正数据';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }
    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        Arrive_Owner_Work_Location__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Bar_Code__c IN :barCodeListP
        AND Bar_Code__c != NULL
        AND Dealer_Arrive__c = TRUE
        AND Dealer_Info_text__c = :accountName
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
        AND Cancellation_Flag__c = TRUE
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          String str = '该商品已经取消';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }

    //不是本出库单的出库产品
    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        Arrive_Owner_Work_Location__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Bar_Code__c IN :barCodeListP
        AND Bar_Code__c != NULL
        AND Dealer_Arrive__c = TRUE
        AND Dealer_Info_text__c = :accountName
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else if (
          !orderpieceorboxMap.containsKey(reSet1[i].Product_Pattern__c)
        ) {
          String str = '不是本出库单的出库产品';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }

    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        Dealer_Info_text__c,
        Arrive_Owner_Work_Location__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Bar_Code__c IN :barCodeListP
        AND Bar_Code__c != NULL
        AND Dealer_Arrive__c = TRUE
        AND ((Dealer_Info_text__c = :accountName
        AND Arrive_Owner_Work_Location__c != :userWorkLocation)
        OR Dealer_Info_text__c != :accountName)
        AND Cancellation_Flag__c = FALSE
        AND Dealer_Shipment__c = FALSE
        AND Dealer_Saled__c = FALSE
        AND Lose_Flag__c = FALSE
        AND Dealer_Returned__c = FALSE
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          // 当前经销商是否存在此产品判断
          boolean containsFlg = false;
          for (Consumable_order_details2__c cod2 : newdet2) {
            if (cod2.Bar_Code__c == reSet1[i].Bar_Code__c) {
              containsFlg = true;
              break;
            }
          }
          if (containsFlg == false) {
            String str =
              '该商品是' +
              reSet1[i].Arrive_Owner_Work_Location__c +
              '的库存';
            if (reSet1[i].Dealer_Info_text__c != accountName) {
              str = '该商品在其他经销商库存';
            }
            consumableorderdetailsRecordserror.add(
              new ConsumableorderdetailsInfo(reSet1[i], str)
            );
            errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
          }
        }
      }
    }

    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Dealer_Saled__c = TRUE
        AND Box_Piece__c = '盒'
        AND Dealer_Info_text__c = :accountName
        AND Dealer_Returned__c = FALSE
        AND Bar_Code__c IN :barCodeListP
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          String str = '该商品已经销售';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }
    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Dealer_Shipment__c = TRUE
        AND Box_Piece__c = '盒'
        AND Dealer_Info_text__c = :accountName
        AND Dealer_Returned__c = FALSE
        AND Bar_Code__c IN :barCodeListP
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          String str = '该商品已经出库';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }
    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Lose_Flag__c = TRUE
        AND Box_Piece__c = '盒'
        AND Dealer_Info_text__c = :accountName
        AND Bar_Code__c IN :barCodeListP
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          String str = '该商品已经丢失';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }
    reSet = [
      SELECT
        Id,
        Name,
        recordtypeid,
        Used_account__c,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        Consumable_order_minor__r.Arrive_Order__c,
        Intra_Trade_List_RMB__c,
        Asset_Model_No__c,
        Isoverdue__c,
        Box_Piece__c,
        ProductPacking_list_manual__c,
        Guarantee_period_for_products__c,
        TracingCode__c,
        Transfer_Time__c,
        Frist_Transfer_Agency__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Dealer_Arrive__c = TRUE
        AND Dealer_Shipment__c = FALSE
        AND Dealer_Saled__c = FALSE
        AND Lose_Flag__c = FALSE
        AND Dealer_Returned__c = FALSE
        AND Bar_Code__c != NULL
        AND Dealer_Info_text__c = :accountName
        AND Bar_Code__c IN :barCodeListP
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
      ORDER BY RemoveBox_No__c DESC
    ];
    //对应录入barcode数量的检索结果
    newdet2 = new List<Consumable_order_details2__c>();
    for (String barcode : barCodeListP) {
      Integer idx = 0;
      for (Consumable_order_details2__c cod2 : reSet) {
        if (cod2.Bar_Code__c == barcode) {
          newdet2.add(cod2);
          reSet.remove(idx);
          break;
        }
        idx++;
      }
    }
    Map<String, String> checkBarcodeResult = new Map<String, String>();
    for (Integer i = 0; i < orderdetails.size(); i++) {
      Integer a = 0;
      for (Integer j = 0; j < newdet2.size(); j++) {
        if (
          newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c &&
          a < orderdetails[i].Shipment_Count__c
        ) {
          if (
            (existIdMap.containsKey(newdet2[j].Bar_Code__c) &&
            newdet2[j].Bar_Code__c == '盒') ||
            errorIdMap.containsKey(newdet2[j].Bar_Code__c)
          ) {
            // 跳过已经处理的消耗品明细
            continue;
          } else if (newdet2[j].Isoverdue__c == 0) {
            String str = '该商品已经超出减菌有效期的有效范围';
            consumableorderdetailsRecordserror.add(
              new ConsumableorderdetailsInfo(newdet2[j], str)
            );
            errorIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
          } else if (newdet2[j].Box_Piece__c != orderdetails[i].Box_Piece__c) {
            String str = '该商品出货单位错误';
            consumableorderdetailsRecordserror.add(
              new ConsumableorderdetailsInfo(newdet2[j], str)
            );
            errorIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
          } else if (!checkBarcodeResult.containsKey(newdet2[j].Bar_Code__c)) {
            Matcher n = Pattern.compile('[0-9]')
              .matcher(newdet2[j].TracingCode__c);
            if (n.find()) {
              // gzw DB202305352696 入库管理编码验证程序调整 start
              if (newdet2[j].TracingCode__c.length() == 5) {
                String tr = newdet2[j].TracingCode__c;
                String Ctr = tr.substring(tr.length() - 3, tr.length());
                String Btr = tr.substring(tr.length() - 4, tr.length() - 3);
                String Atr = tr.substring(tr.length() - 5, tr.length() - 4);
                if (
                  Pattern.compile('[0-9]').matcher(Atr).find() ||
                  Pattern.compile('[0-9]').matcher(Ctr).find()
                ) {
                  String str = '管理编码有误，请检查条形码数据。';
                  consumableorderdetailsRecordserror.add(
                    new ConsumableorderdetailsInfo(newdet2[j], str)
                  );
                  errorIdMap.put(
                    newdet2[j].Bar_Code__c,
                    newdet2[j].Bar_Code__c
                  );
                  continue;
                }
              }
              // String str = '管理编码中有数字，请与管理员确认是否错误。';
              // consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j], str));
              // errorIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
              // continue;
            }
            checkBarcodeResult.put(
              newdet2[j].Bar_Code__c,
              newdet2[j].Bar_Code__c
            );
            consumableorderdetailsRecords.add(
              new ConsumableorderdetailsInfo(newdet2[j])
            );
            a++;
            existIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
          }
        } else if (
          newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c
        ) {
          if (
            a >= orderdetails[i].Shipment_Count__c &&
            orderdetails[i].Box_Piece__c == '个'
          ) {
            // 跳过超过数量的消耗品明细
            continue;
          } else if (errorIdMap.containsKey(newdet2[j].Bar_Code__c)) {
            // 跳过已经处理的消耗品明细
            continue;
          } else {
            //CHAN-C23BWX update by rentx 2021-04-28 start
            // String str = '该商品超出订货数量';
            String str = '该产品超出出库单产品范围';
            //CHAN-C23BWX update by rentx 2021-04-28 end
            consumableorderdetailsRecordserror.add(
              new ConsumableorderdetailsInfo(newdet2[j], str)
            );
            errorIdMap.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
          }
        }
      }
    }

    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        recordtypeid = :System.Label.RT_ConOrderDetail2_Delivery
        AND Bar_Code__c IN :barCodeListP
        AND Dealer_Arrive__c = FALSE
        AND Dealer_Shipment__c = FALSE
        AND Dealer_Saled__c = FALSE
        AND Lose_Flag__c = FALSE
        AND Bar_Code__c != NULL
        AND Dealer_Info_text__c = :accountName
        AND ((Consumable_order_minor__c != NULL
        AND Consumable_order_minor__r.Order_Owner_WorkLocal__c = :userWorkLocation)
        OR (Consumable_order_minor__c = NULL
        AND Cancellation_Flag__c = FALSE))
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          String str = '该商品未到货确认';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }

    allMap.putAll(errorIdMap);
    allMap.putAll(existIdMap);
    //得到不存在的BarCode
    for (Integer i = 0; i < barCodeListP.size(); i++) {
      if (allMap.containsKey(barCodeListP[i])) {
        continue;
      } else {
        exitlist.add(barCodeListP[i]);
      }
    }
    reSet1 = [
      SELECT
        Id,
        Name,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        recordtypeid,
        Consumable_order_minor__r.Arrive_Order__c,
        Box_Piece__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        (Dealer_Saled__c = TRUE
        OR Dealer_Shipment__c = TRUE)
        AND Dealer_Returned__c = FALSE
        AND Bar_Code__c IN :exitlist
      ORDER BY Name
    ];
    if (reSet1.size() > 0) {
      for (Integer i = 0; i < reSet1.size(); i++) {
        if (
          errorIdMap.containsKey(reSet1[i].Bar_Code__c) ||
          existIdMap.containsKey(reSet1[i].Bar_Code__c)
        ) {
          // 跳过已经处理的消耗品明细
          continue;
        } else {
          String str = '该商品已经出货';
          consumableorderdetailsRecordserror.add(
            new ConsumableorderdetailsInfo(reSet1[i], str)
          );
          errorIdMap.put(reSet1[i].Bar_Code__c, reSet1[i].Bar_Code__c);
        }
      }
    }
    allMap.putAll(errorIdMap);
    for (Integer i = 0; i < barCodeListP.size(); i++) {
      if (allMap.containsKey(barCodeListP[i])) {
        continue;
      } else {
        notexitlist.add(barCodeListP[i]);
      }
    }
    if (notexitlist.size() > 0) {
      //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'BarCode号'+ notexitlist + '不存在。'));
      return new ResponseBodyLWC(
        'Error',
        500,
        'BarCode号' + notexitlist + '不存在。',
        ''
      );
    }
    data.put('consumableorderdetailsRecords', consumableorderdetailsRecords);
    data.put(
      'consumableorderdetailsRecordserror',
      consumableorderdetailsRecordserror
    );
    res.status = 'Success';
    res.code = 200;
    System.debug('res = ' + res);
    return res;
  }

  // 去的页面上的barcode，转换成List
  public static List<String> ParseBarCode(String Code) {
    String[] Cache = new List<String>{};
    Cache = Code.split('\n');
    List<String> Buff = new List<String>();
    for (String A : Cache) {
      A = A.trim();
      Buff.add(A.toUpperCase());
    }
    return Buff;
  }

  // 出货
  @AuraEnabled
  public static ResponseBodyLWC ProdElivery(
    String ESetIdLwc,
    Consumable_order__c cocLwc,
    String barcodeLwc,
    String accountNameLwc,
    String userWorkLocationLwc,
    String consumableorderdetailsRecordsLwc,
    List<Consumable_orderdetails__c> orderdetailsLwc,
    Map<String, Decimal> orderpriceMapLwc,
    Map<String, Decimal> orderagencypriceMapLwc
  ) {
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;
    ESetId = ESetIdLwc;
    coc = cocLwc;
    barcode = barcodeLwc;
    accountName = accountNameLwc;
    userWorkLocation = userWorkLocationLwc;
    consumableorderdetailsRecords = (List<ConsumableorderdetailsInfo>) JSON.deserialize(
      consumableorderdetailsRecordsLwc,
      List<ConsumableorderdetailsInfo>.class
    );
    orderdetails = orderdetailsLwc;
    orderpriceMap = orderpriceMapLwc;
    orderagencypriceMap = orderagencypriceMap;
    BarcodeCntMap = new Map<String, Integer>();
    if (coc.Arrive_Order__r.IsShipment__c == true) {
      // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '订单已经出货'));
      // return null;
      return new ResponseBodyLWC('Error', 500, '订单已经出货', '');
    }

    if (consumableorderdetailsRecords.size() < 1) {
      // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '无出货明细'));
      // return null;
      return new ResponseBodyLWC('Error', 500, '无出货明细', '');
    }

    Getconsumableorderdetails2Nobox();

    for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
      String key = '' + ass.orderdetails2.Bar_Code__c;
      Integer deliverycnt = BarcodeCntMap.get(key);
      if (
        ass.orderdetails2.Box_Piece__c == '个' &&
        (ass.outboundCount == null ||
        String.valueof(ass.outboundCount) == '' ||
        ass.outboundCount <= 0)
      ) {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请输入产品 '+ ass.Prod.Name +' 的出货数量'));
        // return null;
        return new ResponseBodyLWC(
          'Error',
          500,
          '请输入产品 ' + ass.Prod.Name + ' 的出货数量',
          ''
        );
      }
      if (ass.outboundCount > deliverycnt) {
        // ass.orderdetails2.Rrturn_count__c.addError('超出出库数量');
        // return null;
        return new ResponseBodyLWC(
          'Error',
          500,
          ass.orderdetails2.Name + '超出出库数量',
          ''
        );
      }
    }

    for (Integer i = 0; i < orderdetails.size(); i++) {
      Decimal a = 0;
      for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
        if (
          ass.orderdetails2.Product_Pattern__c ==
          orderdetails[i].Product_Pattern__c
        ) {
          a = a + ass.outboundCount;
        }
      }
      // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+a));

      if (a < orderdetails[i].Shipment_Count__c) {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'数量小于出货数量'));
        // return null;
        return new ResponseBodyLWC(
          'Error',
          500,
          '商品' +
            orderdetails[i].Consumable_product__r.Name +
            '数量小于出货数量',
          ''
        );
      } else if (a > orderdetails[i].Shipment_Count__c) {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'超出出货数量'));
        // return null;
        return new ResponseBodyLWC(
          'Error',
          500,
          '商品' + orderdetails[i].Consumable_product__r.Name + '超出出货数量',
          ''
        );
      }
    }
    List<Consumable_order_details2__c> Ins = new List<Consumable_order_details2__c>();
    Savepoint sp = Database.setSavepoint();
    List<Consumable_orderdetails__c> orderdetails1List = [
      SELECT Id, Used_date__c
      FROM Consumable_orderdetails__c
      WHERE Consumable_order__c = :ESetId
    ];
    try {
      if (orderdetails1List.size() > 0) {
        for (Integer i = 0; i < orderdetails1List.size(); i++) {
          orderdetails1List[i]
            .RecordTypeId = System.Label.RT_ConOrderDetail1_Shipment;
          orderdetails1List[i].Used_date__c = Date.today();
        }
        ControllerUtil.updateOrderDetails1Satus(orderdetails1List);
      }
      //coc.Order_type__c = '出货';
      coc.RecordTypeId = System.Label.RT_ConOrder_Shipment;
      // update start by vivek 2019-7-15
      // coc.SummonsStatus_c__c = '已完成';
      if (coc.NoConfirmedPrice__c) {
        coc.SummonsStatus_c__c = '价格未定';
      } else {
        coc.SummonsStatus_c__c = '已完成';
      }
      // update start by vivek 2019-7-15
      coc.Outbound_Date__c = Date.today();
      update coc;
      for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
        if (ass.orderdetails2.Box_Piece__c == '个') {
          Decimal cnt = 1;
          for (
            Consumable_order_details2__c codctmp : consumableorderdetails2Nobox
          ) {
            Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
            if (codctmp.Bar_Code__c == ass.orderdetails2.Bar_Code__c) {
              insDetails.Id = codctmp.Id;
              insDetails.Consumable_Sale_order__c = null;
              insDetails.Consumable_Return_order__c = null;
              insDetails.Consumable_ZS_order__c = ESetId;
              insDetails.Delivery_List_RMB__c = orderpriceMap.get(
                ass.orderdetails2.Product_Pattern__c
              );
              insDetails.Return_date__c = null;
              insDetails.Return_reason__c = null;
              insDetails.Consumable_Shipment_order__c = ESetId;
              insDetails.Send_Date__c = Date.today();
              if (coc.SummonsForDirction__c == '互相调货') {
                insDetails.Transfer_Time__c = ass.orderdetails2.Transfer_Time__c ==
                  null
                  ? 1
                  : ass.orderdetails2.Transfer_Time__c + 1;
                insDetails.Frist_Transfer_Agency__c = ass.orderdetails2.Frist_Transfer_Agency__c ==
                  null
                  ? coc.Dealer_Info__r.Name
                  : ass.orderdetails2.Frist_Transfer_Agency__c;
                insDetails.Agency_Transfer__c = true;
              }
              cnt++;
              Ins.add(insDetails);
              if (cnt > ass.outboundCount)
                break;
            }
          }
        } else {
          Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
          insDetails.Id = ass.orderdetails2.Id;
          insDetails.Consumable_Sale_order__c = null;
          insDetails.Consumable_Return_order__c = null;
          insDetails.Consumable_ZS_order__c = ESetId;
          insDetails.Delivery_List_RMB__c = orderpriceMap.get(
            ass.orderdetails2.Product_Pattern__c
          );
          insDetails.Return_date__c = null;
          insDetails.Return_reason__c = null;
          insDetails.Consumable_Shipment_order__c = ESetId;
          insDetails.Send_Date__c = Date.today();
          if (coc.SummonsForDirction__c == '互相调货') {
            insDetails.Transfer_Time__c = ass.orderdetails2.Transfer_Time__c ==
              null
              ? 1
              : ass.orderdetails2.Transfer_Time__c + 1;
            insDetails.Frist_Transfer_Agency__c = ass.orderdetails2.Frist_Transfer_Agency__c ==
              null
              ? coc.Dealer_Info__r.Name
              : ass.orderdetails2.Frist_Transfer_Agency__c;
            insDetails.Agency_Transfer__c = true;
          }
          Ins.add(insDetails);
        }
      }
      if (Ins.size() > 0) {
        ControllerUtil.updateOrderDetailsSatus(Ins);
      }
      if (coc.Arrive_Order__c != null) {
        Consumable_order__c OrderUps = new Consumable_order__c();
        OrderUps.Id = coc.Arrive_Order__c;
        OrderUps.IsShipment__c = true;
        update OrderUps;
      }
    } catch (Exception ex) {
      Database.rollback(sp);
      return new ResponseBodyLWC('Error', 500, ex.getMessage(), '');
    }
    res.status = 'Success';
    res.code = 200;
    System.debug('res = ' + res);
    return res;
  }

  // 销售
  @AuraEnabled
  public static ResponseBodyLWC ProSale(
    String ESetIdLwc,
    Consumable_order__c cocLwc,
    String barcodeLwc,
    String accountNameLwc,
    String userWorkLocationLwc,
    String consumableorderdetailsRecordsLwc,
    List<Consumable_orderdetails__c> orderdetailsLwc,
    Map<String, Decimal> orderpriceMapLwc,
    Map<String, Decimal> orderagencypriceMapLwc
  ) {
    System.debug('enter ProSale');
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;

    ESetId = ESetIdLwc;
    coc = cocLwc;
    barcode = barcodeLwc;
    accountName = accountNameLwc;
    userWorkLocation = userWorkLocationLwc;
    consumableorderdetailsRecords = (List<ConsumableorderdetailsInfo>) JSON.deserialize(
      consumableorderdetailsRecordsLwc,
      List<ConsumableorderdetailsInfo>.class
    );
    orderdetails = orderdetailsLwc;
    orderpriceMap = orderpriceMapLwc;
    orderagencypriceMap = orderagencypriceMapLwc;
    System.debug('ESetId = ' + ESetId);
    System.debug('coc = ' + coc);
    System.debug('barcode = ' + barcode);
    System.debug('accountName = ' + accountName);
    System.debug('userWorkLocation = ' + userWorkLocation);
    System.debug(
      'consumableorderdetailsRecords = ' + consumableorderdetailsRecords
    );
    System.debug('orderdetails = ' + orderdetails);
    System.debug('orderpriceMap = ' + orderpriceMap);
    System.debug('orderagencypriceMap = ' + orderagencypriceMap);
    BarcodeCntMap = new Map<String, Integer>();

    if (consumableorderdetailsRecords.size() < 1) {
      // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '无销售明细'));
      // return null;
      return new ResponseBodyLWC('Error', 500, '无销售明细', '');
    }
    if (coc.Arrive_Order__r.IsShipment__c == true) {
      // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '订单已经销售'));
      // return null;
      return new ResponseBodyLWC('Error', 500, '订单已经销售', '');
    }
    Getconsumableorderdetails2Nobox();

    System.debug('BarcodeCntMap = ' + BarcodeCntMap);
    for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
      String key = '' + ass.orderdetails2.Bar_Code__c;
      Integer deliverycnt = BarcodeCntMap.get(key);
      if (
        ass.orderdetails2.Box_Piece__c == '个' &&
        (ass.outboundCount == null ||
        String.valueof(ass.outboundCount) == '' ||
        ass.outboundCount <= 0)
      ) {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请输入产品 '+ ass.Prod.Name +' 的出货数量'));
        // return null;
        System.debug(
          'ass.orderdetails2.Box_Piece__c = ' + ass.orderdetails2.Box_Piece__c
        );
        System.debug('ass.outboundCount = ' + ass.outboundCount);
        return new ResponseBodyLWC(
          'Error',
          500,
          '请输入产品 ' + ass.Prod.Name + ' 的出货数量',
          ''
        );
      }
      if (ass.outboundCount > deliverycnt) {
        // ass.orderdetails2.Rrturn_count__c.addError('超出出库数量');
        // return null;
        return new ResponseBodyLWC(
          'Error',
          500,
          ass.orderdetails2.Name + '超出出库数量',
          ''
        );
      }
    }

    for (Integer i = 0; i < orderdetails.size(); i++) {
      Decimal a = 0;
      for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
        if (
          ass.orderdetails2.Product_Pattern__c ==
          orderdetails[i].Product_Pattern__c
        ) {
          a = a + ass.outboundCount;
        }
      }
      if (a < orderdetails[i].Shipment_Count__c) {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'数量小于出货数量'));
        // return null;
        return new ResponseBodyLWC(
          'Error',
          500,
          '商品' +
            orderdetails[i].Consumable_product__r.Name +
            '数量小于出货数量',
          ''
        );
      } else if (a > orderdetails[i].Shipment_Count__c) {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'超出出货数量'));
        // return null;
        return new ResponseBodyLWC(
          'Error',
          500,
          '商品' + orderdetails[i].Consumable_product__r.Name + '超出出货数量',
          ''
        );
      }
    }

    Savepoint sp = Database.setSavepoint();
    List<Consumable_orderdetails__c> orderdetails1List = [
      SELECT Id, Used_date__c
      FROM Consumable_orderdetails__c
      WHERE Consumable_order__c = :ESetId
    ];
    try {
      if (orderdetails1List.size() > 0) {
        for (Integer i = 0; i < orderdetails1List.size(); i++) {
          orderdetails1List[i]
            .RecordTypeId = System.Label.RT_ConOrderDetail1_Sale;
          orderdetails1List[i].Used_date__c = Date.today();
        }
        ControllerUtil.updateOrderDetails1Satus(orderdetails1List);
      }
      //coc.Order_type__c = '销售';
      coc.RecordTypeId = System.Label.RT_ConOrder_Sale;
      // update start by vivek 2019-7-15
      // coc.SummonsStatus_c__c = '已完成';
      if (coc.NoConfirmedPrice__c) {
        coc.SummonsStatus_c__c = '价格未定';
      } else {
        coc.SummonsStatus_c__c = '已完成';
      }
      // update start by vivek 2019-7-15
      coc.Outbound_Date__c = Date.today();
      update coc;
      //销售明细
      List<Consumable_order_details2__c> Ins = new List<Consumable_order_details2__c>();
      for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
        if (ass.orderdetails2.Box_Piece__c == '个') {
          Decimal cnt = 1;
          for (
            Consumable_order_details2__c codctmp : consumableorderdetails2Nobox
          ) {
            Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
            if (codctmp.Bar_Code__c == ass.orderdetails2.Bar_Code__c) {
              insDetails.Id = codctmp.Id;
              insDetails.Consumable_Shipment_order__c = null;
              insDetails.Consumable_Return_order__c = null;
              insDetails.Consumable_ZS_order__c = ESetId;
              insDetails.Return_date__c = null;
              insDetails.Delivery_List_RMB__c = orderpriceMap.get(
                ass.orderdetails2.Product_Pattern__c
              );
              if (
                orderagencypriceMap.containsKey(
                  ass.orderdetails2.Product_Pattern__c
                ) == true
              ) {
                insDetails.Unitprice_To_agency__c = orderagencypriceMap.get(
                  ass.orderdetails2.Product_Pattern__c
                );
              }
              insDetails.Return_reason__c = null;
              insDetails.Used_date__c = Date.today();
              insDetails.Consumable_Sale_order__c = ESetId;
              cnt++;
              Ins.add(insDetails);
              if (cnt > ass.outboundCount)
                break;
            }
          }
        } else {
          Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
          insDetails.Id = ass.orderdetails2.Id;
          insDetails.Consumable_Shipment_order__c = null;
          insDetails.Consumable_Return_order__c = null;
          insDetails.Consumable_ZS_order__c = ESetId;
          insDetails.Return_date__c = null;
          insDetails.Delivery_List_RMB__c = orderpriceMap.get(
            ass.orderdetails2.Product_Pattern__c
          );
          if (
            orderagencypriceMap.containsKey(
              ass.orderdetails2.Product_Pattern__c
            ) == true
          ) {
            insDetails.Unitprice_To_agency__c = orderagencypriceMap.get(
              ass.orderdetails2.Product_Pattern__c
            );
          }
          insDetails.Return_reason__c = null;
          insDetails.Used_date__c = Date.today();
          insDetails.Consumable_Sale_order__c = ESetId;
          Ins.add(insDetails);
        }
      }
      //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'consumableorderdetails2Nobox +++'+consumableorderdetails2Nobox.size()));
      //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Ins +++'+Ins));
      //return null;
      if (Ins.size() > 0) {
        ControllerUtil.updateOrderDetailsSatus(Ins);
      }
      if (coc.Arrive_Order__c != null) {
        Consumable_order__c orderUps = new Consumable_order__c();
        orderUps.Id = coc.Arrive_Order__c;
        orderUps.IsShipment__c = true;
        update orderUps;
      }
    } catch (Exception e) {
      Database.rollback(sp);
      return new ResponseBodyLWC(
        'Error',
        500,
        e.getMessage() + e.getStackTraceString(),
        ''
      );
    }
    res.status = 'Success';
    res.code = 200;
    System.debug('res = ' + res);
    return res;
  }

  public static integer Getconsumableorderdetails2Nobox() {
    if (String.isBlank(barcode)) {
      return 0;
    }
    List<String> barCodeListP = ParseBarCode(barcode);
    consumableorderdetails2Nobox = new List<Consumable_order_details2__c>();
    BarcodeCntMap.clear();
    consumableorderdetails2Nobox = [
      SELECT
        Id,
        Name,
        recordtypeid,
        Used_account__c,
        Product_Pattern__c,
        Consumable_Product__r.Name,
        Sterilization_limit__c,
        Deliver_date__c,
        Bar_Code__c,
        Arrive_date__c,
        Send_Date__c,
        Consumable_order_minor__r.Name,
        Consumable_order_minor__c,
        Intra_Trade_List_RMB__c,
        Asset_Model_No__c,
        Isoverdue__c,
        Box_Piece__c,
        ProductPacking_list_manual__c,
        Guarantee_period_for_products__c,
        hospitalSpecialOffer__c
      FROM Consumable_order_details2__c
      WHERE
        Dealer_Arrive__c = TRUE
        AND Dealer_Shipment__c = FALSE
        AND Dealer_Saled__c = FALSE
        AND Lose_Flag__c = FALSE
        AND Bar_Code__c != NULL
        AND Dealer_Info_text__c = :accountName
        AND Bar_Code__c IN :barCodeListP
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
        AND Box_Piece__c = '个'
      ORDER BY RemoveBox_No__c DESC
    ];

    AggregateResult[] results = [
      SELECT Bar_Code__c, count(Id) recordCount
      FROM Consumable_order_details2__c
      WHERE
        Dealer_Arrive__c = TRUE
        AND Dealer_Shipment__c = FALSE
        AND Dealer_Saled__c = FALSE
        AND Lose_Flag__c = FALSE
        AND Bar_Code__c != NULL
        AND Dealer_Info_text__c = :accountName
        AND Bar_Code__c IN :barCodeListP
        AND Arrive_Owner_Work_Location__c = :userWorkLocation
        AND Box_Piece__c = '个'
      GROUP BY Bar_Code__c
    ];

    for (AggregateResult ar : results) {
      String key = '' + ar.get('Bar_Code__c');
      BarcodeCntMap.put(key, Integer.valueOf(ar.get('recordCount')));
    }
    return consumableorderdetails2Nobox.size();
  }

  @TestVisible
  class ConsumableorderdetailsInfo implements Comparable {
    @AuraEnabled
    public Consumable_orderdetails__c orderdetails1 { get; set; }
    @AuraEnabled
    public Consumable_order_details2__c orderdetails2 { get; set; }
    @AuraEnabled
    public Product2__c Prod { get; set; }
    @AuraEnabled
    public String oldConsumableCount { get; set; }
    @AuraEnabled
    public String ErrorReason { get; set; }
    @AuraEnabled
    public Decimal outboundCount { get; set; }

    public ConsumableorderdetailsInfo(
      Consumable_order_details2__c e,
      string str
    ) {
      orderdetails1 = new Consumable_orderdetails__c();
      orderdetails2 = e;
      Prod = e.Consumable_Product__r;
      oldConsumableCount = e.name;
      ErrorReason = str;
    }

    public ConsumableorderdetailsInfo(Consumable_order_details2__c e) {
      orderdetails1 = new Consumable_orderdetails__c();
      orderdetails2 = e;
      Prod = e.Consumable_Product__r;
      if (e.Box_Piece__c == '盒') {
        outboundCount = 1;
      }
      oldConsumableCount = e.name;
    }

    public ConsumableorderdetailsInfo(Consumable_orderdetails__c e) {
      orderdetails1 = e;
      Prod = e.Consumable_Product__r;
      outboundCount = e.Shipment_Count__c;
    }
    // 排序
    public Integer compareTo(Object compareTo) {
      return null;
    }
  }
}
