public without sharing class LexConsumableAccountController {
  //经销商用户产品分类（ET、ENG）
  public static String agencyProType { get; set; }
  public static String agencyProTypestr { get; set; }
  //选项卡名称
  public static String filterName { get; set; }
  //选项卡类型
  public static String hosptialType { get; set; }
  public static ApexPages.StandardSetController setCon { get; set; }
  //画面显示数量
  public static Integer size { get; set; }
  public static Integer noOfRecords { get; set; }
  //显示集合
  public static List<Account> pageRecords { get; set; }
  //经销商信息
  private static String accountName { get; set; }
  private static String accountId { get; set; }
  //排序使用
  // public static String sortKey { get; set; }
  // public static String preSortKey { get; private set; }
  // public static Boolean sortOrderAsc { get; private set; }
  // public static String[] sortOrder { get; private set; }
  // //排序使用
  // private static String[] orderby = new String[]{ 'Name','State_Master__c','Salesdepartment_HP__c','CreatedDate','Is_Active__c','RecordType.Name','Grade__c','OCM_Category__c','City_Master__c','Town__c','Phone'};
  //上周开始、结束日期
  private static Datetime lastweekstart { get; set; }
  private static Datetime lastweekend { get; set; }
  // page
  public static Integer pagesize { get; set; }
  public static Integer pageToken { get; set; }
  public static String sortField { get; set; }
  public static String sortOrder { get; set; }
  public static Integer totalcount { get; set; }

  //初始化
  @AuraEnabled
  public static ResponseBodyLWC init(
    Integer pageSizeLWC,
    Integer pageTokenLWC,
    String fiscalYear
  ) {
    try {
      ResponseBodyLWC res = new ResponseBodyLWC();
      Map<String, object> data = new Map<String, object>();
      res.entity = data;

      pageSize = pageSizeLWC;
      pageToken = pageTokenLWC > 2000 ? 2000 : pageTokenLWC;

      User Useracc = [
        SELECT accountid, UserPro_Type__c
        FROM user
        WHERE id = :UserInfo.getUserId()
      ];
      accountId = [SELECT id, Name FROM account WHERE id = :Useracc.accountid]
      .id;
      agencyProType = Useracc.UserPro_Type__c;
      if (String.isBlank(Useracc.UserPro_Type__c)) {
        agencyProType = 'ET';
      }
      agencyProTypestr = '%' + agencyProType + '%';
      System.debug('accountId = ' + accountId);
      System.debug('agencyProTypestr = ' + agencyProTypestr);
      List<Account> allSelectAccount = [
        SELECT
          id,
          Name,
          State_Master__c,
          State_Master__r.Name,
          Salesdepartment_HP__c,
          CreatedDate,
          Is_Active__c,
          RecordType.Name,
          Grade__c,
          OCM_Category__c,
          City_Master__c,
          City_Master__r.Name,
          Town__c,
          Phone
        FROM Account
        WHERE
          id IN (
            SELECT Hospital__c
            FROM Agency_Hospital_Link__c
            WHERE
              Agency__c = :accountId
              AND Hosptial_Type__c LIKE :agencyProTypestr
          )
      ];
      totalCount = allSelectAccount.size();

      List<Account> selectAccList = [
        SELECT
          id,
          Name,
          State_Master__c,
          State_Master__r.Name,
          Salesdepartment_HP__c,
          CreatedDate,
          Is_Active__c,
          RecordType.Name,
          Grade__c,
          OCM_Category__c,
          City_Master__c,
          City_Master__r.Name,
          Town__c,
          Phone
        FROM Account
        WHERE
          id IN (
            SELECT Hospital__c
            FROM Agency_Hospital_Link__c
            WHERE
              Agency__c = :accountId
              AND Hosptial_Type__c LIKE :agencyProTypestr
          )
        LIMIT :pageSize
      ];
      System.debug('selectAccList = ' + selectAccList);
      PaginatedAccounts paginatedAccounts = new PaginatedAccounts();
      paginatedAccounts.nextPageToken = (pageToken + pageSize < totalCount)
        ? pageToken + pageSize
        : null;
      paginatedAccounts.recordStart = pageToken + 1;
      paginatedAccounts.pageNumber = pageToken / pageSize + 1;
      Integer recordEnd = pageSize * paginatedAccounts.pageNumber;
      paginatedAccounts.recordEnd = totalCount >= recordEnd
        ? recordEnd
        : totalCount;
      paginatedAccounts.totalRecords = totalCount;

      //销量前十的客户
      // List<Account> acList = [
      //     SELECT
      //         id,
      //         Name,
      //         State_Master__c,
      //         State_Master__r.Name,
      //         Salesdepartment_HP__c,
      //         CreatedDate,
      //         Is_Active__c,
      //         RecordType.Name,
      //         Grade__c,
      //         OCM_Category__c,
      //         City_Master__c,
      //         City_Master__r.Name,
      //         Town__c,
      //         Phone
      //     FROM Account
      //     WHERE State_Master__r.Name != '' AND City_Master__r.Name != '' AND Is_Active__c = '有効' AND RecordType.Name = '病院'
      //     LIMIT 10
      // ];
      TopInfo topInfo = new TopInfo();

      Date today = Date.today();
      Integer lastYear = today.year() - 1;
      Integer thisYear = today.year();
      Integer nextYear = today.year() + 1;
      Date lastDatetime = Date.newInstance(lastYear, 4, 1);
      Date thisDatetime = Date.newInstance(thisYear, 4, 1);
      Date thisDatetime2 = Date.newInstance(thisYear, 4, 1);
      Date nextDatetime = Date.newInstance(nextYear, 4, 1);

      AggregateResult[] arList = null;

      System.debug('fiscalYear = ' + fiscalYear);
      if (fiscalYear == 'thisYear') {
        AggregateResult[] saleAmountList = LexConsumableAccountSOQL.getAccountTotalSales(
          thisDatetime,
          nextDatetime
        );
        topInfo.saleAmount = Decimal.valueOf(
          String.valueOf(saleAmountList[0].get('saleAmount'))
        );
        System.debug('topInfo.saleAmount = ' + topInfo.saleAmount);
        arList = LexConsumableAccountSOQL.getAccountBySales(
          thisDatetime,
          nextDatetime
        );
      } else if (fiscalYear == 'lastYear') {
        AggregateResult[] saleAmountList = LexConsumableAccountSOQL.getAccountTotalSales(
          lastDatetime,
          thisDatetime2
        );
        topInfo.saleAmount = Decimal.valueOf(
          String.valueOf(saleAmountList[0].get('saleAmount'))
        );
        System.debug('topInfo.saleAmount = ' + topInfo.saleAmount);
        arList = LexConsumableAccountSOQL.getAccountBySales(
          lastDatetime,
          thisDatetime2
        );
      } else {
        AggregateResult[] saleAmountList = LexConsumableAccountSOQL.getAccountTotalSales(
          lastDatetime,
          nextDatetime
        );
        topInfo.saleAmount = Decimal.valueOf(
          String.valueOf(saleAmountList[0].get('saleAmount'))
        );
        System.debug('topInfo.saleAmount = ' + topInfo.saleAmount);
        arList = LexConsumableAccountSOQL.getAccountBySales(
          lastDatetime,
          nextDatetime
        );
      }

      // Map<String,Decimal> mapTemp = new Map<String,Decimal>();
      // for (AggregateResult ar : arList) {
      //     if(!mapTemp.get(String.valueOf(ar.get('hospitalName')))){
      //         mapTemp.put(String.valueOf(ar.get('hospitalName'),Decimal.valueOf(String.valueOf(ar.get('thisAmount')))));
      //     }else {
      //         Decimal decimal = mapTemp.get(String.valueOf(ar.get('hospitalName')));
      //         decimal += Decimal.valueOf(String.valueOf(ar.get('thisAmount')));
      //         mapTemp.put(String.valueOf(ar.get('hospitalName'),decimal));
      //     }
      // }
      // System.debug('mapTemp = ' + mapTemp);
      // //排序Decimal从大到小
      // List<Decimal> decimalList = new List<Decimal>(mapTemp.values());
      // decimalList.sort((a, b) => b.compareTo(a));
      // Map<String, Decimal> sortedMap = new Map<String, Decimal>();
      // for (String key : mapTemp.keySet()) {
      //     sortedMap.put(key, mapTemp.get(key));
      // }

      // System.debug('Sorted Map: ' + sortedMap);

      //查询客户信息（名称，省，县）
      System.debug('arList = ' + arList);
      List<String> accountList = new List<String>();
      for (AggregateResult ar : arList) {
        System.debug('thisAmount = ' + String.valueOf(ar.get('thisAmount')));
        if (String.valueOf(ar.get('thisAmount')) != '0.0') {
          accountList.add(String.valueOf(ar.get('Order_ForHospital__c')));
          topInfo.deList.add(
            Decimal.valueOf(String.valueOf(ar.get('thisAmount')))
          );
        }
      }

      System.debug('accountList = ' + accountList);
      System.debug('topInfo = ' + topInfo);

      List<Account> acList = [
        SELECT
          id,
          Name,
          State_Master__c,
          State_Master__r.Name,
          Salesdepartment_HP__c,
          CreatedDate,
          Is_Active__c,
          RecordType.Name,
          Grade__c,
          OCM_Category__c,
          City_Master__c,
          City_Master__r.Name,
          Town__c,
          Phone
        FROM Account
        WHERE Id = :accountList
      ];

      List<Account> acListTemp = new List<Account>();

      for (String s : accountList) {
        for (Account a : acList) {
          if (s == a.id) {
            acListTemp.add(a);
          }
        }
      }

      topInfo.acList = acListTemp;

      data.put('topInfo', topInfo);
      data.put('pageRecords', selectAccList);
      data.put('paginatedAccounts', paginatedAccounts);
      data.put('accountId', accountId);
      data.put('agencyProType', agencyProType);
      data.put('agencyProTypestr', agencyProTypestr);
      res.status = 'Success';
      res.code = 200;
      res.msg = '';
      return res;
    } catch (Exception e) {
      return new ResponseBodyLWC(
        'Error',
        500,
        e.getMessage() + e.getLineNumber(),
        ''
      );
    }
  }

  @AuraEnabled
  public static ResponseBodyLWC changeFiscalYearView(String fiscalYear) {
    ResponseBodyLWC res = new ResponseBodyLWC();
    Map<String, object> data = new Map<String, object>();
    res.entity = data;
    try {
      TopInfo topInfo = new TopInfo();

      Date today = Date.today();
      Integer lastYear = today.year() - 1;
      Integer thisYear = today.year();
      Integer nextYear = today.year() + 1;
      Date lastDatetime = Date.newInstance(lastYear, 4, 1);
      Date thisDatetime = Date.newInstance(thisYear, 4, 1);
      Date thisDatetime2 = Date.newInstance(thisYear, 4, 1);
      Date nextDatetime = Date.newInstance(nextYear, 4, 1);

      AggregateResult[] arList = null;

      System.debug('fiscalYear = ' + fiscalYear);
      System.debug('thisYear = ' + thisYear);
      System.debug('lastYear = ' + lastYear);

      if (fiscalYear == 'thisYear') {
        AggregateResult[] saleAmountList = LexConsumableAccountSOQL.getAccountTotalSales(
          thisDatetime,
          nextDatetime
        );
        if (saleAmountList[0].get('saleAmount') != null) {
          topInfo.saleAmount = Decimal.valueOf(
            String.valueOf(saleAmountList[0].get('saleAmount'))
          );
          System.debug('topInfo.saleAmount = ' + topInfo.saleAmount);
        }
        arList = LexConsumableAccountSOQL.getAccountBySales(
          thisDatetime,
          nextDatetime
        );
      } else if (fiscalYear == 'lastYear') {
        AggregateResult[] saleAmountList = LexConsumableAccountSOQL.getAccountTotalSales(
          lastDatetime,
          thisDatetime2
        );
        if (saleAmountList[0].get('saleAmount') != null) {
          topInfo.saleAmount = Decimal.valueOf(
            String.valueOf(saleAmountList[0].get('saleAmount'))
          );
          System.debug('topInfo.saleAmount = ' + topInfo.saleAmount);
        }
        arList = LexConsumableAccountSOQL.getAccountBySales(
          lastDatetime,
          thisDatetime2
        );
      } else {
        AggregateResult[] saleAmountList = LexConsumableAccountSOQL.getAccountTotalSales(
          lastDatetime,
          nextDatetime
        );
        if (saleAmountList[0].get('saleAmount') != null) {
          topInfo.saleAmount = Decimal.valueOf(
            String.valueOf(saleAmountList[0].get('saleAmount'))
          );
          System.debug('topInfo.saleAmount = ' + topInfo.saleAmount);
        }
        arList = LexConsumableAccountSOQL.getAccountBySales(
          lastDatetime,
          nextDatetime
        );
      }
      //查询客户信息（名称，省，县）
      List<String> accountList = new List<String>();
      for (AggregateResult ar : arList) {
        System.debug('thisAmount = ' + String.valueOf(ar.get('thisAmount')));
        if (String.valueOf(ar.get('thisAmount')) != '0.0') {
          accountList.add(String.valueOf(ar.get('Order_ForHospital__c')));
          topInfo.deList.add(
            Decimal.valueOf(String.valueOf(ar.get('thisAmount')))
          );
        }
      }
      System.debug('accountList = ' + accountList);
      System.debug('topInfo = ' + topInfo);
      List<Account> acList = [
        SELECT
          id,
          Name,
          State_Master__c,
          State_Master__r.Name,
          Salesdepartment_HP__c,
          CreatedDate,
          Is_Active__c,
          RecordType.Name,
          Grade__c,
          OCM_Category__c,
          City_Master__c,
          City_Master__r.Name,
          Town__c,
          Phone
        FROM Account
        WHERE Id = :accountList
      ];
      List<Account> acListTemp = new List<Account>();
      for (String s : accountList) {
        for (Account a : acList) {
          if (s == a.id) {
            acListTemp.add(a);
          }
        }
      }
      topInfo.acList = acListTemp;
      data.put('topInfo', topInfo);
      res.status = 'Success';
      res.code = 200;
      res.msg = '';
      return res;
    } catch (Exception e) {
      return new ResponseBodyLWC(
        'Error',
        500,
        e.getMessage() + e.getLineNumber(),
        ''
      );
    }
  }

  @AuraEnabled
  public static ResponseBodyLWC changelistView(
    String filterNameLwc,
    String accountIdLwc,
    String agencyProTypeLwc,
    Integer pageSizeLWC,
    Integer pageTokenLWC,
    String sortFieldLWC,
    String sortOrderLWC
  ) {
    try {
      ResponseBodyLWC res = new ResponseBodyLWC();
      Map<String, object> data = new Map<String, object>();
      res.entity = data;

      filterName = filterNameLwc;
      accountId = accountIdLwc;
      agencyProTypestr = agencyProTypeLwc;
      pageSize = pageSizeLWC;
      pageToken = pageTokenLWC > 2000 ? 2000 : pageTokenLWC;
      sortField = sortFieldLWC;
      sortOrder = sortOrderLWC;

      String soql = makeSoql(filterName, accountId);
      System.debug('soql1+++++++ ' + soql);
      List<Account> allSelectAccount = Database.query(soql);

      totalCount = allSelectAccount.size();
      String nullFL = sortOrder.toLowerCase() == 'asc'
        ? 'NULLS FIRST'
        : 'NULLS LAST';
      if (String.isNotBlank(sortField)) {
        soql += ' order by ' + sortField + ' ' + sortOrder + ' ' + nullFL;
      }
      soql += ' limit ' + pagesize + ' offset ' + pageToken;
      System.debug('soql2+++++++ ' + soql);
      List<Account> selectAccList = Database.query(soql);
      System.debug('selectAccList = ' + selectAccList);

      PaginatedAccounts paginatedAccounts = new PaginatedAccounts();
      paginatedAccounts.nextPageToken = (pageToken + pageSize < totalCount)
        ? pageToken + pageSize
        : null;
      paginatedAccounts.recordStart = pageToken + 1;
      paginatedAccounts.pageNumber = pageToken / pageSize + 1;
      Integer recordEnd = pageSize * paginatedAccounts.pageNumber;
      paginatedAccounts.recordEnd = totalCount >= recordEnd
        ? recordEnd
        : totalCount;
      paginatedAccounts.totalRecords = totalCount;

      data.put('pageRecords', selectAccList);
      data.put('paginatedAccounts', paginatedAccounts);
      res.status = 'Success';
      res.code = 200;
      res.msg = '';
      return res;
    } catch (Exception e) {
      return new ResponseBodyLWC(
        'Error',
        500,
        e.getMessage() + ' ' + e.getLineNumber(),
        ''
      );
    }
  }

  //sql文作成
  private static String makeSoql(String viewName, String accountId) {
    Date st = Date.today().addDays(-7).toStartOfWeek();
    lastweekstart = Datetime.newInstance(
      st.year(),
      st.month(),
      st.day(),
      8,
      0,
      0
    );
    lastweekend = lastweekstart.addDays(7);
    String soql = 'SELECT id,Name,State_Master__c,Salesdepartment_HP__c,CreatedDate,Is_Active__c,RecordType.Name,State_Master__r.Name,City_Master__r.Name';
    soql += ' ,Grade__c,OCM_Category__c,City_Master__c,Town__c,Phone FROM Account';
    soql +=
      ' WHERE id in (SELECT Hospital__c FROM Agency_Hospital_Link__c WHERE Agency__c =:accountId AND Hosptial_Type__c like \'%' +
      String.escapeSingleQuotes(agencyProTypestr.replaceAll('%', '\\%')) +
      '%\')';
    if (viewName == '61. 医院_Hospital草案中的医院') {
      soql += ' AND Is_Active__c = \'' + '草案中' + '\'';
    }
    if (viewName == '62. 医院_Hospital申请中的医院') {
      soql += ' AND Is_Active__c = \'' + '申请中' + '\'';
    }
    if (viewName == '63. 医院_Hospital上周创建的医院') {
      soql += ' AND Is_Active__c = \'' + '有效' + '\'';
      soql += ' AND CreatedDate >= :lastweekstart ';
      soql += ' AND CreatedDate < :lastweekend ';
    }
    System.debug('soql +++++' + soql);
    return soql;
  }

  //分页Bean
  public class PaginatedAccounts {
    @AuraEnabled
    public Integer nextPageToken;
    @AuraEnabled
    public Integer pageNumber { get; set; }
    @AuraEnabled
    public Integer totalRecords { get; set; }
    @AuraEnabled
    public Integer recordStart { get; set; }
    @AuraEnabled
    public Integer recordEnd { get; set; }
  }

  //top10 Account
  public class TopInfo {
    @AuraEnabled
    public Decimal saleAmount { get; set; }
    @AuraEnabled
    public List<Account> acList { get; set; }
    @AuraEnabled
    public List<Decimal> deList { get; set; }

    public TopInfo() {
      acList = new List<Account>();
      deList = new List<Decimal>();
    }
  }
}
