/***
 *
 *
 *
 *
 */
public without sharing class LexConsumableOrderManageController {
  public static Consumable_order__c coc { get; set; }
  public static String agencyProType { get; set; }
  public static String category1 { get; set; }
  public static String baseUrl { get; private set; }
  private static String[] columus = new List<String>{ 'Product2__c.Name' };
  public static List<SelectOption> provinceOpts { get; set; }
  public static List<CusOption> provinceCusOpts;
  private static String accountid = null;
  public static List<String> title { get; private set; }
  public static List<String> column;
  public static List<List<String>> columns { get; private set; }
  public static List<Consumable_order__c> raesList { get; private set; }
  private static String userWorkLocation;
  public static Boolean hasHop { get; set; }
  public static Boolean hasSpecial { get; set; }
  public LexConsumableOrderManageController() {
    baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
  }

  @AuraEnabled
  public static Results init1() {
    Results results = new Results();
    results.isNoteStay = LexUtility.getIsNoteStay();
    try {
      String userId = UserInfo.getUserId();
      // String userId = '0050l000007CAieAAG';
      List<user> Useracc = new List<user>();
      Useracc = [
        SELECT accountid, Work_Location__c, UserPro_Type__c
        FROM user
        WHERE id = :userId
      ];
      accountid = Useracc[0].accountid;
      agencyProType = Useracc[0].UserPro_Type__c;
      if (String.isBlank(Useracc[0].UserPro_Type__c)) {
        agencyProType = 'ET';
      }
      userWorkLocation = Useracc[0].Work_Location__c;
      coc = new Consumable_order__c();
      // 获得订单一览
      Map<String, Schema.FieldSet> fsMap = Schema.getGlobalDescribe()
        .get('Consumable_order__c')
        .getDescribe()
        .fieldSets.getMap();
      Schema.FieldSet fs = fsMap.get('order_view');
      // 获得订单中的所有项目
      List<FieldSetMember> fsmList = fs.getFields();
      // 获得字段标签和字段名
      title = new List<String>();
      column = new List<String>();
      columns = new List<List<String>>();
      List<CusCol> cols = new List<CusCol>();
      for (FieldSetMember fsm : fsmList) {
        //add by Link
        if (
          fsm.getFieldPath() == 'Order_ForHospital__c' &&
          agencyProType == 'ET'
        ) {
        } else {
          CusCol col = new CusCol();
          col.label = fsm.getLabel();
          col.fieldName = fsm.getFieldPath();
          col.hideDefaultActions = true;
          // col.sortable = true;
          col.wrapText = true;
          if (fsm.getFieldPath() == 'Order_ForHospital__c') {
            col.type = 'url';
            col.fieldName = 'hosUrl';
            TypeAttr typeAttributes1 = new TypeAttr();
            CusLable cusLabel = new CusLable();
            cusLabel.fieldName = 'hosName';
            typeAttributes1.label = cusLabel;
            typeAttributes1.target = '_blank';
            col.typeAttributes = typeAttributes1;
          }
          if (fsm.getFieldPath() == 'Name') {
            col.type = 'url';
            col.fieldName = 'nameUrl';
            TypeAttr typeAttributes1 = new TypeAttr();
            CusLable cusLabel = new CusLable();
            cusLabel.fieldName = 'Name';
            typeAttributes1.label = cusLabel;
            typeAttributes1.target = '_blank';
            col.typeAttributes = typeAttributes1;
          }
          cols.add(col);
        }
        //update by rentx 2020-12-22 start
        if (
          fsm.getLabel() == '医院' &&
          agencyProType != null &&
          agencyProType == 'ET'
        ) {
        } else {
          title.add(fsm.getLabel());
        }
        if (
          fsm.getFieldPath() == 'Order_ForHospital__c' &&
          agencyProType != null &&
          agencyProType == 'ET'
        ) {
        } else {
          column.add(fsm.getFieldPath());
          columns.add(fsm.getFieldPath().split('\\.'));
        }
      }
      provinceOpts = new List<SelectOption>();
      provinceOpts.add(new SelectOption('', '-无-'));
      provinceOpts.add(new SelectOption('草案中', '草案中'));
      provinceOpts.add(new SelectOption('已提交', '已提交'));
      provinceOpts.add(new SelectOption('批准', '批准'));
      provinceOpts.add(new SelectOption('驳回', '驳回'));
      //针对lwc的自定义option
      provinceCusOpts = new List<CusOption>();
      provinceCusOpts.add(new CusOption('-无-', ''));
      provinceCusOpts.add(new CusOption('草案中', '草案中'));
      provinceCusOpts.add(new CusOption('已提交', '已提交'));
      provinceCusOpts.add(new CusOption('批准', '批准'));
      provinceCusOpts.add(new CusOption('驳回', '驳回'));
      // 获得显示数据
      raesList = new List<Consumable_order__c>();
      String soql = 'select Id';
      for (String s : column) {
        soql += ',' + s;
      }
      soql +=
        ',Order_ForHospital__r.Name from Consumable_order__c where Order_type__c = \'' +
        '订单' +
        '\'';
      soql += ' and RecordtypeId = \'' + System.Label.RT_ConOrder_Order + '\'';
      soql += ' and Order_Owner_WorkLocal__c = \'' + userWorkLocation + '\'';
      soql += ' and Order_ProType__c =\'' + agencyProType + '\' ';
      soql +=
        ' and Dealer_Info__c =\'' +
        accountid +
        '\' order by Order_status__c ';
      System.debug('====soql====' + soql);
      raesList = Database.query(soql);
      //add by rentx 2021-3-10 start
      //为 hasHop 赋值 判断当前经销商下是否有特价医院
      List<hospitalprice__c> hopList = [
        SELECT id, hospital__c
        FROM hospitalprice__c
        WHERE account__c = :accountid
      ];
      if (hopList == null || hopList.size() == 0) {
        hasHop = false;
      } else {
        hasHop = true;
      }
      //为 hasSpecial 赋值 判断当前经销商下是否有促销商品
      //查询当前经销商下的有效合同
      List<Account> contractList = [
        SELECT Id, Name, RecordType.DeveloperName
        FROM Account
        WHERE
          RecordType.DeveloperName = 'AgencyContract'
          AND Contact_Type__c LIKE :agencyProType
          AND Agent_Ref__c = :accountid
      ];
      List<Id> dealIds = new List<Id>();
      if (contractList != null && contractList.size() > 0) {
        for (Account acc : contractList) {
          dealIds.add(acc.Id);
        }
        List<Dealer_Product__c> deList = [
          SELECT id
          FROM Dealer_Product__c
          WHERE Dealer_Contact__c IN :dealIds
        ];
        if (deList == null || deList.size() == 0) {
          hasSpecial = false;
        } else {
          hasSpecial = true;
        }
      } else {
        hasSpecial = false;
      }
      results.result = 'Success';
      results.provinceOpts = provinceCusOpts;
      results.raesList = raesList;
      results.agencyProType = agencyProType;
      results.userWorkLocation = userWorkLocation;
      results.accountid = accountid;
      results.hasHop = hasHop;
      results.hasSpecial = hasSpecial;
      results.title = title;
      results.cols = cols;
    } catch (Exception e) {
      results.result = 'Fail';
      results.raesList = new List<Consumable_order__c>();
      results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
    }
    return results;
  }

  @AuraEnabled
  public static Results searchConsumableorderdetails(
    String categoryStr,
    Date orderDate,
    String orderStatus,
    String accountidStr,
    String agencyProTypeStr,
    String userWorkLocationStr
  ) {
    Results results = new Results();
    agencyProType = agencyProTypeStr;
    userWorkLocation = userWorkLocationStr;
    accountid = accountidStr;
    if (String.isBlank(categoryStr)) {
      category1 = null;
    } else {
      category1 = categoryStr;
    }
    coc = new Consumable_order__c();
    if (String.isBlank(orderStatus)) {
      coc.Order_status__c = null;
    } else {
      coc.Order_status__c = orderStatus;
    }
    coc.Order_date__c = orderDate;
    try {
      Date cate2 = coc.Order_date__c;
      String cate3 = coc.Order_status__c;
      // 获得订单一览
      Map<String, Schema.FieldSet> fsMap = Schema.getGlobalDescribe()
        .get('Consumable_order__c')
        .getDescribe()
        .fieldSets.getMap();
      Schema.FieldSet fs = fsMap.get('order_view');
      // 获得订单中的所有项目
      List<FieldSetMember> fsmList = fs.getFields();
      // 获得字段标签和字段名
      title = new List<String>();
      column = new List<String>();
      columns = new List<List<String>>();
      for (FieldSetMember fsm : fsmList) {
        //update by rentx 2020-12-22 start
        if (
          fsm.getLabel() == '医院' &&
          agencyProType != null &&
          agencyProType == 'ET'
        ) {
        } else {
          title.add(fsm.getLabel());
        }
        if (
          fsm.getFieldPath() == 'Order_ForHospital__c' &&
          agencyProType != null &&
          agencyProType == 'ET'
        ) {
        } else {
          column.add(fsm.getFieldPath());
          columns.add(fsm.getFieldPath().split('\\.'));
        }
      }
      // 获得显示数据
      raesList = new List<Consumable_order__c>();
      String soql = 'select Id';
      for (String s : column) {
        soql += ',' + s;
      }
      soql +=
        ',Order_ForHospital__r.Name from Consumable_order__c where Order_type__c = \'' +
        '订单' +
        '\' and RecordtypeId = \'' +
        System.Label.RT_ConOrder_Order +
        '\' and Dealer_Info__c =\'' +
        accountid +
        '\' ';
      soql += ' and Order_Owner_WorkLocal__c = \'' + userWorkLocation + '\' ';
      soql += ' and Order_ProType__c =\'' + agencyProType + '\' ';
      if (!String.isBlank(category1)) {
        soql +=
          ' and Name like \'%' +
          String.escapeSingleQuotes(category1.replaceAll('%', '\\%')) +
          '%\' ';
      }
      if (cate2 != null) {
        soql += ' and Order_date__c = :cate2';
      }
      if (cate3 != null) {
        soql += ' and Order_status__c = :cate3 ';
      }
      soql += ' order by Order_status__c ';
      system.debug('====soql:' + soql);
      raesList = Database.query(soql);
      system.debug('====raesList:' + raesList);
      if (raesList.size() > 0) {
        results.result = 'Success';
        results.raesList = raesList;
        results.errorMsg = '共有' + raesList.size() + '个订单';
      } else {
        results.result = 'Fail';
        results.raesList = new List<Consumable_order__c>();
        results.errorMsg = '没有搜索到相关订单';
      }
    } catch (Exception e) {
      results.result = 'Fail';
      results.raesList = new List<Consumable_order__c>();
      results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
    }
    return results;
  }

  public class Results {
    @AuraEnabled
    public String result;
    @AuraEnabled
    public String errorMsg;
    @AuraEnabled
    public List<CusOption> provinceOpts;
    @AuraEnabled
    public List<String> title;
    @AuraEnabled
    public String accountid;
    @AuraEnabled
    public String agencyProType;
    @AuraEnabled
    public String userWorkLocation;
    @AuraEnabled
    public Boolean hasHop;
    @AuraEnabled
    public Boolean hasSpecial;
    @AuraEnabled
    public List<Consumable_order__c> raesList;
    @AuraEnabled
    public List<CusCol> cols;
    @AuraEnabled
    public Boolean isNoteStay;
  }

  public class CusOption {
    CusOption(String label, String value) {
      this.label = label;
      this.value = value;
    }

    @AuraEnabled
    public String label;
    @AuraEnabled
    public String value;
  }

  public class CusCol {
    @AuraEnabled
    public String label;
    @AuraEnabled
    public String fieldName;
    @AuraEnabled
    public String type;
    @AuraEnabled
    public Boolean sortable;
    @AuraEnabled
    public Boolean wrapText;
    @AuraEnabled
    public Boolean hideDefaultActions;
    @AuraEnabled
    public TypeAttr typeAttributes;
  }

  public class TypeAttr {
    @AuraEnabled
    public CusLable label;
    @AuraEnabled
    public String target;
  }

  public class CusLable {
    @AuraEnabled
    public String fieldName;
  }
}
