public with sharing class IDInformationAnalyseAssetController {

    /*****************検索用******************/
    //设备型号
    public String AssetModel {
        get;
        set;
    } 
    //医院名称
    public String HospitalName {
        get;
        set;
    } 
    //医院管理编码
    public String SerialNumber {
        get;
        set;
    } 
    //时间
    public String YearRange {
        get;
        set;
    } 

    public List < ChoiceAssetDetailedInfo > choiceAssetDetailedview {
        get;
        set;
    }

    public IDInformationAnalyseAssetController(ApexPages.StandardController controller) {

    }

    public IDInformationAnalyseAssetController() {
        choiceAssetDetailedview = new List < ChoiceAssetDetailedInfo > ();
    }

    // 画面初始化
    public void init() {
      choiceAssetDetailedview.clear();
    }
    class ChoiceAssetDetailedInfo {
      public String HPid { get; set; } //医院ID
      public String HPName { get; set; } //医院名字
      public String AstModel { get; set; } //设备型号
      public Decimal Endoscope { get; set; } //内镜件数
      public Decimal Overhaul { get; set; }  //大修次数
      public Decimal OverhaulPrice { get; set; } //大修报价
      public Decimal OverhaulvagPrice { get; set; } //大修均价
      public Integer Users { get; set; } //通电次数
      public Integer CBF { get; set; } //2次修理之间内镜的使用次数
      // public Integer YearVagCBF { get; set; } //年均使用例数
      public Decimal YearVagCBF { get; set; } //年均使用例数 WYL add
      public Decimal MinuteVagCBF { get; set; } //例均分钟数
      public Decimal UsersVagPrice { get; set; } //例均维修价格
    }
    public void hospitalCount(){
      choiceAssetDetailedview.clear();
      List<String> hospitalNameList = new List<String>();//医院名称List
	  System.debug('医院名称1：'+HospitalName);
      if (String.isNotBlank(HospitalName)){
        for(String hospitalName :HospitalName.trim().split('[,\\，]')){
          if (!hospitalNameList.contains(hospitalName)) {
            hospitalNameList.add(hospitalName);
          }
        }
      }else{
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '医院名称必须填写'));
		return;
      }

      system.debug('1111111111111111111111111111111医院名称'+hospitalNameList);

      List<ID> hospitalIDList = new List<ID>();//医院IDList
      if (hospitalNameList.size()>0) {
        List<Account> accList = [select id,name from Account where name IN : hospitalNameList];
        Map<String,ID> accMap = new Map<String,ID>();
        if (accList.size()>0) {
          for(Account acc : accList){
            accMap.put(acc.Name, acc.Id);
            if (!hospitalIDList.contains(acc.Id)) {
              hospitalIDList.add(acc.Id);
            }
          }
        }
        for(String st: hospitalNameList){
          if (String.isBlank(accMap.get(st))) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '医院名称:'+st+'不存在，请确认'));
          }
        }
      }else{
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '医院名称不存在，请确认'));
      }
      
      List<String> serialNumberList = new List<String>();
      if (String.isNotBlank(SerialNumber)){
        for(String SerialNumber :SerialNumber.trim().split('[,\\，]')){
          if (!serialNumberList.contains(SerialNumber)) {
            serialNumberList.add(SerialNumber);
          }
        }
      }
      system.debug('1111111111111111111111111111111机身编码'+serialNumberList);
      List<String> assetModelList = new List<String>();
      if (String.isNotBlank(AssetModel)){
        for(String assetModel :AssetModel.trim().split('[,\\，]')){
          if (!assetModelList.contains(assetModel)) {
            assetModelList.add(assetModel);
          }
        }
      }
      system.debug('1111111111111111111111111111111保有设备型号'+assetModelList);
      Integer yearCount = 0 ;
      if (String.isNotBlank(YearRange)){
        yearCount = Integer.valueOf(YearRange);
      }else{
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '搜索年限必须填写'));
      }
      
      Date dateToday = Date.today();
      Integer year = dateToday.year() - yearCount;
      Date mon1stDate = Date.newInstance(year, dateToday.month(), dateToday.day());
      // 2023-10-21 WYL id信息逻辑分析 update start
      System.debug('搜索年限：'+mon1stDate);
      String soql = 'select id,name,Repair_Severity_Rank__c,Repair_List_Price_formula__c,Hospital__c,Hospital__r.Name,Cumulative_Uses__c,Cumulative_Times__c,Cycle_between_failure__c,Delivered_Product__r.Product2.Asset_Model_No__c,Product_Unique_Value__c,Average_Usage_Time__c,Difference_in_repair_intervals__c';
      // soql += ' from Repair__c where Repair_Severity_Rank__c =\'大修理\' AND (Status1__c !=\'0.删除\' OR Status1__c !=\'0.取消\')';
      soql += ' from Repair__c where Repair_Severity_Rank__c =\'大修理\' AND Status1__c !=\'0.删除\' And Status1__c !=\'0.取消\''; 
      // 2023-10-21 WYL id信息逻辑分析  update end
      soql += 'AND createddate >= :mon1stDate ';
      if (assetModelList.size()>0){
        soql += 'AND Delivered_Product__r.Product2.Asset_Model_No__c IN : assetModelList ';
      }
      if(hospitalIDList.size()>0){
        soql += 'AND Hospital__c IN :hospitalIDList ';
      }
      if(serialNumberList.size()>0){
        soql += 'AND SerialNumber__c IN :serialNumberList ';
      }
      system.debug('111111111111111111111111111SQl语句'+soql);
      List<Repair__c> repairList = Database.query(soql);
      system.debug('111111111111111111111111111修理数量'+repairList.size());
      // 2023-10-15 WYL 新增 start
      // 1、将查询回来的数据通过Product_Unique_Value__c进行去重
      Map<String,String> repairMap = new Map<String,String>();
      for (Repair__c r : repairList) {
          if(!repairMap.containsKey(r.Product_Unique_Value__c)) {
            repairMap.put(r.Product_Unique_Value__c, r.Product_Unique_Value__c);
          }
      }
      // 2、通过去重后的组合去修理中查询出所有的 修理
      List<String> rList = new List<String>(repairMap.values());
      List<Repair__c> rLists = [select id,
                                name,
                                Cumulative_Uses__c,
                                Cumulative_Times__c,
                                Repair_Ordered_Date__c,
                                Cycle_between_failure__c,
                                Delivered_Product__c,
                                Product_Unique_Value__c 
                                from Repair__c 
                                where 
                                Cumulative_Uses__c != null 
                                and Cumulative_Times__c != null 
                                and Product_Unique_Value__c in: rList 
                                ORDER BY Repair_Ordered_Date__c Asc];
      System.debug('所有数据：'+rLists);
      Map<String,String> repairMap2 = new Map<String,String>();
      for (Repair__c r : rLists) {
          if(!repairMap2.containsKey(r.Product_Unique_Value__c)) {
            repairMap2.put(r.Product_Unique_Value__c, r.id);
          }  
      }
      System.debug('每组第一条数据：'+repairMap2.values());
      System.debug('第一条数据共有'+repairMap2.size());
      // 2023-10-15 WYL 新增 end
      List<Id> repairIDList = new List<Id>(); //修理IDList
      Map <Id,Repair__c> repair2Map = new Map <Id,Repair__c> (); //存储修理ID和修理对象
      List<ID> accountIDList = new List<ID>(); //医院List
      Map <Id,String> accountMap = new Map <Id,String> (); //存储修理ID和修理对象
      if (repairList.size()>0) {
        for (Repair__c re : repairList){
          if (!repairIDList.contains(re.Id)) {
            repairIDList.add(re.Id);
          }
          if (!accountIDList.contains(re.Hospital__c)) {
            accountIDList.add(re.Hospital__c);
            accountMap.put(re.Hospital__c, re.Hospital__r.Name);
          }
          repair2Map.put(re.Id, re);
        }
      }
      AggregateResult[] assetList = [select count(Id) ids,Delivered_Product__r.Product2.Asset_Model_No__c ass,Hospital__c from Repair__c where 
                    Id in : repairIDList
                    group by Delivered_Product__r.Product2.Asset_Model_No__c,Hospital__c
                    ];//统计大修修理找出保有设备型号数量
      system.debug('111111111111111111111111111设备型号数量'+assetList);
      Map <String,Integer> assetMap = new Map <String,Integer> ();//设备型号和数量
      List<String> assetModelAllList = new List<String>(); //设备型号List
        List<String> hpAllList = new List<String>(); //医院List
      for (AggregateResult ast : assetList){
        if (!assetModelAllList.contains(String.valueOf(ast.get('Hospital__c')) +String.valueOf(ast.get('ass')))) {
            assetModelAllList.add(String.valueOf(ast.get('Hospital__c')) +String.valueOf(ast.get('ass')));
                }
                if (!hpAllList.contains(String.valueOf(ast.get('Hospital__c')))) {
                    hpAllList.add(String.valueOf(ast.get('Hospital__c')));
                    assetMap.put(String.valueOf(ast.get('Hospital__c')) +String.valueOf(ast.get('ass')),Integer.valueOf(ast.get('ids')));
                 }
      }
      
      system.debug('11111111111111111大修设备型号'+assetModelAllList.size()+assetModelAllList);
        system.debug('11111111111111111大修设备型号个数'+assetMap.size()+assetMap);

      Map <String,Integer> repairCNMap = new Map <String,Integer> ();//存储医院ID和大修次数
      Map <String,Decimal> repairPRMap = new Map <String,Decimal> ();//存储医院ID和大修金额
      Map <String,Integer> repairUsesMap = new Map <String,Integer> ();//存储医院ID和通电次数
      Map <String,Integer> repairCBFMap = new Map <String,Integer> ();//存储医院ID和CBF
      Map <String,Integer> repairCTimesMap = new Map <String,Integer> ();//存储医院ID和通电时间
      Map <String,Decimal> NumberofcasesMap = new Map <String,Decimal> ();//新增 年均使用例数 两次维修间隔的使用例数➗间隔的检查日期（之差）*365 WYL 2023-11-20
      if (assetModelAllList.size()>0) {
        for(String ast : assetModelAllList){
          Integer overhaul = 0;
        Decimal overhaulPrice = 0;
        Integer users = 0;
        Integer cbf = 0;
        Integer cumulativeTimes= 0;
        Integer cbfNum = 0; // 记录repairList有多少条数据为第一条数据
        Integer cbfSum = 0; // 记录第一条数据的和 这部分数据不进行计算
        Decimal Numberofcases = 0;// 新增 年均使用例数 两次维修间隔的使用例数➗间隔的检查日期（之差）*365 WYL 2023-11-20
        Integer NumberofcasesNum = 0;
        if (repairList.size()>0) {
            for(Repair__c re : repairList){
              if (repairMap2.get(re.Product_Unique_Value__c) ==  re.Id) {
                System.debug('第一条数据的打印：'+ re);
                cbfSum += repair2Map.get(re.Id).Cycle_between_failure__c == null ? 0 :Integer.valueOf(repair2Map.get(re.Id).Cycle_between_failure__c);
                cbfNum ++;
              }
            
            // if (ast == repair2Map.get(re.Id).Delivered_Product__r.Product2.Asset_Model_No__c && hpAllList.contains(repair2Map.get(re.Id).Hospital__c)) {
            if (ast ==  (repair2Map.get(re.Id).Hospital__c+repair2Map.get(re.Id).Delivered_Product__r.Product2.Asset_Model_No__c )){
                          overhaul ++ ;
              overhaulPrice += repair2Map.get(re.Id).Repair_List_Price_formula__c;
              users += repair2Map.get(re.Id).Cumulative_Uses__c == null ? 0 :Integer.valueOf(repair2Map.get(re.Id).Cumulative_Uses__c);
              cbf += repair2Map.get(re.Id).Cycle_between_failure__c == null ? 0 :Integer.valueOf(repair2Map.get(re.Id).Cycle_between_failure__c);
              // cumulativeTimes += repair2Map.get(re.Id).Cumulative_Times__c == null ? 0 :Integer.valueOf(repair2Map.get(re.Id).Cumulative_Times__c/60);
               cumulativeTimes += repair2Map.get(re.Id).Average_Usage_Time__c == null ? 0 :Integer.valueOf(repair2Map.get(re.Id).Average_Usage_Time__c); // WYL 2023-11-20 update
               // 新增 年均使用例数 两次维修间隔的使用例数➗间隔的检查日期（之差）*365 WYL 2023-11-20 start
               if (repair2Map.get(re.Id).Difference_in_repair_intervals__c != null && repair2Map.get(re.Id).Difference_in_repair_intervals__c != 0 ) {
                 Numberofcases += repair2Map.get(re.Id).Cycle_between_failure__c == null ? 0 : repair2Map.get(re.Id).Cycle_between_failure__c/repair2Map.get(re.Id).Difference_in_repair_intervals__c * 365;
                 NumberofcasesNum++;
               }
               // 新增 年均使用例数 两次维修间隔的使用例数➗间隔的检查日期（之差）*365 WYL 2023-11-20 end
              }
            }
            System.debug('共有：'+repairList.size()+'条数据，其中有'+cbfNum+'条数据为第一条;第一条数据的总和：'+cbfSum);
          repairCNMap.put(ast,overhaul);
          // repairPRMap.put(ast,overhaulPrice);
          repairPRMap.put(ast,overhaulPrice);
          // repairUsesMap.put(ast,users);
          // repairUsesMap.put(ast,cbf-cbfSum);// WYL 2024/1/10 update
          if (cbf-cbfSum > 0 ) {
            repairCBFMap.put(ast,(cbf-cbfSum)/(repairList.size()-cbfNum));
            repairUsesMap.put(ast,cbf-cbfSum);// WYL 2024/1/10 update
          }else {
            repairCBFMap.put(ast,0);
            repairUsesMap.put(ast,0);// WYL 2024/1/10 update
          }
          if (cumulativeTimes >0) {
            repairCTimesMap.put(ast,cumulativeTimes/repairList.size());
          }else {
            repairCTimesMap.put(ast,0);
          }
          if (Numberofcases != 0 && NumberofcasesNum != 0) {
            NumberofcasesMap.put(ast, Numberofcases/NumberofcasesNum);
          }else {
            NumberofcasesMap.put(ast, 0);
          }
         
          }  
        }
      }
      
        system.debug('存储医院ID和大修次数'+repairCNMap);
        system.debug('存储医院ID和大修金额'+repairPRMap);
        system.debug('存储医院ID和通电次数'+repairUsesMap);
        system.debug('存储医院ID和CBF'+repairCBFMap);
        system.debug('存储医院ID和通电时间'+repairCTimesMap);

      String hpAssetSring = null;
      Map <String,Integer> assetCountMap = new Map <String,Integer> ();//保有设备型号和设备数量
      if (assetModelAllList.size()>0) {
        AggregateResult[] assetAllList = [select count(Id) ids,Product2.Asset_Model_No__c ass,Hospital__c from Asset where Id != null
                    AND Hospital__c in : accountIDList
                    AND Status in ('使用中','未使用','不明')
                    group by Product2.Asset_Model_No__c,Hospital__c
                    ];//通过医院和保有设备型号找出医院下所有的设备数量
      for (AggregateResult ast : assetAllList){
        hpAssetSring = String.valueOf(ast.get('Hospital__c')) + String.valueOf(ast.get('ass'));
        assetCountMap.put(hpAssetSring,Integer.valueOf(ast.get('ids')));
                system.debug('医院11111'+hpAssetSring);
                system.debug('保有设备1111'+assetCountMap);
      }
            
            
      }

      if (accountIDList.size()>0) {
        for (ID acc3 : accountIDList){
          if (assetModelAllList.size()>0){
            for(String ast : assetModelAllList){
                        if (acc3 == ast.substring(0,18)){
                            ChoiceAssetDetailedInfo cdinfo = new ChoiceAssetDetailedInfo();
                            cdinfo.HPid = acc3;
                            cdinfo.HPName = accountMap.get(acc3);
                            cdinfo.AstModel = ast.substring(18,ast.length());
                            // cdinfo.Endoscope = assetCountMap.get(acc3+ast); //内镜件数
                            // cdinfo.Overhaul = assetMap.get(acc3+ast);       //大修件数
                            cdinfo.Endoscope = assetCountMap.get(ast); //内镜件数
                            cdinfo.Overhaul = assetMap.get(ast);       //大修件数
                            cdinfo.OverhaulPrice = repairPRMap.get(ast);    //大修报价
                            cdinfo.OverhaulvagPrice = repairCNMap.get(ast) == 0 ? 0 : Math.ceil(repairPRMap.get(ast)/repairCNMap.get(ast));
                            cdinfo.Users = repairUsesMap.get(ast);
                            cdinfo.CBF = repairCBFMap.get(ast);
                            // cdinfo.YearVagCBF = Integer.valueOf(repairUsesMap.get(ast)/yearCount);
                            cdinfo.YearVagCBF =  Math.ceil(NumberofcasesMap.get(ast)); // WYL ID信息分析逻辑 add 
                            // cdinfo.MinuteVagCBF = repairUsesMap.get(ast) == 0 ? 0 : Integer.valueOf(repairCTimesMap.get(ast)/repairUsesMap.get(ast));
                            cdinfo.MinuteVagCBF = repairUsesMap.get(ast) == 0 ? 0 : Math.ceil(Decimal.valueOf(repairCTimesMap.get(ast)));
                            cdinfo.UsersVagPrice = repairUsesMap.get(ast) == 0 ? 0 : Math.ceil(repairPRMap.get(ast)/repairUsesMap.get(ast));
                            if (!choiceAssetDetailedview.contains(cdinfo)) {
                                choiceAssetDetailedview.add(cdinfo);
                            }
                        }
              
            }

          }
          system.debug('11111111111111111111111页面数量'+choiceAssetDetailedview.size());
        }
        
      }

    }
}