public with sharing   class OpportunityService{

  private static String opp_search_field = ' Id, Name, Account_Name_F__c, OwnerId, Hospital__c, Opportunity_No__c, Opportunity_stage__c, StageName__c, Bidding_Project_Name_Bid__c, Department_Class__r.RecordTypeId ';
  
  // 查询已保存的数据  
  //noStr 询价的ID
  //daccountID 客户的ID 现在没用
  // IdStr 招投标的ID
  //hospital 医院的ID
  @AuraEnabled
  public  static string GetNormalProductDataSearch(String noStr,String accountId,String IdStr,String hospital,String[] hospitalArr, String departments) {

    String sql = 'select ';
    // sql += CommonUtils.GetSqlToPorps(Opportunity.SObjectType);
    sql += opp_search_field;
    sql += ' from Opportunity';
    // 多对多关系 去掉未关联的判断 start
    // sql += ' where Bidding_Project_Name_Bid__c = null ';
    sql += ' where id != null ';
    // 多对多关系 去掉未关联的判断 end
    if(noStr != null && noStr != '' && noStr != ' ')
    {
      sql += ' and Opportunity_No__c = :noStr';
    }

    if(hospitalArr!= null && hospitalArr.size() > 0)
    {
      sql += ' and Hospital__c in :hospitalArr';
    }
    if(hospital != null && hospital != '' && hospital != ' ')
    {
      sql += ' and Hospital__c = :hospital';
    }

    // String paremt1 = '012100000006KMe';
    // String paremt2 = '01210000000QekK';
    // String paremt3 = '引合';
    // sql += ' and (recordtypeid = :paremt1 or recordtypeid = :paremt2) and stagename = :paremt3 ';
    sql += ' and recordtype.developername in (\'Opportunity\',\'SI_Oppor\') and Hospital__r.Is_Active__c = \'有効\' '+
        // 这里有修改，别给盖了
    ' and ( (SAP_Send_OK__c = true and SAP_Send_OK_Date__c   = LAST_N_DAYS:183  ) '+
        'or( stagename = \'敗戦\' and Final_Contract_Proceeded_Date__c = LAST_N_DAYS:183  ) or stagename = \'引合\' ) ';
      // 这里有修改，别给盖了
    // 20210914 战略科室修改
    //if (departments != null && String.isNotBlank(departments)) {
    //  String[] depart_types = departments.split(';');
    //  if (depart_types != null && depart_types.size() > 0 && depart_types.size() < 6) {
    //    sql += ' and Department_Class__r.RecordTypeId in :depart_types ';
    //  }
    //}
    // 20210914 战略科室修改
    // 去掉已经关联的招标
    if(IdStr != null && String.isNotBlank(IdStr)) {
      sql += ' and id not in (select Opportunity__c from Tender_Opportunity_Link__c where Tender_information__c = :IdStr) ';
    }
    // 20221014 ljh SWAG-CK28WT add start
    String proId = UserInfo.getProfileId();
    String p_2M4 = System.Label.ProfileId_2M4;
    if(proId.substring(0,15) == p_2M4.substring(0,15)){
       sql += ' AND OwnerId =\''+UserInfo.getUserId()+'\'';
    }
    System.debug('sql:'+sql);
    // 20221014 ljh SWAG-CK28WT add end
    sql += '  limit 50';
    List<Opportunity> arrays = Database.query(sql);
    return JSON.serialize(arrays); 
    
  }
 
 // 查询未保存的数据  
  // IdStr 招投标的ID
  //hospital 医院的ID
  @AuraEnabled
  public  static string GetNormalProductDataNotSave(String IdStr,String[] hospital, String departments) {

    //TODU
    // QueryWrapper query = new QueryWrapper(Tender_information__c.SObjectType);
    // query.eq('Id',IdStr);

    // 招标-询价关联修改 20210813 start
    String sql = 'select ';
    // sql += CommonUtils.GetSqlToPorps(Opportunity.SObjectType);
    sql += opp_search_field;
    sql += ' from Opportunity';
    // 多对多关系 去掉未关联的判断 start
    // sql += ' where Bidding_Project_Name_Bid__c = null ';
    // 多对多关系 去掉未关联的判断 end
    // String paremt1 = '012100000006KMe';
    // String paremt2 = '01210000000QekK';
    // String paremt3 = '引合';
    // sql += ' and (recordtypeid = :paremt1 or recordtypeid = :paremt2) and stagename = \'引合\' ';
    // sql += ' and recordtype.developername in (\'Opportunity\',\'SI_Oppor\') and Hospital__r.Is_Active__c = \'有効\' '+
    sql += ' where recordtype.developername in (\'Opportunity\',\'SI_Oppor\') and Hospital__r.Is_Active__c = \'有効\' '+
        // 这里有修改，别给盖了
    ' and ( (SAP_Send_OK__c = true and SAP_Send_OK_Date__c   = LAST_N_DAYS:183 ) '+
        'or( stagename = \'敗戦\' and Final_Contract_Proceeded_Date__c = LAST_N_DAYS:183  ) or stagename = \'引合\' ) ';
      // 这里有修改，别给盖了
    // 去掉已经关联的招标
    if(IdStr != null && String.isNotBlank(IdStr)) {
      sql += ' and id not in (select Opportunity__c from Tender_Opportunity_Link__c where Tender_information__c = :IdStr) ';
    }
    // 20210914 战略科室修改
    //if (departments != null && String.isNotBlank(departments)) {
    //  String[] depart_types = departments.split(';');
    //  if (depart_types != null && depart_types.size() > 0 && depart_types.size() < 6) {
    //    sql += ' and Department_Class__r.RecordTypeId in :depart_types ';
    //  }
    //}
    // 20210914 战略科室修改
    if(hospital!= null && hospital.size() > 0)
    {
      sql += ' and Hospital__c in :hospital';
    }
    // 20221014 ljh SWAG-CK28WT add start
    String proId = UserInfo.getProfileId();
    String p_2M4 = System.Label.ProfileId_2M4;
    if(proId.substring(0,15) == p_2M4.substring(0,15)){
       sql += ' AND OwnerId =\''+UserInfo.getUserId()+'\'';
    }
    System.debug('sql:'+sql);
    // 20221014 ljh SWAG-CK28WT add end
    sql += '  limit 50';
    List<Opportunity> arrays = Database.query(sql);

    // Tender_information__c
    return JSON.serialize(arrays); 
    
    // 招标-询价关联修改 20210813 end
  }





  //查询已保存
  // 只有一个 当前招投标
  //IdStr 招投标的ID
  @AuraEnabled
  public  static string GetNormalProductDataIsSave(String IdStr) {
    // 招标-询价关联修改 20210817 start
    // 查询方式或许应该优化一下
    // QueryWrapper query = new QueryWrapper(Opportunity.SObjectType);
    // query.eq('Bidding_Project_Name_Bid__c', IdStr);
    // List<Opportunity> arrays = DataBasePlus.listPlus(query);
    List<Id> oppIds = new List<Id>();
    List<Tender_Opportunity_Link__c> links = [select Opportunity__c from Tender_Opportunity_Link__c where Tender_information__c = :IdStr];
    if (links != null && links.size() > 0) {
      for (Tender_Opportunity_Link__c link : links) {
        oppIds.add(link.Opportunity__c);
      }
    }
    // String sql = 'select ' + CommonUtils.GetSqlToPorps(Opportunity.SObjectType) + ' from Opportunity ';
    String sql = 'select ' + opp_search_field + ' from Opportunity ';
    sql += 'where Id in :oppIds';
    List<Opportunity> arrays = Database.query(sql);
    // 招标-询价关联修改 20210817 end
    return JSON.serialize(arrays); 
  }
   


  
  //保存
   //JsonSelected JSON格式的招投标的已选择数据集合
   //JsonNotSelected JSON格式的招投标的未选择数据集合
   // BiddingId 对应的招标项目名（招投标）
   // flag  修改 招投标项目 关联询价时间的一个标识
  @AuraEnabled
  public  static string SaveData(String JsonSelected,String JsonNotSelected,String BiddingId,Boolean flag) {

    try{
      // 新增招标-询价关联关系表，去掉更新询价上的最新招标信息 20210813 start
      // if(JsonSelected != null &&  JsonSelected != '' && JsonSelected !='[]')
      // {
      //   List<Opportunity> SelectedList = (List<Opportunity>)JSON.deserialize(JsonSelected,List<Opportunity>.class);

      //   for(Opportunity item :SelectedList){
      //     item.Bidding_Project_Name_Bid__c = null;
      //   }
       

              
      // Database.update(SelectedList,false);
      // }
      // string OppOwnerId = '';
      // if(JsonNotSelected != null &&  JsonNotSelected != '' && JsonNotSelected !='[]')
      // {
      //   List<Opportunity> NotSelectedList = (List<Opportunity>)JSON.deserialize(JsonNotSelected,List<Opportunity>.class);

      //   for(Opportunity item :NotSelectedList){
      //     item.Bidding_Project_Name_Bid__c = BiddingId;
      //   }
      //   OppOwnerId = NotSelectedList[0].ownerId;
      //   Database.update(NotSelectedList);
      // }
      // if(flag != null && flag == true)
      // {
      //   string tenProp = CommonUtils.GetSqlToPorps(Tender_information__c.SObjectType);
      //   String sql = 'select '+tenProp+' from Tender_information__c  where Id = :BiddingId';
      //   List<Tender_information__c> arrays = Database.query(sql);
      //   arrays[0].RelateOppTime__c = datetime.now();
      //   //if( arrays[0].IsBid__c == null && OppOwnerId != '')
      //   //{
      //   //  arrays[0].ownerId = OppOwnerId;
      //   //}
      //   if (arrays != null && arrays.size() >0 &&
      //   (arrays[0].ownerId == '00510000005sEEM' || arrays[0].ownerId == '00510000000gmxH')
      //   && OppOwnerId != '')
      //   {
      //     arrays[0].ownerId = OppOwnerId;
      //   }
      //   Database.update(arrays);
      // }
      // 新增招标-询价关联关系表，去掉更新询价上的最新招标信息 20210813 end

      // 招标-询价关联修改 20210813 start
      // 查询招标
      // string tenProp = CommonUtils.GetSqlToPorps(Tender_information__c.SObjectType);
      // String sql = 'select '+tenProp+' from Tender_information__c  where Id = :BiddingId';
      String sql = 'SELECT ';
      sql += 'Id, ';
      sql += 'NotBidApprovalStatus__c, ';
      sql += 'IsBid__c, ';
      sql += 'TenderBeginTime__c, ';
      sql += 'InfoType__c, ';
      sql += 'OwnerId, ';
      sql += 'IsReactionOpp__c, ';
      sql += 'IsRelateProject__c, ';
      sql += 'RelateOppTime__c, ';
      sql += 'irrelevantReasons__c, ';
      sql += 'irrelevantReasonOther__c, ';
      sql += 'Hospital__c, ';
      sql += 'Hospital1__c, ';
      sql += 'Hospital2__c, ';
      sql += 'Hospital3__c, ';
      sql += 'Hospital4__c, ';
      sql += 'publicDate__c, ';// 20221114 ljh SWAG-CKL5UC
      sql += 'Tender_Order__c, ';  //20220620 you SWAG-CFD4SU 
      sql += 'subInfoType__c ';  //20220718 you 招标任务 
      sql += 'FROM Tender_information__c  WHERE Id = :BiddingId order by Tender_Order__c desc,relativeTime_F__c desc'; //20220620 you SWAG-CFD4SU 增加 order by
      List<Tender_information__c> arrays = Database.query(sql);
      Tender_information__c tender = arrays[0];
      
      // 不应标申请中的时候 调回申请修改 20210907 start
      if (tender.NotBidApprovalStatus__c != null && tender.NotBidApprovalStatus__c == '申请中') {
        List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest> ();
        ProcessInstance pi = [Select Id, SubmittedById from ProcessInstance where TargetObjectId = :tender.Id and Status = 'Pending' order by CreatedDate desc limit 1];
        if (pi != null) {
          for(ProcessInstanceWorkItem wi : [Select Id from ProcessInstanceWorkItem where ProcessInstanceId = :pi.Id]){
            Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
            if (pi.SubmittedById.equals(Userinfo.getUserId())) {
              req2.setAction('Removed');
              tender.NotBidApprovalStatus__c = '草案中';
            } else {
              req2.setAction('Reject');
              tender.NotBidApprovalStatus__c = '驳回';
              tender.IsBid__c = null;
            }
            req2.setWorkitemId(wi.Id);
            requests.add(req2);
          }
          system.debug('==requests.size()=='+requests.size());
          if (requests.size() > 0) {
            Approval.ProcessResult[] processResults = null;
            processResults = Approval.process(requests, true);
            system.debug('==调回结果=='+processResults);
          }
        }
      }
      // 不应标申请中的时候 调回申请修改 20210907 end
      
      // 合并已关联和未关联列表
      List<Opportunity> all_selected_list = new List<Opportunity>();
      if (JsonSelected != null &&  JsonSelected != '' && JsonSelected !='[]') {
        all_selected_list.addAll((List<Opportunity>)JSON.deserialize(JsonSelected,List<Opportunity>.class));
      }
      if (JsonNotSelected != null &&  JsonNotSelected != '' && JsonNotSelected !='[]') {
        all_selected_list.addAll((List<Opportunity>)JSON.deserialize(JsonNotSelected,List<Opportunity>.class));
      }
      // 招标所有人是否要修改flag
      // boolean owner_change = false;
      // 先删除旧的link
      // 跳过trigger标记
      // 没有删除逻辑
      StaticParameter.EscapeTOLinkTrigger = true;
      // List<Tender_Opportunity_Link__c> del_links = [select Id from Tender_Opportunity_Link__c where Tender_information__c = :BiddingId];
      // if (del_links != null && del_links.size() > 0) {
      //   delete del_links;
      // }
      // 更新询价
      List<Opportunity> upd_opps = new List<Opportunity>();
      List<Opportunity> upd_opps1 = new List<Opportunity>();
      List<String> owners = new List<String>();
      // 插入link
      if (all_selected_list.size() > 0) {
        // 设置招标所有人
        // OppOwnerId = all_selected_list[0].ownerId;
        // 初始化参数
        List<Tender_Opportunity_Link__c> add_list = new List<Tender_Opportunity_Link__c>();
        // 当询价关联过结果阶段的招标项目，再被另一个结果阶段的招标项目关联时，会因为数据被锁定而报错
        // 在此处重新检索询价
        List<String> oppIds = new List<String>();
        for (Opportunity opp : all_selected_list) {
          oppIds.add(opp.Id);
          owners.add(opp.ownerId);
          // 新建link
          Tender_Opportunity_Link__c link = new Tender_Opportunity_Link__c();
          link.Tender_information__c = tender.Id;
          link.Opportunity__c = opp.Id;
          link.Tender_Opportunity_Uniq__c = String.valueOf(tender.Id) + String.valueOf(opp.Id);

          add_list.add(link);
        }
        // 插入link
        if (add_list.size() > 0) {
          insert add_list;
        }
        // 恢复trigger标记
        StaticParameter.EscapeTOLinkTrigger = false;
        //20220620 you SWAG-CFD4SU 改造 start  始终显示最新的 ① 3：结果,② 4：变更,③ 2：公告,④ 1：预告,⑤ 5：其他 
        List<String> tenIds = new List<String>();//20220718 you 招标任务
        system.debug('opportunityservicetest'+oppIds);
        if (oppIds.size() > 0) {
          // 20221114 SWAG-CKL5UC ljh 增加 Created_Day__c,LeadSource,LeakageNumber__c
          List<Opportunity> wait_upd_opps = [select id,Opp_Order__c,Tender_Number__c, Bidding_Project_Name_Bid__c, Bidding_Project_Name_Bid__r.InfoType__c,Created_Day__c,LeadSource,LeakageNumber__c from Opportunity where id in :oppIds ];//and Bidding_Project_Name_Bid__r.InfoType__c != '3：结果'];
          if (wait_upd_opps != null && wait_upd_opps.size() > 0) {
            for (Opportunity opp : wait_upd_opps) {
              /**
              if (opp.Bidding_Project_Name_Bid__c == null || String.isBlank(opp.Bidding_Project_Name_Bid__c)) {
                opp.Bidding_Project_Name_Bid__c = tender.Id;
                opp.TenderBeginDate_Text__c = tender.TenderBeginTime__c;
                upd_opps.add(opp);
              } else if (tender.InfoType__c == '3：结果' && opp.Bidding_Project_Name_Bid__r.InfoType__c != '3：结果') {
                opp.Bidding_Project_Name_Bid__c = tender.Id;
                upd_opps.add(opp);
              }
              **/
              if(opp.Opp_Order__c <= tender.Tender_Order__c){
                opp.Bidding_Project_Name_Bid__c =tender.Id;
                //opp.TenderBeginDate_Text__c = tender.TenderDate__c;//更改询价2时修改这个字段，引用超20，tender.TenderBeginTime__c;
                upd_opps.add(opp);
                //20220715 you 招标项目 start
                if(String.isNotBlank(tender.InfoType__c) && tender.InfoType__c=='3：结果' && String.isNotBlank(tender.subInfoType__c) && (tender.subInfoType__c=='3-5：中标通知' || tender.subInfoType__c=='3-6：合同公告')){
                  tenIds.add(opp.id); //符合条件生成任务
                }
                //20220715 you 招标项目 end
                break;
              }

            }
            //20220829 you SWAG-CHL67J start
            for (Opportunity opp : wait_upd_opps) {
              Integer returncount =0;
              if(String.isNotBlank(tender.InfoType__c) && tender.InfoType__c!='1：预告' && String.isNotBlank(tender.subInfoType__c) && tender.subInfoType__c!='3-1：废标公告' && tender.subInfoType__c!='3-2：流标公告'){  
                  returncount += 1;
                }
              opp.Tender_Number__c = returncount;
              // 20221114 ljh SWAG-CKL5UC start 
              if(opp.LeakageNumber__c != 1 && tender.publicDate__c != null && String.isNotBlank(opp.LeadSource) && opp.LeadSource == '招标网' && opp.Created_Day__c > tender.publicDate__c){
                opp.LeakageNumber__c = 1;
              }
              // 20221114 ljh SWAG-CKL5UC start 
              upd_opps1.add(opp);  
            }  
                 
            //20220829 you SWAG-CHL67J end 
          }
        }
        if (upd_opps1.size() > 0) {
          update upd_opps1;
        }
        //20220620 you SWAG-CFD4SU 改造 end
        // 更新询价上的招标项目
        if (upd_opps.size() > 0) {
          update upd_opps;
        }
         //20220718 you 招标任务 start
                             
        if (tenIds !=null && tenIds.size() > 0) {
            Database.executeBatch(new TenderResultConfirmTaskBatch(tenIds));
          }
          //20220718 you 招标任务 end
      }

      // 查询招标数量并更新
      List<Tender_Opportunity_Link__c> tenderLinks = [SELECT id, Tender_information__c, Opportunity__c, Opportunity__r.Hospital__c, Opportunity__r.OwnerId FROM Tender_Opportunity_Link__c WHERE Tender_information__c = :tender.Id];
      List<String> oppOwnerInLinks = new List<String>();
      for (Tender_Opportunity_Link__c link : tenderLinks) {
        oppOwnerInLinks.add(link.Opportunity__r.OwnerId);
      }
      // 更新招标上的所有人
      if (tender.OwnerId == null || '00510000000gmxH'.equals(tender.OwnerId) || (oppOwnerInLinks.size() > 0 && !oppOwnerInLinks.contains(tender.OwnerId))) {
        tender.ownerId = owners.size() > 0 ? owners.get(0) : '00510000000gmxH';
      }
      // 反映询价状态
      tender.IsReactionOpp__c = true;
      // 查询招标数量并更新
      //List<Tender_Opportunity_Link__c> tenderLinks = [SELECT id, Tender_information__c, Opportunity__c, Opportunity__r.Hospital__c FROM Tender_Opportunity_Link__c WHERE Tender_information__c = :tender.Id];
      tender.OpportunityNum__c = tenderLinks != null ? tenderLinks.size() : 0;
      // 关联询价时间和是否相关状态
      if (tender.IsRelateProject__c != '是') {
        tender.IsRelateProject__c = '是';
        tender.RelateOppTime__c = datetime.now();
        tender.irrelevantReasons__c = null;
        tender.irrelevantReasonOther__c = null;
      }
      // 更新关联医院
      if (tenderLinks != null && tenderLinks.size() > 0) {
        // 招标项目的医院
        Map<String,String> fiveHospitalMap = new Map<String,String>();
        fiveHospitalMap.put('Hospital__c', tender.Hospital__c);
        fiveHospitalMap.put('Hospital1__c', tender.Hospital1__c);
        fiveHospitalMap.put('Hospital2__c', tender.Hospital2__c);
        fiveHospitalMap.put('Hospital3__c', tender.Hospital3__c);
        fiveHospitalMap.put('Hospital4__c', tender.Hospital4__c);
        for(Integer i = 0; i<tenderLinks.size();i++) {
          //当招投标项目的五个医院赋值完成后不再赋值
          Boolean HospitalIsNeedBreak = false;
          for(String ApiName :fiveHospitalMap.keySet()){
              HospitalIsNeedBreak = fiveHospitalMap.get(ApiName)==null?false:true;
          }
          
          if(HospitalIsNeedBreak){
              break;
          }

          //给招投标项目的5个医院设值
          for(String ApiName : fiveHospitalMap.keySet()){
            String tempTenderHospId = fiveHospitalMap.get(ApiName)==null?'':fiveHospitalMap.get(ApiName);
            String oppHospId = tenderLinks.get(i).Opportunity__r.Hospital__c; 
            //如果招标项目已经有该医院就判断下一个询价的医院
            if(tempTenderHospId.contains(oppHospId)){
                break;
            }

            //医院为空,赋值医院(赋值之后进行赋值下一个医院)
            if(String.isBlank( fiveHospitalMap.get(ApiName) )){
                fiveHospitalMap.put(ApiName,oppHospId);
                break;
            }
          }
        }
        tender.Hospital__c = fiveHospitalMap.get('Hospital__c');
        tender.Hospital1__c = fiveHospitalMap.get('Hospital1__c');
        tender.Hospital2__c = fiveHospitalMap.get('Hospital2__c');
        tender.Hospital3__c = fiveHospitalMap.get('Hospital3__c');
        tender.Hospital4__c = fiveHospitalMap.get('Hospital4__c');
      }
      update tender;
      // 招标-询价关联修改 20210813 end
      return '成功'; 
    }catch (Exception ex) {
      return  ex.getMessage();
    }

  }
}