public with sharing class LexConInvoicedetailsController {
  //出库单使用
  public static Consumable_order__c coc { get; set; }

  //发票使用
  public static Consumable_order__c invoicecode { get; set; }

  //价格计算结果
  public static Decimal sumPrice { get; set; }

  //出库单ID
  private static String orderId { get; set; }
  //发票单ID
  private static String invoiceId { get; set; }
  //出库单明细1，画面显示使用
  public static List<ConsumableorderdetailsInfo> consumableorderdetails1Records {
    get;
    set;
  }
  //明细数量
  public static Integer invoiceOrderRecoedsCount {
    get {
      return consumableorderdetails1Records == null
        ? 0
        : consumableorderdetails1Records.size();
    }
  }

  //页面初始化
  @AuraEnabled
  public static ResponseBodyLWC init(String orderIdLwc, String invoiceIdLwc) {
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;

    orderId = orderIdLwc;
    invoiceId = invoiceIdLwc;
    consumableorderdetails1Records = new List<ConsumableorderdetailsInfo>();
    sumPrice = 0;
    coc = new Consumable_order__c();
    //出库单信息
    coc = [
      SELECT Id, Name, Outbound_Date__c, Order_ForDealerText__c, Dealer_Info__c
      FROM Consumable_order__c
      WHERE Id = :orderId
    ];
    //发票信息
    invoicecode = [
      SELECT
        Id,
        Name,
        ShipmentAccount__c,
        Order_ForCustomerText__c,
        Order_ForDealerText__c,
        Dealer_Info__c
      FROM Consumable_order__c
      WHERE Id = :invoiceId
    ];
    //发票明细1
    Map<String, Consumable_Orderdetails__c> invoiceorderdet1CountMap = new Map<String, Consumable_Orderdetails__c>();
    List<Consumable_Orderdetails__c> invoiceorderdetails1 = [
      SELECT
        Id,
        Name,
        Consumable_order__c,
        Asset_Model_No__c,
        Consumable_Product__r.Asset_Model_No__c,
        Consumable_Count__c,
        Shipment_Count__c,
        RrturnPro_count__c,
        Delivery_List_RMB__c,
        InvoicedProCost_RMB__c,
        Invoiced_Procount__c,
        Invoiced_Count__c,
        Invoice_Unitprice__c,
        InvoiceProNot_count__c,
        Invoice_Cost_RMB__c,
        Invoice_No__c,
        Invoice_Unit__c,
        Invoicedet1_OD_link__c
      FROM Consumable_Orderdetails__c
      WHERE
        Consumable_order__c = :invoiceId
        AND Invoicedet1_OD_link__c = :orderId
    ];
    for (Integer i = 0; i < invoiceorderdetails1.size(); i++) {
      invoiceorderdet1CountMap.put(
        invoiceorderdetails1[i].Asset_Model_No__c,
        invoiceorderdetails1[i]
      );
    }
    //出库单明细1，画面显示使用
    List<Consumable_Orderdetails__c> consumableorderdetails1 = [
      SELECT
        Id,
        Name,
        Consumable_order__c,
        Asset_Model_No__c,
        Consumable_Product__r.Asset_Model_No__c,
        Consumable_Count__c,
        Shipment_Count__c,
        RrturnPro_count__c,
        Delivery_List_RMB__c,
        InvoicedProCost_RMB__c,
        Invoiced_Procount__c,
        Invoiced_Count__c,
        Invoice_Unitprice__c,
        InvoiceProNot_count__c,
        Invoice_Cost_RMB__c,
        Invoice_No__c,
        Consumable_Product__c,
        Intra_Trade_List_RMB__c,
        Dealer_Custom_Price__c,
        Sum_of_money__c,
        Used_date__c,
        Send_date__c,
        Box_Piece__c,
        Invoice_Unit__c,
        Consumable_Product__r.Packing_list_manual__c,
        ProductPacking_list_manual__c
      FROM Consumable_Orderdetails__c
      WHERE Consumable_order__c = :orderId
    ];
    System.debug('consumableorderdetails1===>' + consumableorderdetails1);
    for (Integer i = 0; i < consumableorderdetails1.size(); i++) {
      consumableorderdetails1Records.add(
        new ConsumableorderdetailsInfo(consumableorderdetails1[i])
      );
    }
    for (ConsumableorderdetailsInfo ass : consumableorderdetails1Records) {
      if (invoiceorderdet1CountMap.containsKey(ass.esd.Asset_Model_No__c)) {
        ass.check = true;
        if (
          invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c)
            .Invoice_Unit__c == null ||
          invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c)
            .Invoice_Unit__c == ''
        ) {
          ass.esd.Invoice_Unit__c = ass.esd.Box_Piece__c;
        } else {
          ass.esd.Invoice_Unit__c = invoiceorderdet1CountMap.get(
              ass.esd.Asset_Model_No__c
            )
            .Invoice_Unit__c;
        }
        if (
          invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c)
            .Invoiced_Count__c == null ||
          invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c)
            .Invoiced_Count__c == 0
        ) {
          ass.invoiceCount = ass.esd.Invoiced_Count__c;
        } else {
          ass.invoiceCount = invoiceorderdet1CountMap.get(
              ass.esd.Asset_Model_No__c
            )
            .Invoiced_Count__c;
        }

        if (ass.esd.Box_Piece__c == '盒' && ass.esd.Invoice_Unit__c == '个') {
          ass.esd.Invoice_Unitprice__c =
            ass.esd.Delivery_List_RMB__c / ass.Packing_list_manual;
        } else {
          ass.esd.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
        }
        Decimal invoiceAllprice = 0.00;
        invoiceAllprice = (ass.invoiceCount * ass.esd.Invoice_Unitprice__c)
          .setScale(2);
        ass.invoiceAllprice = invoiceAllprice;
      } else {
        ass.invoiceCount = ass.esd.InvoiceProNot_count__c;
        ass.esd.Invoice_Unit__c = ass.esd.Box_Piece__c;
        ass.esd.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
      }
    }
    data.put('invoicecode', invoicecode);
    data.put('coc', coc);
    data.put('consumableorderdetails1Records', consumableorderdetails1Records);
    res.status = 'Success';
    res.code = 200;
    System.debug('res = ' + res);
    return res;
  }

  @AuraEnabled
  public static ResponseBodyLWC save(
    String consumableorderdetails1RecordsLwc,
    String invoiceIdLwc,
    String orderIdLwc
  ) {
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;

    consumableorderdetails1Records = (List<ConsumableorderdetailsInfo>) JSON.deserialize(
      consumableorderdetails1RecordsLwc,
      List<ConsumableorderdetailsInfo>.class
    );
    invoiceId = invoiceIdLwc;
    orderId = orderIdLwc;
    System.debug(
      'consumableorderdetails1Records = ' + consumableorderdetails1Records
    );
    System.debug('invoiceId = ' + invoiceId);
    System.debug('orderId = ' + orderId);

    Savepoint sp = Database.setSavepoint();
    //新规发票明细1
    List<Consumable_Orderdetails__c> invoiceorderList1 = new List<Consumable_Orderdetails__c>();
    //更新发票明细1
    List<Consumable_Orderdetails__c> invoiceorderUpList1 = new List<Consumable_Orderdetails__c>();
    //删除发票明细1
    List<Consumable_Orderdetails__c> invoiceorderDeList1 = new List<Consumable_Orderdetails__c>();

    Map<String, Consumable_Orderdetails__c> invoiceordet1Map = new Map<String, Consumable_Orderdetails__c>();

    List<String> consumableorderList = new List<String>();
    List<String> consumableNameList = new List<String>();
    try {
      //更新出库单明细1
      for (ConsumableorderdetailsInfo ass : consumableorderdetails1Records) {
        consumableorderList.add(ass.esd.Asset_Model_No__c);
      }

      //发票明细1获取
      List<Consumable_Orderdetails__c> invoiceorderdetails1 = [
        SELECT
          Id,
          Name,
          Consumable_order__c,
          Asset_Model_No__c,
          Consumable_Product__r.Asset_Model_No__c,
          Consumable_Count__c,
          Shipment_Count__c,
          RrturnPro_count__c,
          Delivery_List_RMB__c,
          InvoicedProCost_RMB__c,
          Invoiced_Procount__c,
          Invoiced_Count__c,
          Invoice_Unitprice__c,
          InvoiceProNot_count__c,
          Invoice_Cost_RMB__c,
          Invoice_No__c,
          Invoice_Unit__c,
          Box_Piece__c,
          Invoicedet1_OD_link__c
        FROM Consumable_Orderdetails__c
        WHERE
          Consumable_order__c = :invoiceId
          AND Invoicedet1_OD_link__c = :orderId
          AND Asset_Model_No__c IN :consumableorderList
      ];
      for (Integer i = 0; i < invoiceorderdetails1.size(); i++) {
        invoiceordet1Map.put(
          invoiceorderdetails1[i].Invoicedet1_OD_link__c +
          invoiceorderdetails1[i].Asset_Model_No__c,
          invoiceorderdetails1[i]
        );
      }
      List<Consumable_Orderdetails__c> invoicedetails1count = [
        SELECT
          Id,
          Name,
          Consumable_order__c,
          Invoicedet1_OD_link__c,
          Asset_Model_No__c,
          Consumable_Product__r.Asset_Model_No__c,
          Consumable_Count__c,
          Shipment_Count__c,
          RrturnPro_count__c,
          Delivery_List_RMB__c,
          InvoicedProCost_RMB__c,
          Invoiced_Procount__c,
          Invoiced_Count__c,
          Sum_of_money__c,
          Invoice_Unitprice__c,
          InvoiceProNot_count__c,
          Invoice_Cost_RMB__c,
          Invoice_Unit__c,
          Invoice_No__c
        FROM Consumable_Orderdetails__c
        WHERE Consumable_order__c = :invoiceId
      ];
      Integer invoiceRecordscon = invoicedetails1count.size() + 1;

      for (ConsumableorderdetailsInfo ass : consumableorderdetails1Records) {
        if (ass.check == true && ass.invoiceCount > 0) {
          if (String.isEmpty(String.valueOf(ass.invoiceCount))) {
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入发票数量！'));
            // return null;
            return new ResponseBodyLWC('Error', 500, '请输入发票数量！', '');
          }
          if (ass.esd.Box_Piece__c == '盒' && ass.esd.Invoice_Unit__c == '个') {
            if (
              ass.invoiceCount >
              (ass.esd.InvoiceProNot_count__c * ass.Packing_list_manual)
                .setScale(0)
            ) {
              // ass.esd.InvoiceProNot_count__c.addError('发票数量不能超过还没发票数量！');
              // return null;
              return new ResponseBodyLWC(
                'Error',
                500,
                '发票数量不能超过还没发票数量！',
                ''
              );
            }
          } else {
            if (ass.invoiceCount > ass.esd.InvoiceProNot_count__c) {
              // ass.esd.InvoiceProNot_count__c.addError('发票数量不能超过还没发票数量！');
              // return null;
              return new ResponseBodyLWC(
                'Error',
                500,
                '发票数量不能超过还没发票数量！',
                ''
              );
            }
          }

          //if(ass.esd.Invoice_Unit__c =='个'){
          String invoiceCount = String.valueOf(ass.invoiceCount);
          if (!Pattern.matches('^\\+{0,1}[1-9]\\d*', invoiceCount)) {
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '发票数量必须是整数'));
            // return null;
            return new ResponseBodyLWC('Error', 500, '发票数量必须是整数', '');
          }
          //}

          if (
            invoiceordet1Map.containsKey(
              ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
            )
          ) {
            invoiceordet1Map.get(
                ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
              )
              .Shipment_Count__c = ass.invoiceCount;
            invoiceordet1Map.get(
                ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
              )
              .Invoiced_Count__c = ass.invoiceCount;
            //invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).InvoicedProCost_RMB__c = invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Delivery_List_RMB__c * ass.invoiceCount;
            invoiceordet1Map.get(
                ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
              )
              .Invoice_Unit__c = ass.esd.Invoice_Unit__c;
            invoiceordet1Map.get(
                ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
              )
              .Box_Piece__c = ass.esd.Box_Piece__c;
            if (
              ass.esd.Box_Piece__c == '盒' &&
              ass.esd.Invoice_Unit__c == '个'
            ) {
              invoiceordet1Map.get(
                    ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
                  )
                  .InvoicedProCost_RMB__c =
                (ass.esd.Delivery_List_RMB__c / ass.Packing_list_manual) *
                ass.invoiceCount;
              invoiceordet1Map.get(
                    ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
                  )
                  .Invoice_Unitprice__c =
                ass.esd.Delivery_List_RMB__c / ass.Packing_list_manual;
            } else {
              invoiceordet1Map.get(
                    ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
                  )
                  .InvoicedProCost_RMB__c =
                ass.esd.Delivery_List_RMB__c * ass.invoiceCount;
              invoiceordet1Map.get(
                  ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
                )
                .Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
            }

            invoiceorderUpList1.add(
              invoiceordet1Map.get(
                ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
              )
            );
            invoiceRecordscon++;
          } else {
            String str = string.valueOf(invoiceRecordscon);
            if (str.length() == 1) {
              str = '0' + str;
            }
            Consumable_Orderdetails__c invoiceInsert1 = new Consumable_Orderdetails__c();
            invoiceInsert1.Used_date__c = ass.esd.Used_date__c;
            invoiceInsert1.Send_date__c = ass.esd.Send_date__c;
            invoiceInsert1.Name =
              invoicecode.Name +
              '-' +
              ass.esd.Name.substring(
                ass.esd.Name.length() - 7,
                ass.esd.Name.length()
              );
            invoiceInsert1.Shipment_Count__c = ass.invoiceCount;
            invoiceInsert1.Consumable_Product__c = ass.esd.Consumable_Product__c;
            invoiceInsert1.Intra_Trade_List_RMB__c = ass.esd.Intra_Trade_List_RMB__c;
            invoiceInsert1.Delivery_List_RMB__c = ass.esd.Delivery_List_RMB__c;
            invoiceInsert1.Dealer_Custom_Price__c = ass.esd.Dealer_Custom_Price__c;
            invoiceInsert1.RecordTypeId = System.Label.RT_ConOrderDetail1_Invoice;
            if (
              ass.esd.Box_Piece__c == '盒' &&
              ass.esd.Invoice_Unit__c == '个'
            ) {
              invoiceInsert1.Invoice_Unitprice__c =
                ass.esd.Delivery_List_RMB__c / ass.Packing_list_manual;
            } else {
              invoiceInsert1.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
            }
            //invoiceInsert1.Invoice_Unitprice__c = ass.esd.Invoice_Unitprice__c;
            invoiceInsert1.Invoice_Unit__c = ass.esd.Invoice_Unit__c;
            invoiceInsert1.Box_Piece__c = ass.esd.Box_Piece__c;
            if (ass.esd.Invoiced_Procount__c == null)
              ass.esd.Invoiced_Procount__c = 0;
            invoiceInsert1.Invoiced_Count__c = ass.invoiceCount;
            if (ass.esd.InvoicedProCost_RMB__c == null)
              ass.esd.InvoicedProCost_RMB__c = 0;
            invoiceInsert1.InvoicedProCost_RMB__c =
              ass.invoiceCount * invoiceInsert1.Invoice_Unitprice__c;
            invoiceInsert1.Consumable_order__c = invoiceId;
            invoiceInsert1.Invoicedet1_OD_link__c = orderId;
            invoiceRecordscon++;
            invoiceorderList1.add(invoiceInsert1);
          }
        } else {
          if (
            invoiceordet1Map.containsKey(
              ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
            )
          ) {
            invoiceorderDeList1.add(
              invoiceordet1Map.get(
                ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c
              )
            );
          }
        }
      }

      if (invoiceorderList1.size() > 0) {
        insert invoiceorderList1;
      }
      if (invoiceorderUpList1.size() > 0) {
        update invoiceorderUpList1;
      }
      if (invoiceorderDeList1.size() > 0) {
        delete invoiceorderDeList1;
      }
    } catch (Exception e) {
      ApexPages.addmessages(e);
      // Database.rollback(sp);
      // return null;
      return new ResponseBodyLWC(
        'Error',
        500,
        e.getMessage() + ' ' + e.getLineNumber(),
        ''
      );
    }
    res.status = 'Success';
    res.code = 200;
    System.debug('res = ' + res);
    return res;
  }

  // Data Bean
  @TestVisible
  class ConsumableorderdetailsInfo {
    @AuraEnabled
    public Boolean check { get; set; }
    @AuraEnabled
    public Boolean oldCheck { get; set; }
    @AuraEnabled
    public Consumable_Orderdetails__c esd { get; set; }
    @AuraEnabled
    public Product2__c Prod { get; set; }
    @AuraEnabled
    public Decimal invoiceCount { get; set; }
    @AuraEnabled
    public Decimal invoiceAllprice { get; set; }
    @AuraEnabled
    public Decimal Packing_list_manual { get; set; }
    public List<SelectOption> Invoice_UnitOpts { get; set; }
    @AuraEnabled
    public Map<String, String> Invoice_UnitOptsMap { get; set; }
    // 消耗品产品明细
    public ConsumableorderdetailsInfo(Consumable_Orderdetails__c e) {
      check = false;
      oldCheck = false;
      esd = e;
      Prod = e.Consumable_Product__r;
      invoiceAllprice = 0;

      Packing_list_manual = e.Consumable_Product__r.Packing_list_manual__c;
      if (!Test.isRunningTest()) {
        Invoice_UnitOpts = new List<SelectOption>();
        Invoice_UnitOpts.add(new SelectOption('盒', '盒'));
        Invoice_UnitOpts.add(new SelectOption('个', '个'));
      }

      Invoice_UnitOptsMap = new Map<String, String>();
      Invoice_UnitOptsMap.put('盒', '盒');
      Invoice_UnitOptsMap.put('个', '个');
    }
  }
}
