public without sharing class LexOutboundorderImportController {
  //经销商产品分类
  public static String agencyProType { get; set; }
  private static String sqlagencyProType;
  public static Blob csvFileBody { get; set; }
  public static string csvAsString { get; set; }
  public static String[] csvFileLines { get; set; }
  public static List<ConsumableorderdetailsInfo> orderRecords { get; set; }
  public static List<String[]> csvRecordStr { get; set; }
  public static Map<String, String> hospitalconMap { get; set; }
  public static Map<String, String> product2conMap { get; set; }
  public static Map<String, String> hospitalSysMap { get; set; }
  public static Map<String, String> secondAgencyMap { get; set; }
  private static String accountid { get; set; }
  private static String accountName { get; set; }
  private static Integer messageCount;
  public static boolean saveFLGbln { get; set; }
  private static List<String> barcodeList { get; set; }
  private static List<String> barcodePieceList { get; set; }
  public static Map<String, Integer> barcodePieceMap { get; set; }
  public static boolean errorflg { get; set; }
  public static String errorMessage { get; set; }
  private static String userWorkLocation { get; set; }
  public static String errorMsg { get; set; }

  @AuraEnabled
  public static ResponseBodyLWC init() {
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;
    messageCount = 0;
    errorflg = false;
    errorMessage = null;
    User useracc = [
      SELECT accountid, Work_Location__c, UserPro_Type__c
      FROM user
      WHERE id = :UserInfo.getUserId()
    ];
    accountid = Useracc.accountid;
    userWorkLocation = Useracc.Work_Location__c;
    agencyProType = Useracc.UserPro_Type__c;
    if (String.isBlank(Useracc.UserPro_Type__c)) {
      agencyProType = 'ET';
    }
    sqlagencyProType = '%' + agencyProType + '%';
    Account accountInfo = [SELECT Name FROM account WHERE id = :accountid];
    accountName = accountInfo.name;

    data.put('accountid', accountid);
    data.put('userWorkLocation', userWorkLocation);
    data.put('agencyProType', agencyProType);
    data.put('accountName', accountName);
    data.put('sqlagencyProType', sqlagencyProType);
    res.status = 'Success';
    res.code = 200;
    res.msg = '';
    System.debug('res:' + res);
    return res;
  }

  @AuraEnabled
  public static ResponseBodyLWC importCSVFile(
    String base64DataLwc,
    String sqlagencyProTypeLwc,
    String userWorkLocationLwc,
    String accountNameLwc
  ) {
    System.debug('enter importCSVFile');
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;

    errorMsg = '';
    sqlagencyProType = sqlagencyProTypeLwc;
    userWorkLocation = userWorkLocationLwc;
    accountName = accountNameLwc;
    String base64Data = EncodingUtil.urlDecode(base64DataLwc, 'UTF-8');
    csvFileBody = EncodingUtil.base64Decode(base64Data);
    product2conMap = new Map<String, String>();

    messageCount = 0;
    errormessage = null;
    saveFLGbln = false;
    csvRecordStr = new List<String[]>();
    barcodeList = new List<String>();
    barcodePieceMap = new Map<String, Integer>();
    barcodePieceList = new List<String>();
    orderRecords = new List<ConsumableorderdetailsInfo>();
    hospitalconMap = new Map<String, String>();
    if (csvFileBody == null) {
      errorflg = true;
      saveFLGbln = true;
      // errormessage = '读取内容为空。';
      return new ResponseBodyLWC('Error', 500, '读取内容为空。', '');
    } else {
      //产品数据查找
      map<string, string> orderNameMap = new Map<string, string>();
      try {
        csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n');
        for (Integer i = 0; i < csvFileLines.size(); i++) {
          string[] csvRecordData = csvFileLines[i].split(',');
          if (String.isNotBlank(csvRecordData[6])) {
            barcodeList.add(csvRecordData[6]);
            if (String.valueOf(csvRecordData[9]) == '个') {
              barcodePieceList.add(csvRecordData[6]);
              barcodePieceMap.put(
                csvRecordData[6],
                Integer.valueOf(csvRecordData[7])
              );
            }
          }
          String[] csvRecordDataStr = new String[13];
          for (Integer j = 0; j < csvRecordData.size(); j++) {
            csvRecordDataStr[j] = csvRecordData[j];
          }
          if (i == 0) {
            csvRecordDataStr[12] = '产品';
          } else {
            csvRecordDataStr[12] = '';
          }
          csvRecordStr.add(csvRecordDataStr);
        }
        Map<String, String> productBarcodeMap = new Map<String, String>();
        List<Consumable_order_details2__c> cOrderDet = [
          SELECT Id, Bar_Code__c, Name, Consumable_Product__c, Box_Piece__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 IN :barcodeList
            AND Product_Type__c LIKE :sqlagencyProType
            AND Arrive_Owner_Work_Location__c = :userWorkLocation
            AND Dealer_Info_text__c = :accountName
        ];
        for (Consumable_order_details2__c pdinfo : cOrderDet) {
          productBarcodeMap.put(
            pdinfo.Bar_Code__c,
            pdinfo.Consumable_Product__c
          );
        }
        for (String[] csvlistStr : csvRecordStr) {
          if (productBarcodeMap.containsKey(csvlistStr[6])) {
            csvlistStr[12] = productBarcodeMap.get(csvlistStr[6]);
          } else {
          }
        }
        //检索存在拆盒产品数量
        Map<String, Integer> exitpieceBarcodeMap = new Map<String, Integer>();
        AggregateResult[] pieceOrderDet = [
          SELECT count(Id) cnt, Bar_Code__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 IN :barcodePieceList
            AND Product_Type__c LIKE :sqlagencyProType
            AND Dealer_Info_text__c = :accountName
            AND Arrive_Owner_Work_Location__c = :userWorkLocation
            AND Box_Piece__c = '个'
          GROUP BY Bar_Code__c
        ];
        for (AggregateResult ar : pieceOrderDet) {
          exitpieceBarcodeMap.put(
            String.valueOf(ar.get('Bar_Code__c')),
            Integer.valueOf(ar.get('cnt'))
          );
        }
        for (String bc : barcodePieceList) {
          if (!exitpieceBarcodeMap.containsKey(bc)) {
            if (messageCount >= 100)
              break;
            // ApexPages.addmessage(
            //     new ApexPages.message(ApexPages.severity.ERROR, 'Barcode ' + bc + ' 不存在或单位错误，请确认。')
            // );
            errorMsg += 'Barcode ' + bc + ' 不存在或单位错误，请确认。<br />';
            saveFLGbln = true;
            messageCount++;
          } else if (
            exitpieceBarcodeMap.containsKey(bc) &&
            exitpieceBarcodeMap.get(bc) < barcodePieceMap.get(bc)
          ) {
            if (messageCount >= 100)
              break;
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'Barcode ' + bc + ' 库存不足，请确认。'));
            errorMsg += 'Barcode ' + bc + ' 库存不足，请确认。<br />';
            saveFLGbln = true;
            messageCount++;
          }
        }
      } catch (Exception e) {
        //ApexPages.addMessages(e);
        errorMsg += e.getMessage() + ' ' + e.getLineNumber() + ';';
        //return new ResponseBodyLWC('Error', 500, e.getMessage()+e.getStackTraceString(), '');
      }
      getorderinfo();
      dataInfoconfim();
      getorderdet2info(csvRecordStr);
      if (saveFLGbln == false) {
        getorderdetinfo(csvRecordStr);
      }
      data.put('orderRecords', orderRecords);
      data.put('saveFLGbln', saveFLGbln);
      data.put('csvRecordStr', csvRecordStr);
      data.put('barcodeList', barcodeList);
      data.put('secondAgencyMap', secondAgencyMap);
      data.put('hospitalSysMap', hospitalSysMap);
      res.status = 'Success';
      res.code = 200;
      res.msg = errorMsg;
      return res;
    }
  }

  public static void getorderinfo() {
    map<string, string> orderNameMap = new Map<string, string>();
    try {
      csvAsString = csvFileBody.toString();
      csvFileLines = csvAsString.split('\n');
      for (Integer i = 1; i < csvFileLines.size(); i++) {
        Consumable_order__c cocObj = new Consumable_order__c();
        string[] csvRecordData = csvFileLines[i].split(',');
        if (orderNameMap.containsKey(csvRecordData[0]))
          continue;
        cocObj.Name = csvRecordData[0];
        if (String.isNotBlank(csvRecordData[1])) {
          cocObj.SummonsForDirction__c = csvRecordData[1];
        } else {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + csvRecordData[0] + '出货目的为空，请确认。')
          // );
          errorMsg +=
            '出库单 ' +
            csvRecordData[0] +
            '出货目的为空，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        }
        cocObj.Order_Attachment__c = csvRecordData[2];
        cocObj.Order_Indication__c = csvRecordData[3];
        cocObj.Order_ForCustomerText__c = csvRecordData[4];
        cocObj.Invoice_Note__c = csvRecordData[5];
        if (String.isBlank(csvRecordData[11])) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cocObj.Name + '的产品中，存在出库日期为空，请确认。')
          // );
          errorMsg +=
            '出库单 ' +
            cocObj.Name +
            '的产品中，存在出库日期为空，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        } else {
          cocObj.Outbound_Date__c = Date.parse(csvRecordData[11].trim());
        }
        if (String.isNotEmpty(csvRecordData[2])) {
          hospitalconMap.put(csvRecordData[2].trim(), csvRecordData[0].trim());
        }
        orderNameMap.put(csvRecordData[0], csvRecordData[0]);
        orderRecords.add(new ConsumableorderdetailsInfo(cocObj));
      }
    } catch (Exception e) {
      //return new ResponseBodyLWC('Error', 500, e.getMessage(), '');
      errorMsg += e.getMessage() + ' ' + e.getLineNumber() + ';';
    }
  }

  public static void dataInfoconfim() {
    //确认医院信息
    hospitalSysMap = new Map<String, String>();
    secondAgencyMap = new Map<String, String>();
    for (ConsumableorderdetailsInfo ass : orderRecords) {
      if (
        (ass.order.SummonsForDirction__c == '销售给二级经销商' ||
        ass.order.SummonsForDirction__c == '直接销售给医院' ||
        ass.order.SummonsForDirction__c == '医院试用') &&
        (String.isBlank(ass.hospitalName) ||
        String.isBlank(ass.hospitalCode) ||
        String.isBlank(ass.order.Order_ForCustomerText__c))
      ) {
        if (messageCount >= 100)
          break;
        // ApexPages.addmessage(
        //     new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name + '医院相关信息不能空，请确认。')
        // );
        errorMsg +=
          '出库单' +
          ass.order.Name +
          '医院相关信息不能空，请确认。<br />';
        messageCount++;
        saveFLGbln = true;
        //return null;
      }
      if (ass.order.SummonsForDirction__c == '销售给二级经销商') {
        if (String.isBlank(ass.agencyName)) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name + '经销商信息不能空，请确认。')
          // );
          errorMsg +=
            '出库单' +
            ass.order.Name +
            '经销商信息不能空，请确认。<br />';
          messageCount++;
          saveFLGbln = true;
        }
      }
      if (ass.order.SummonsForDirction__c == '直接销售给医院') {
        if (String.isNotBlank(ass.agencyName)) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name + '不需要二级经销商，请确认。')
          // );
          errorMsg +=
            '出库单' +
            ass.order.Name +
            '不需要二级经销商，请确认。<br />';
          messageCount++;
          saveFLGbln = true;
        }
      }
      if (ass.order.SummonsForDirction__c == '互相调货') {
        if (String.isBlank(ass.agencyName)) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name + '经销商信息不能空，请确认。')
          // );
          errorMsg +=
            '出库单' +
            ass.order.Name +
            '经销商信息不能空，请确认。<br />';
          messageCount++;
          saveFLGbln = true;
        }
        if (
          String.isNotBlank(ass.hospitalName) ||
          String.isNotBlank(ass.hospitalCode) ||
          String.isNotBlank(ass.order.Order_ForCustomerText__c)
        ) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name + '不需要医院相关信息，请确认。')
          // );
          errorMsg +=
            '出库单' +
            ass.order.Name +
            '不需要医院相关信息，请确认。<br />';
          messageCount++;
          saveFLGbln = true;
        }
      }
    }
    System.debug('accountName = ' + accountName);
    List<Agency_Hospital_Link__c> hospitalInfo = [
      SELECT Hospital__c, Hospital__r.Management_Code__c, Hospital__r.Name
      FROM Agency_Hospital_Link__c
      WHERE Agency__r.Name = :accountName
    ];
    List<Dealer_elationship__c> secondAgencyInfo = [
      SELECT Dealer_subordinate__c, Dealer_subordinate__r.Name
      FROM Dealer_elationship__c
      WHERE Dealer_principal__r.Name = :accountName
    ];
    for (Agency_Hospital_Link__c hpinfo : hospitalInfo) {
      hospitalSysMap.put(
        hpinfo.Hospital__r.Management_Code__c,
        hpinfo.Hospital__c
      );
    }
    for (Dealer_elationship__c safo : secondAgencyInfo) {
      secondAgencyMap.put(
        safo.Dealer_subordinate__r.Name,
        safo.Dealer_subordinate__c
      );
    }
    //出库单信息验证
    System.debug('hospitalconMap = ' + hospitalconMap);
    System.debug('hospitalSysMap = ' + hospitalSysMap);
    for (String widget : hospitalconMap.keySet()) {
      if (!hospitalSysMap.containsKey(widget)) {
        if (messageCount >= 100)
          break;
        // ApexPages.addmessage(
        //     new ApexPages.message(
        //         ApexPages.severity.ERROR,
        //         '出库单 ' +
        //         hospitalconMap.get(widget) +
        //         ' 的医院编码' +
        //         widget +
        //         ' 不存在或者不是本经销商负责的医院，请确认。'
        //     )
        // );
        errorMsg +=
          '出库单 ' +
          hospitalconMap.get(widget) +
          ' 的医院编码' +
          widget +
          ' 不存在或者不是本经销商负责的医院，请确认。<br />';
        saveFLGbln = true;
      }
    }
  }

  public static void getorderdet2info(List<String[]> csvRecordStr) {
    barcodeList = new List<String>();
    try {
      for (Integer i = 1; i < csvRecordStr.size(); i++) {
        Consumable_Order_details2__c cod2Obj = new Consumable_Order_details2__c();
        string[] csvRecordData = csvRecordStr[i];
        cod2Obj.TracingCode__c = csvRecordData[0];
        cod2Obj.Bar_Code__c = csvRecordData[6];
        if (String.isNotBlank(csvRecordData[6])) {
          barcodeList.add(csvRecordData[6]);
        }
        if (String.isBlank(csvRecordData[9])) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(
          //         ApexPages.severity.ERROR,
          //         '出库单 ' +
          //         cod2Obj.TracingCode__c +
          //         '的barcode ' +
          //         cod2Obj.Bar_Code__c +
          //         ' 不存在出库单位，请确认。'
          //     )
          // );
          errorMsg +=
            '出库单 ' +
            cod2Obj.TracingCode__c +
            '的barcode ' +
            cod2Obj.Bar_Code__c +
            ' 不存在出库单位，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        } else if (
          String.valueOf(csvRecordData[9]) != '盒' &&
          String.valueOf(csvRecordData[9]) != '个'
        ) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(
          //         ApexPages.severity.ERROR,
          //         '出库单 ' +
          //         cod2Obj.TracingCode__c +
          //         '的barcode ' +
          //         cod2Obj.Bar_Code__c +
          //         ' 出库单位不正确，请确认。'
          //     )
          // );
          errorMsg +=
            '出库单 ' +
            cod2Obj.TracingCode__c +
            '的barcode ' +
            cod2Obj.Bar_Code__c +
            ' 出库单位不正确，请确认。';
          saveFLGbln = true;
          messageCount++;
        } else {
          cod2Obj.Box_Piece__c = csvRecordData[9];
        }
        if (String.isBlank(csvRecordData[8])) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '产品出货单价为空，请确认。')
          // );
          errorMsg +=
            '出库单 ' +
            cod2Obj.TracingCode__c +
            '产品出货单价为空，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        } else if (String.isNotBlank(csvRecordData[8])) {
          if (
            Decimal.valueOf(csvRecordData[8]) == 0 &&
            (String.valueOf(csvRecordData[1]) == '直接销售给医院' ||
            String.valueOf(csvRecordData[1]) == '销售给二级经销商')
          ) {
            if (messageCount >= 100)
              break;
            // ApexPages.addmessage(
            //     new ApexPages.message(
            //         ApexPages.severity.ERROR,
            //         '出库单 ' +
            //         cod2Obj.TracingCode__c +
            //         '产品出货单价不能为0，请确认。'
            //     )
            // );
            errorMsg +=
              '出库单 ' +
              cod2Obj.TracingCode__c +
              '产品出货单价不能为0，请确认。<br />';
            saveFLGbln = true;
            messageCount++;
          } else {
            cod2Obj.Delivery_List_RMB__c = Decimal.valueOf(csvRecordData[8]);
          }
        }
        if (String.isBlank(csvRecordData[6])) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(
          //         ApexPages.severity.ERROR,
          //         '出库单 ' +
          //         cod2Obj.TracingCode__c +
          //         '的产品中，存在barcode为空，请确认。'
          //     )
          // );
          errorMsg +=
            '出库单 ' +
            cod2Obj.TracingCode__c +
            '的产品中，存在barcode为空，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        } else if (String.isBlank(csvRecordData[12])) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(
          //         ApexPages.severity.ERROR,
          //         '出库单 ' +
          //         cod2Obj.TracingCode__c +
          //         '的barcode ' +
          //         cod2Obj.Bar_Code__c +
          //         ' 不存在或不是在库产品，请确认。'
          //     )
          // );
          errorMsg +=
            '出库单 ' +
            cod2Obj.TracingCode__c +
            '的barcode ' +
            cod2Obj.Bar_Code__c +
            ' 不存在或不是在库产品，请确认。';
          saveFLGbln = true;
          messageCount++;
        }
        cod2Obj.Return_reason__c = csvRecordData[12];
        if (String.isBlank(csvRecordData[11])) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(
          //         ApexPages.severity.ERROR,
          //         '出库单 ' +
          //         cod2Obj.TracingCode__c +
          //         '的产品中，存在出库日期为空，请确认。'
          //     )
          // );
          errorMsg +=
            '出库单 ' +
            cod2Obj.TracingCode__c +
            '的产品中，存在出库日期为空，请确认。';
          saveFLGbln = true;
          messageCount++;
        } else {
          cod2Obj.Send_Date__c = Date.parse(csvRecordData[11].trim());
        }
      }
    } catch (Exception e) {
      //return new ResponseBodyLWC('Error', 500, e.getMessage(), '');
      errorMsg += e.getMessage() + ' ' + e.getLineNumber() + ';';
    }
  }

  public static void getorderdetinfo(List<String[]> csvRecordStr) {
    map<string, string> orderdetMap = new Map<string, string>();
    try {
      for (Integer i = 1; i < csvRecordStr.size(); i++) {
        Consumable_Orderdetails__c codObj = new Consumable_Orderdetails__c();
        string[] csvRecordData = csvRecordStr[i];
        if (orderdetMap.containsKey(csvRecordData[0] + csvRecordData[12]))
          continue;
        codObj.Remarks__c = csvRecordData[0];
        if (String.isBlank(csvRecordData[7])) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + csvRecordData[0] + '产品出货数量为空，请确认。')
          // );
          errorMsg +=
            '出库单 ' +
            csvRecordData[0] +
            '产品出货数量为空，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        } else if (
          Decimal.valueOf(csvRecordData[7]) > 1 &&
          String.valueOf(csvRecordData[9]) == '盒'
        ) {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(
          //         ApexPages.severity.ERROR,
          //         '出库单 ' +
          //         csvRecordData[0] +
          //         '存在单位是盒，产品出货数量大于1，请确认。'
          //     )
          // );
          errorMsg +=
            '出库单 ' +
            csvRecordData[0] +
            '存在单位是盒，产品出货数量大于1，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        } else {
          codObj.Shipment_Count__c = Decimal.valueOf(csvRecordData[7]);
        }
        codObj.Box_Piece__c = csvRecordData[9];
        if (String.isNotBlank(csvRecordData[8])) {
          codObj.Delivery_List_RMB__c = Decimal.valueOf(csvRecordData[8]);
        } else {
          if (messageCount >= 100)
            break;
          // ApexPages.addmessage(
          //     new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + csvRecordData[0] + '产品出货单价为空，请确认。')
          // );
          errorMsg +=
            '出库单 ' +
            csvRecordData[0] +
            '出库单 ' +
            csvRecordData[0] +
            '产品出货单价为空，请确认。<br />';
          saveFLGbln = true;
          messageCount++;
        }
        //if(String.isNotBlank(csvRecordData[10])){
        // codObj.Unitprice_To_agency__c = Decimal.valueOf(csvRecordData[10]);
        //}
        codObj.Lose_reason__c = csvRecordData[12];
        codObj.Used_date__c = Date.parse(csvRecordData[11].trim());
        product2conMap.put(csvRecordData[12].trim(), csvRecordData[12].trim());
        orderdetMap.put(
          csvRecordData[0] + csvRecordData[12],
          csvRecordData[0] + csvRecordData[12]
        );
        //orderdetRecords.add(new ConsumableorderdetailsInfo(codObj));
      }
    } catch (Exception e) {
      //return new ResponseBodyLWC('Error', 500, e.getMessage(), '');
      errorMsg += e.getMessage() + ' ' + e.getLineNumber() + ';';
    }
  }

  @AuraEnabled
  public static ResponseBodyLWC dataImport(
    List<String[]> csvRecordStrLwc,
    String orderRecordsLwc,
    String sqlagencyProTypeLwc,
    String userWorkLocationLwc,
    String accountNameLwc,
    String accountidLwc,
    String agencyProTypeLwc,
    Map<String, String> secondAgencyMapLwc,
    Map<String, String> hospitalSysMapLwc
  ) {
    List<ConsumableorderdetailsInfo> orderdetRecords = new List<ConsumableorderdetailsInfo>();
    List<ConsumableorderdetailsInfo> orderdet2BoxRecords = new List<ConsumableorderdetailsInfo>();
    List<ConsumableorderdetailsInfo> orderdet2PieceRecords = new List<ConsumableorderdetailsInfo>();
    product2conMap = new Map<String, String>();
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;

    csvRecordStr = csvRecordStrLwc;
    orderRecords = (List<ConsumableorderdetailsInfo>) JSON.deserialize(
      orderRecordsLwc,
      List<ConsumableorderdetailsInfo>.class
    );
    System.debug('orderRecords = ' + orderRecords);
    sqlagencyProType = sqlagencyProTypeLwc;
    userWorkLocation = userWorkLocationLwc;
    accountName = accountNameLwc;
    secondAgencyMap = secondAgencyMapLwc;
    hospitalSysMap = hospitalSysMapLwc;
    accountid = accountidLwc;
    agencyProType = agencyProTypeLwc;
    System.debug('agencyProType = ' + agencyProType);

    errorMsg = '';
    System.debug('csvRecordStr = ' + csvRecordStr);
    orderdetRecords = getorderdetList(csvRecordStr);
    orderdet2BoxRecords = getorderdet2BoxList(csvRecordStr);
    orderdet2PieceRecords = getorderdet2pieceList(csvRecordStr);
    System.debug('orderdetRecords = ' + orderdetRecords);
    System.debug('orderdet2BoxRecords = ' + orderdet2BoxRecords);
    System.debug('orderdet2PieceRecords = ' + orderdet2PieceRecords);
    Savepoint sp = Database.setSavepoint();
    try {
      Map<String, String> orderInfoMap = new Map<String, String>();
      List<Consumable_order__c> coc = new List<Consumable_order__c>();
      for (ConsumableorderdetailsInfo ass : orderRecords) {
        ass.order.Order_type__c = '传票';
        ass.order.SummonsStatus_c__c = '已完成';
        ass.order.Order_ProType__c = agencyProType;
        ass.order.Dealer_Info__c = accountid;
        ass.order.Order_ForHospital__c = hospitalSysMap.get(ass.hospitalCode);
        if (secondAgencyMap.containsKey(ass.agencyName)) {
          ass.order.Order_ForDealer__c = secondAgencyMap.get(ass.agencyName);
        } else {
          ass.order.Order_ForDealerText__c = ass.agencyName;
        }
        ass.order.RecordTypeId = System.Label.RT_ConOrder_Sale;
        coc.add(ass.order);
      }
      System.debug('coc = ' + coc);
      if (coc.size() > 0) {
        insert coc;
      }
      for (Consumable_order__c order : coc) {
        orderInfoMap.put(order.Name, order.Id);
      }
      List<Consumable_Orderdetails__c> cod = new List<Consumable_Orderdetails__c>();
      for (String field : orderInfoMap.keySet()) {
        Integer i = 1;
        for (ConsumableorderdetailsInfo ass : orderdetRecords) {
          if (ass.orderName == field) {
            String str = string.valueOf(i);
            if (str.length() == 1) {
              str = '0' + str;
            }
            ass.orderdetails1.Name = ass.orderName + '-' + str;
            ass.orderdetails1.Consumable_order__c = orderInfoMap.get(
              ass.orderName
            );
            ass.orderdetails1.Consumable_Product__c = ass.productName;
            ass.orderdetails1.RecordTypeId = System.Label.RT_ConOrderDetail1_Sale;
            cod.add(ass.orderdetails1);
            i++;
          }
        }
      }
      System.debug('cod = ' + cod);
      if (cod.size() > 0) {
        insert cod;
      }
      //盒的数据检索
      List<Consumable_Order_details2__c> cod2List = new List<Consumable_Order_details2__c>();
      List<Consumable_order_details2__c> cOrderDet = [
        SELECT Id, Bar_Code__c, Name, Consumable_Product__c, Box_Piece__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 IN :barcodeList
          AND Product_Type__c LIKE :sqlagencyProType
          AND Dealer_Info_text__c = :accountName
          AND Arrive_Owner_Work_Location__c = :userWorkLocation
          AND Box_Piece__c = '盒'
      ];
      for (ConsumableorderdetailsInfo ass : orderdet2BoxRecords) {
        Integer idx = 0;
        for (Consumable_order_details2__c codtest : cOrderDet) {
          Consumable_Order_details2__c cod2 = new Consumable_Order_details2__c();
          if (codtest.Bar_Code__c == ass.orderdetails2.Bar_Code__c) {
            cod2 = codtest;
            cod2.Consumable_Sale_order__c = orderInfoMap.get(ass.orderName);
            cod2.Consumable_ZS_order__c = orderInfoMap.get(ass.orderName);
            cod2.Used_date__c = ass.orderdetails2.Used_date__c;
            cod2.Send_Date__c = ass.orderdetails2.Send_Date__c;
            //cod2.Unitprice_To_agency__c = ass.orderdetails2.Unitprice_To_agency__c;
            cod2.Delivery_List_RMB__c = ass.orderdetails2.Delivery_List_RMB__c;
            cod2List.add(cod2);
            cOrderDet.remove(idx);
            break;
          }
          idx++;
        }
      }

      //个的数据检索
      List<Consumable_order_details2__c> cOrderDetPiece = [
        SELECT
          Id,
          Bar_Code__c,
          RemoveBox_No__c,
          Name,
          Consumable_Product__c,
          Box_Piece__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 Arrive_Owner_Work_Location__c = :userWorkLocation
          AND Bar_Code__c IN :barcodePieceList
          AND Product_Type__c LIKE :sqlagencyProType
          AND Dealer_Info_text__c = :accountName
          AND Box_Piece__c = '个'
        ORDER BY Bar_Code__c, RemoveBox_No__c DESC
      ];
      for (ConsumableorderdetailsInfo ass : orderdet2PieceRecords) {
        Decimal idy = 1;
        for (Integer idx = 0; idx < cOrderDetPiece.size(); idx++) {
          Consumable_Order_details2__c cod2 = new Consumable_Order_details2__c();
          if (
            cOrderDetPiece[idx].Bar_Code__c == ass.orderdetails2.Bar_Code__c &&
            idy <= ass.pieceCount
          ) {
            cod2 = cOrderDetPiece[idx].Clone();
            cod2.Id = cOrderDetPiece[idx].Id;
            cod2.Consumable_Sale_order__c = orderInfoMap.get(ass.orderName);
            cod2.Consumable_ZS_order__c = orderInfoMap.get(ass.orderName);
            cod2.Used_date__c = ass.orderdetails2.Used_date__c;
            cod2.Send_Date__c = ass.orderdetails2.Send_Date__c;
            //cod2.Unitprice_To_agency__c = ass.orderdetails2.Unitprice_To_agency__c;
            cod2.Delivery_List_RMB__c = ass.orderdetails2.Delivery_List_RMB__c;
            cod2List.add(cod2);
            cOrderDetPiece[idx].Bar_Code__c = '';
            idy++;
            //break;
          }
        }
      }
      if (cod2List.size() > 0) {
        update cod2List;
      }
      errorflg = true;
      //errorMessage = '保存完成。';
      saveFLGbln = true;

      res.status = 'Success';
      res.code = 200;
      res.msg = errorMsg;
      return res;
    } catch (Exception e) {
      Database.rollback(sp);
      // ApexPages.addMessages(e);
      // return null;
      return new ResponseBodyLWC(
        'Error',
        500,
        e.getMessage() + e.getStackTraceString(),
        ''
      );
    }
  }

  public static List<ConsumableorderdetailsInfo> getorderdetList(
    List<String[]> csvRecordStr
  ) {
    List<ConsumableorderdetailsInfo> orderdetRecords = new List<ConsumableorderdetailsInfo>();
    map<string, Decimal> orderdetMap = new Map<string, Decimal>();
    try {
      for (Integer i = 1; i < csvRecordStr.size(); i++) {
        Consumable_Orderdetails__c codObj = new Consumable_Orderdetails__c();
        string[] csvRecordData = csvRecordStr[i];
        if (
          orderdetMap.containsKey(
            csvRecordData[0] + csvRecordData[12] + csvRecordData[9]
          )
        ) {
          orderdetMap.put(
            csvRecordData[0] + csvRecordData[12] + csvRecordData[9],
            orderdetMap.get(
              csvRecordData[0] + csvRecordData[12] + csvRecordData[9]
            ) + Decimal.valueOf(csvRecordData[7])
          );
          continue;
        } else {
          orderdetMap.put(
            csvRecordData[0] + csvRecordData[12] + csvRecordData[9],
            Decimal.valueOf(csvRecordData[7])
          );
        }
        codObj.Remarks__c = csvRecordData[0];
        codObj.Shipment_Count__c = Decimal.valueOf(csvRecordData[7]);
        codObj.Box_Piece__c = csvRecordData[9];
        if (String.isNotBlank(csvRecordData[8])) {
          codObj.Delivery_List_RMB__c = Decimal.valueOf(csvRecordData[8]);
        }
        codObj.Lose_reason__c = csvRecordData[12];
        if (String.isNotBlank(csvRecordData[11])) {
          codObj.Used_date__c = Date.parse(csvRecordData[11].trim());
        }
        product2conMap.put(csvRecordData[12].trim(), csvRecordData[12].trim());
        orderdetRecords.add(new ConsumableorderdetailsInfo(codObj));
      }
      for (ConsumableorderdetailsInfo ass : orderdetRecords) {
        if (
          orderdetMap.containsKey(
            ass.orderName + ass.productName + ass.orderdetails1.Box_Piece__c
          )
        ) {
          ass.orderdetails1.Shipment_Count__c = orderdetMap.get(
            ass.orderName + ass.productName + ass.orderdetails1.Box_Piece__c
          );
        }
      }
      System.debug('orderdetRecords = ' + orderdetRecords);
      return orderdetRecords;
    } catch (Exception e) {
      // ApexPages.addMessages(e);
      // return null;
      errorMsg += e.getMessage() + ' ' + e.getLineNumber() + ';';
      System.debug('orderdetRecords = null ' + e.getLineNumber());
      return null;
    }
  }

  public static List<ConsumableorderdetailsInfo> getorderdet2BoxList(
    List<String[]> csvRecordStr
  ) {
    barcodeList = new List<String>();
    List<ConsumableorderdetailsInfo> orderdet2BoxRecords = new List<ConsumableorderdetailsInfo>();
    try {
      for (Integer i = 1; i < csvRecordStr.size(); i++) {
        string[] csvRecordData = csvRecordStr[i];
        if (String.valueOf(csvRecordData[9]) == '盒') {
          Consumable_Order_details2__c cod2Obj = new Consumable_Order_details2__c();
          cod2Obj.TracingCode__c = csvRecordData[0];
          cod2Obj.Bar_Code__c = csvRecordData[6];
          if (String.isNotBlank(csvRecordData[6])) {
            barcodeList.add(csvRecordData[6]);
          }
          cod2Obj.Box_Piece__c = csvRecordData[9];
          if (String.isNotBlank(csvRecordData[8])) {
            cod2Obj.Delivery_List_RMB__c = Decimal.valueOf(csvRecordData[8]);
          }
          //if(String.isNotBlank(csvRecordData[10])){
          //  cod2Obj.Unitprice_To_agency__c = Decimal.valueOf(csvRecordData[10]);
          //}
          cod2Obj.Return_reason__c = csvRecordData[12];
          if (
            String.valueOf(csvRecordData[1]) == '销售给二级经销商' ||
            String.valueOf(csvRecordData[1]) == '直接销售给医院'
          ) {
            cod2Obj.Used_date__c = Date.parse(csvRecordData[11].trim());
          } else {
            cod2Obj.Send_Date__c = Date.parse(csvRecordData[11].trim());
          }
          orderdet2BoxRecords.add(new ConsumableorderdetailsInfo(cod2Obj));
        }
      }
      return orderdet2BoxRecords;
    } catch (Exception e) {
      // ApexPages.addMessages(e);
      // return null;
      errorMsg += e.getMessage() + ' ' + e.getLineNumber() + ';';
      return null;
    }
  }

  public static List<ConsumableorderdetailsInfo> getorderdet2pieceList(
    List<String[]> csvRecordStr
  ) {
    barcodePieceList = new List<String>();
    List<ConsumableorderdetailsInfo> orderdet2PieceRecords = new List<ConsumableorderdetailsInfo>();
    try {
      for (Integer i = 1; i < csvRecordStr.size(); i++) {
        string[] csvRecordData = csvRecordStr[i];
        if (String.valueOf(csvRecordData[9]) == '个') {
          Consumable_Order_details2__c cod2Obj = new Consumable_Order_details2__c();
          cod2Obj.TracingCode__c = csvRecordData[0];
          cod2Obj.Bar_Code__c = csvRecordData[6];
          if (String.isNotBlank(csvRecordData[6])) {
            barcodePieceList.add(csvRecordData[6]);
          }
          cod2Obj.Box_Piece__c = csvRecordData[9];
          if (String.isNotBlank(csvRecordData[8])) {
            cod2Obj.Delivery_List_RMB__c = Decimal.valueOf(csvRecordData[8]);
          }
          cod2Obj.Return_reason__c = csvRecordData[12];
          if (
            String.valueOf(csvRecordData[1]) == '销售给二级经销商' ||
            String.valueOf(csvRecordData[1]) == '直接销售给医院'
          ) {
            cod2Obj.Used_date__c = Date.parse(csvRecordData[11].trim());
          } else {
            cod2Obj.Send_Date__c = Date.parse(csvRecordData[11].trim());
          }
          cod2Obj.Rrturn_count__c = Decimal.valueOf(csvRecordData[7]);
          orderdet2PieceRecords.add(new ConsumableorderdetailsInfo(cod2Obj));
        }
      }
      return orderdet2PieceRecords;
    } catch (Exception e) {
      // ApexPages.addMessages(e);
      // return null;
      errorMsg += e.getMessage();
      return null;
    }
  }
  @TestVisible
  class ConsumableorderdetailsInfo implements Comparable {
    @AuraEnabled
    public Consumable_order__c order { get; set; }
    @AuraEnabled
    public Consumable_orderdetails__c orderdetails1 { get; set; }
    @AuraEnabled
    public Consumable_order_details2__c orderdetails2 { get; set; }
    @AuraEnabled
    public String orderName { get; set; }
    @AuraEnabled
    public String hospitalCode { get; set; }
    @AuraEnabled
    public String hospitalName { get; set; }
    @AuraEnabled
    public String agencyName { get; set; }
    @AuraEnabled
    public String productName { get; set; }
    @AuraEnabled
    public Decimal pieceCount { get; set; }
    // 取到的订单信息
    public ConsumableorderdetailsInfo(Consumable_order__c e) {
      order = e;
      hospitalCode = e.Order_Attachment__c;
      hospitalName = e.Order_Indication__c;
      agencyName = e.Invoice_Note__c;
      e.Order_Attachment__c = '';
      e.Order_Indication__c = '';
      e.Invoice_Note__c = '';
    }
    // 取到的订单明细
    public ConsumableorderdetailsInfo(Consumable_orderdetails__c e) {
      orderdetails1 = e;
      orderName = e.Remarks__c;
      productName = e.Lose_reason__c;
      e.Lose_reason__c = '';
      e.Remarks__c = '';
    }
    // 取到的产品明细
    public ConsumableorderdetailsInfo(Consumable_order_details2__c e) {
      orderdetails2 = e;
      orderName = e.TracingCode__c;
      productName = e.Return_reason__c;
      pieceCount = e.Rrturn_count__c;
      e.TracingCode__c = '';
      e.Return_reason__c = '';
      e.Rrturn_count__c = null;
    }
    public Integer compareTo(Object compareTo) {
      return null;
    }
  }
}
