// 20240226 ssm 2S6-2无法覆盖2S6-1创建的报价计算结果，改成without sharing
public without sharing class QuoteTrialController{

     public static String ParamId;
       //获取 报价数据
    @AuraEnabled
    public static  String GetQuoteData(String QuoteID) {

         List<Quote> arrays = Database.query(' select id,Agent1_Agent2_Price__c,Dealer_Final_Price_F__c,Quote_Decision__c,Opportunity.Trade__c,Opportunity.Sales_Root__c,Opportunity.IsAuthorized__c,Opportunity.RecordType.DeveloperName,Agency1__c,multiYearWarranty__c from Quote where Id = :QuoteID ');
    
         return JSON.serialize(arrays);
    }

    //获取待选择产品 
    @AuraEnabled
    public static  List<QuoteLineItem>  GetPromotionDefalut(String IdParam) {
     //     QueryWrapper query = new QueryWrapper(QuoteLineItem.SObjectType);
     //     query.eq('Quoteid', IdParam);
          List<QuoteLineItem> repeatarray = new List<QuoteLineItem>();
          // List<String> arrayId = new List<String>();
          Map<String,QuoteLineItem> map1 = new Map<String,QuoteLineItem>();
          string sql = 'select ';
          String props = CommonUtils.GetSqlToPorps(QuoteLineItem.SObjectType);
          sql += props;
          sql +=' ,Product2.Intra_Trade_List_RMB__c,Product2.Intra_Trade_Service_RMB__c,Product2.Foreign_Trade_List_US__c,Product2.NoDiscount_Foreign__c,Product2.MDM_Model_No__c ';
          sql += ' from QuoteLineItem where Quoteid = :IdParam ';
          List<QuoteLineItem> arrays = Database.query(sql);
          for(QuoteLineItem pspsc :arrays){
               QuoteLineItem quoteLine = new QuoteLineItem();
               if(map1.containsKey(pspsc.Product2Id)){
                    quoteLine = map1.get(pspsc.Product2Id);
                    quoteLine.Quantity +=pspsc.Quantity;
                    map1.put(pspsc.Product2Id,quoteLine);
               }else{
                    map1.put(pspsc.Product2Id,pspsc);
               }
          }
          for (QuoteLineItem value : map1.values()) {
               repeatarray.add(value);
          }
         return repeatarray;
    }
    //获取经销商姓名
    @AuraEnabled
    public static  String GetAgencyRName() {

         List<PromotionHead__c> arrays = Database.query(' select id,Agency__r.name,Agency__c from PromotionHead__c');
    
         return JSON.serialize(arrays);
    }
//     @AuraEnabled
//     public static  List<QuoteLineItem>  GetPromotionQuoteLineItem() {
//         string Quoteid = '0Q01s0000005KoJ';
//         List<QuoteLineItem> result = Database.query(' select id,Product2.Asset_Model_No__c,Product2.Name,Quantity,GuranteeType__c,ListPrice,AgencyUnitPrice__c,AgencySubtotal__c,NoDiscountTotal__c from  QuoteLineItem where Quoteid = :Quoteid  ');
//         System.debug(result.size()+'');
//         return result;
//    }

   //获取 促销方案
//    @AuraEnabled
//    public static  List<PromotionHead__c>  GetPromotionPromotion() {
//         QueryWrapper query = new QueryWrapper(PromotionHead__c.SObjectType);
//         query.eq('recordtype.developername', 'Promotion');
//         List<PromotionHead__c> arrays = DataBasePlus.listPlus(query);
//         return arrays;
//    }

    //获取 促销方案 搜索 Integer page, Integer pageLimit,String search,String sortOrder,String sortPlus
    @AuraEnabled
    public  static string GetPromotionPromotionSearch(Integer page, Integer pageLimit,String search,String sortOrder,String sortPlus) {
     QuoteTrialService dao =  new QuoteTrialService();
       String[] arrTest = new String[] {'PromotionNo__cEqual','NameLike'}; 
       PagePlus pages = dao.GetPromotionPromotionSearchFn(page,pageLimit,search,sortOrder,sortPlus,arrTest);  
       System.debug(pages);
       return JSON.serialize(pages);
     // return DataBasePlus.Mysql;
    }

   //获取 固定资产 
//    @AuraEnabled
//    public static  List<PromotionHead__c>  GetPromotionNormalProduct() {
//         QueryWrapper query = new QueryWrapper(PromotionHead__c.SObjectType);
//         query.eq('recordtype.developername', 'NormalProduct');
//         List<PromotionHead__c> arrays = DataBasePlus.listPlus(query);
//         return arrays;
//    }


   
    //获取 固定资产 搜索 Integer page, Integer pageLimit,String search,String sortOrder,String sortPlus
    @AuraEnabled
    public  static string GetNormalProductSearch(Integer page, Integer pageLimit,String search,String sortOrder,String sortPlus) {
     QuoteTrialService dao =  new QuoteTrialService();
       String[] arrTest = new String[] {'PromotionNo__cEqual','NameLike'}; 
       PagePlus pages = dao.GetNormalProductSearchFn(page,pageLimit,search,sortOrder,sortPlus,arrTest);  

     
       
       QueryWrapper query = new QueryWrapper(PromotionHead__c.SObjectType);
       query.eq('recordtype.developername', 'NormalProduct');
       List<PromotionHead__c> arrays = DataBasePlus.listPlus(query);
     
       return JSON.serialize(pages) + '--' + JSON.serialize(arrays);
     // return DataBasePlus.Mysql;
    }


    //获取 特约折扣 搜索 Integer page, Integer pageLimit,String search,String sortOrder,String sortPlus
//     select id, recordtype.developername, Name from PromotionHead__c where recordtype.developername = 'Authorizer'
    @AuraEnabled
    public  static string GetAuthorizerSearch(Integer page, Integer pageLimit,String search,String sortOrder,String sortPlus,String Agency1c) {
     QuoteTrialService dao =  new QuoteTrialService();
       String[] arrTest = new String[] {'PromotionNo__cEqual','NameEqual'}; 
       PagePlus pages = dao.GetAuthorizerSearchFn(page,pageLimit,search,sortOrder,sortPlus,arrTest,Agency1c);  
       return JSON.serialize(pages);
     // return DataBasePlus.Mysql;
    }
    
    

     //获取 产品对应的Item
     @AuraEnabled
     public  static  List<PromotionProduct__c>  GetSearchProductById(String SearchId) {
          QueryWrapper query = new QueryWrapper(PromotionProduct__c.SObjectType);
          query.eq('PromotionHead__c', SearchId);
          List<PromotionProduct__c> arrays = DataBasePlus.listPlus(query);
          return arrays;
     }
     //获取所有PromotionSales__c表中的数据
     @AuraEnabled
     public  static  List<PromotionSales__c>  selectAllDataProduct(String ParamIdStr) {
          QueryWrapper query = new QueryWrapper(PromotionSales__c.SObjectType);
          query.eq('Quote__c', ParamIdStr);
          List<PromotionSales__c> arrays = DataBasePlus.listPlus(query);
          return arrays;
     }
     //获取所有PromotionSalesProducts__c表中的数据
     @AuraEnabled
     public  static  List<PromotionSalesProducts__c>  selectAllDataDiscount(String ParamIdStr) {

          string sql = 'select ';
          String query = CommonUtils.GetSqlToPorps(PromotionSalesProducts__c.SObjectType);
          sql += query;
          sql +=' ,	Product2__r.Intra_Trade_List_RMB__c,Product2__r.Intra_Trade_Service_RMB__c,Product2__r.Foreign_Trade_List_US__c,Product2__r.NoDiscount_Foreign__c,Product2__r.MDM_Model_No__c ';
          sql += ' from PromotionSalesProducts__c where QuantityId__c = :ParamIdStr ';
          List<PromotionSalesProducts__c> arrays = Database.query(sql);
          return arrays;
     }
     //保存所选方案，价格政策和折扣政策，JsonStr 是要保存的数据的转成的json字符串,ParamIdStr 保存方案表的id
     @AuraEnabled
     public  static  String   saveAllDataProduct(String JsonStr,String ParamIdStr,String JsonStr2,String QuoteId,String SalesRootc,Double ContractPrice,String OpportunityId,Double DealerFinalPriceFc,Double Agent1Agent2Pricec) {
          deleteAll(ParamIdStr);
          // List<GeDatass> lists =  new List<GeDatass>();
          // GeDatass gds =  new GeDatass();
          // gds.head = '11111';
          // lists.add(gds);
          // String jsonStr = Json.serialize(lists);
          // PromotioDao dao =  new PromotioDao();
          // GeDatas ges = (GeDatas) JSON.deserializeStrict(data, GeDatass.class);
          //  List<PromotionSales__c> goodsList = (List<PromotionSales__c>)JSON.deserialize(datass,List<PromotionSales__c>.class);
          /////////////////////////////////////
          List<GeDatass> goodsList = (List<GeDatass>)JSON.deserialize(JsonStr,List<GeDatass>.class);
           List<PromotionSales__c> psc=new List<PromotionSales__c>();
           Map<String,Id> PromotionSalesMap=new Map<String,Id>();
           Map<String,String> ifYiBan=new Map<String,String>();
          //  Map<String,String> YiBanId=new Map<String,String>();
           for(GeDatass itms:goodsList){
               PromotionSales__c sales = new  PromotionSales__c();
               // sales.head_id__c = itms.Id ;
               if(itms.JxsType!='一般折扣'){
                    sales.PromotionHead__c = (Id)itms.Id;
               }
               // else{
               //      // YiBanId.put(itms.Categoryc+itms.NormalDiscountcInput,itms.Categoryc+itms.NormalDiscountcInput);
               //      // YiBanId.put(itms.Categoryc+itms.NormalDiscountcInput,itms.Id);
               // }
               sales.JxsType__c=itms.JxsType;
               sales.Category__c=itms.Categoryc;
               sales.GuaranteeDiscount_c_Input__c=itms.GuaranteeDiscountcInput;
               sales.NormalDiscount_c_Input__c=itms.NormalDiscountcInput;
               sales.PromotionNo_cEqual__c=itms.PromotionNocEqual;
               sales.typess__c=itms.typess;
               sales.PromotionNo__c=itms.PromotionNoc;
               sales.Name=itms.Name;
               sales.itemIdStr__c=itms.itemIdStr;
               sales.IsTempItems__c=itms.IsTempItems;
               sales.itemCounts__c=itms.itemCounts;
               // sales.ParamIdStr__c=itms.ParamIdStr;
               sales.Quote__c=(Id)itms.ParamIdStr;
               sales.GuaranteeDiscount__c=itms.GuaranteeDiscountc;
               sales.NormalDiscountc__c=itms.NormalDiscountc;
               sales.Description__c=itms.Descriptionc;
               sales.if_Contain_Nod__c=itms.ifContainNodc;
               sales.if_Fix__c=itms.ifFixc==null?false:itms.ifFixc;
               sales.ifNecessary__c=itms.ifNecessaryc==null?false:itms.ifNecessaryc;
               sales.Price_CNY__c=itms.PriceCNYc;
               sales.Price_total__c=itms.Total;
               sales.contractPrice__c=itms.HeTongTotal;
               sales.maxCounts__c=itms.maxCounts;
               sales.sumNoDiscountTotal__c=itms.sumNoDiscountTotal;
               sales.GuaranteeDiscount_H_Money__c=itms.GuaranteeDiscountHMoneyc;
               sales.NormalDiscount_H_Money__c=itms.NormalDiscountHMoneyc;
               if(itms.Trade=='内貿'){
                    sales.ListPriceTotal__c=itms.ListPriceTotalc;
                    sales.NodiscountTotal__c=itms.sumNod;
               }else if(itms.Trade=='外貿'){
                    sales.ListPriceTotalUSD__c=itms.ListPriceTotalc;
                    sales.NodiscountTotalUSD__c=itms.sumNod;
               }
               sales.CompareId__c=itms.CompareId;
               // insert(sales);
               psc.add(sales);
           }
           if(psc!=null){
               insert psc;
           }
           for (PromotionSales__c item : psc) {
               
               if(item.typess__c =='折扣政策'){
                    if(item.JxsType__c=='一般折扣'){
                         ifYiBan.put('一般折扣','一般折扣');
                         // PromotionSalesMap.put(YiBanId.get(item.Category__c+item.NormalDiscount_c_Input__c),item.Id);
                         PromotionSalesMap.put(item.Category__c+item.NormalDiscount_c_Input__c,item.Id);
                    }else{
                         // PromotionSalesMap.put(item.PromotionHead__c,item.Id);
                         PromotionSalesMap.put(item.PromotionHead__c+item.GuaranteeDiscount_c_Input__c+item.NormalDiscount_c_Input__c,item.Id);
                    }
               }else{ 
                    PromotionSalesMap.put(item.PromotionHead__c,item.Id);
               }
               // if(item.JxsType__c=='一般折扣'){
               //      ifYiBan.put('一般折扣','一般折扣');
               //      // PromotionSalesMap.put(YiBanId.get(item.Category__c+item.NormalDiscount_c_Input__c),item.Id);
               //      PromotionSalesMap.put(YiBanId.get(item.Category__c+item.NormalDiscount_c_Input__c),item.Category__c+item.NormalDiscount_c_Input__c);
               // }else if(item.typess__c =='折扣政策'){
               //      // PromotionSalesMap.put(item.PromotionHead__c,item.Id);
               //      PromotionSalesMap.put(item.PromotionHead__c+item.GuaranteeDiscount_c_Input__c+item.NormalDiscount_c_Input__c,item.PromotionHead__c+item.GuaranteeDiscount_c_Input__c+item.NormalDiscount_c_Input__c);
               // }else{
               //      PromotionSalesMap.put(item.PromotionHead__c,item.Id);
               //      // PromotionSalesMap.put(item.PromotionHead__c+item.GuaranteeDiscount_c_Input__c+item.NormalDiscount_c_Input__c,item.PromotionHead__c+item.GuaranteeDiscount_c_Input__c+item.NormalDiscount_c_Input__c);
               // }
               System.debug('ifYiBan==='+ifYiBan);
           }
           
           saveAllDataDiscount(JsonStr2,ParamIdStr,PromotionSalesMap,ifYiBan,QuoteId,SalesRootc,ContractPrice,OpportunityId,DealerFinalPriceFc,Agent1Agent2Pricec);
           String TempStr = Json.serialize(goodsList);
           return TempStr;
     }

     //方案类
     public class GeDatass {
          public  String Id;//产品编码(产品代码)
          public String JxsType;
          public String Categoryc;
          public String GuaranteeDiscountcInput;
          public String NormalDiscountcInput;
          public String PromotionNocEqual;
          public String typess;
          public String PromotionNoc;
          public String Name;
          public String itemIdStr;
          public String IsTempItems;
          public String itemCounts;
          public String ParamIdStr;
          public String GuaranteeDiscountc;
          public String NormalDiscountc;
          public String Descriptionc;
          public Boolean ifContainNodc;
          public Boolean ifFixc;
          public Double PriceCNYc;
          public Double Total;
          public Double HeTongTotal;
          public Boolean ifNecessaryc;
          public Decimal maxCounts;
          public Double ListPriceTotalc;
          public Double sumNod;
          public String CompareId;
          public String Trade;
          public String sumNoDiscountTotal;
          public Double GuaranteeDiscountHMoneyc;
          public Double NormalDiscountHMoneyc;
      }
      //判断所处数据是否为空
      @AuraEnabled
      public  static  Boolean  GetParamToId (String Param) {
          ParamId = Param;
          if(ParamId == null || ParamId == '') 
          {
               return false;
          }else
          {
               return true;
          }
          
      }
      //删除方案
      public static  void deleteAll(String ParamIdStr){
          PromotionSales__c salesss = new PromotionSales__c();
          QueryWrapper query = new QueryWrapper(PromotionSales__c.SObjectType);
          query.eq('Quote__c', ParamIdStr);
          List<PromotionSales__c> arrays = DataBasePlus.listPlus(query);
          // for(PromotionSales__c promotion:arrays){
          //      delete(promotion);
          // }
          delete arrays;
          // delete(salesss);
     }
     //测试清空表中数据，非正式环境
     @AuraEnabled
     public static  void deleteAlltable(){
          PromotionSales__c salesss = new PromotionSales__c();
          QueryWrapper query = new QueryWrapper(PromotionSales__c.SObjectType);
          List<PromotionSales__c> arrays = DataBasePlus.listPlus(query);
          for(PromotionSales__c promotion:arrays){
               delete(promotion);
          }
          // delete(salesss);
     }


     
     //获取 产品Head的Item
     // @AuraEnabled
     // public  static  List<PromotionHead__c>  GetSearchHeadById(String SearchId) {
     //      QueryWrapper query = new QueryWrapper(PromotionHead__c.SObjectType);
     //      query.eq('Id', SearchId);
     //      List<PromotionHead__c> arrays = DataBasePlus.listPlus(query);
     //      return arrays;
     // }

     //保存所选产品和未选产品，JsonStr 是要保存的数据的转成的json字符串,ParamIdStrs 保存产品表的id
     // @AuraEnabled
     public  static  void   saveAllDataDiscount(String JsonStrs,String ParamIdStrs,Map<String,Id> PromotionSalesMap,Map<String,String> ifYiBan,String QuoteId,String SalesRootc,Double ContractPrice,String OpportunityId,Double DealerFinalPriceFc,Double Agent1Agent2Pricec) {
          deleteAllDiscount(ParamIdStrs);
          System.debug('DealerFinalPriceFc==='+DealerFinalPriceFc);
         List<Discount> goodsList = (List<Discount>)JSON.deserialize(JsonStrs,List<Discount>.class);
          // System.debug('productmap:'+productmap);
          List<PromotionSalesProducts__c> psp=new List<PromotionSalesProducts__c>();
           for(Discount itms:goodsList){
               PromotionSalesProducts__c saless = new  PromotionSalesProducts__c();
               // String id = '01t10000000TfqC';
               saless.QuoteTrialKey__c =itms.Id ;
               saless.Asset_Model_No__c=itms.AssetModelNoc;
               saless.Name_c__c=itms.Namec;
               saless.Quantity__c=itms.Quantity;
               saless.GuranteeType__c=itms.GuranteeTypec;
               saless.PromotionNo__c=itms.PromotionNoc;
               saless.Name__c=itms.Name;
               saless.ListPrice__c=itms.ListPrice;
               saless.AgencyUnitPrice__c=itms.AgencyUnitPricec;
               saless.AgencySubtotal__c=itms.AgencySubtotalc;
               saless.NoDiscountTotal__c=itms.NoDiscountTotalc;
               // saless.ParamIdStr__c=itms.ParamIdStr;
               saless.QuantityId__c=(Id)itms.ParamIdStr;
               saless.TypeName__c=itms.TypeName;
               // saless.UUID__c=itms.UUID;
               saless.ismatch__c=itms.ismatch;
               // String ifYiBans=ifYiBan.get(itms.Name);
               // saless.PromotionSales__c=(Id)PromotionSalesMap.get(itms.PromotionId);
               if(itms.Name!='一般折扣'){
                    saless.Promotion_id__c=(Id)itms.PromotionId;
                    //
                    if(itms.TypeName=='折扣政策'){
                         saless.PromotionSales__c=(Id)PromotionSalesMap.get(itms.PromotionId+itms.GuaranteeDiscountcInput+itms.NormalDiscountcInput);
                    }else{
                         saless.PromotionSales__c=(Id)PromotionSalesMap.get(itms.PromotionId);
                    }
               }else{
                    //
                    saless.PromotionSales__c=(Id)PromotionSalesMap.get(itms.Categoryc+itms.NormalDiscountcInput);
               }
               
               saless.UseCount__c=itms.UseCountc;
               saless.Product2__c=(Id)itms.Product2c;
               saless.ServicePrice__c=itms.ServicePricec;
               saless.ifNecessary__c=itms.ifNecessaryc==null?false:itms.ifNecessaryc;
               saless.if_Fix__c=itms.ifFixc==null?false:itms.ifFixc;
               saless.CompareId__c=itms.CompareId;
               saless.DiscountRate__c=itms.DiscountcInput;
               saless.Category__c=itms.Categoryc;
               saless.NormalDiscountcInput__c=itms.NormalDiscountcInput;
               saless.GuaranteeDiscountcInput__c=itms.GuaranteeDiscountcInput;
               saless.multiYearWarranty__c=itms.multiYearWarrantyc;
               // System.debug('Product2:'+saless.Product2__c);
               // insert(saless);
               psp.add(saless);
           }
           if(psp!=null){
               insert psp ;
           }
               // SWAG-CCY65A 2022-04-19 ssm start
               // 在报价计算保存之后，按照报价上的保存逻辑给报价行和询价产品行重新计算一次预测金额
               // Quote quote = new Quote();
               // quote.Id=QuoteId;
               Quote quote = [select Id, 
                                   TotalPrice__c,                   // 总价
                                   Estimation_List_Price__c,        // 标准List价格
                                   MultiYearWarrantyTotalPrice__c   // 多年保合计
                                    // DB202311242191 【报价单】报价单合同金额更新和生成新报价单规则确认和修改 fy start
                                   ,Dealer_Final_Price__c
                                    // DB202311242191 【报价单】报价单合同金额更新和生成新报价单规则确认和修改 fy end
                              from Quote where Id = :QuoteId];
               quote.OCM_Sales_Forecast__c=ContractPrice;
               System.debug('quote:' + quote);

               Opportunity opportunity = new Opportunity();
               opportunity.Id=OpportunityId;
               opportunity.Wholesale_Price__c=ContractPrice;
               System.debug('opportunity:'+opportunity);
               // DB202311242191 【报价单】报价单合同金额更新和生成新报价单规则确认和修改 fy start
               quote.Dealer_Final_Price__c = DealerFinalPriceFc;
               // DB202311242191 【报价单】报价单合同金额更新和生成新报价单规则确认和修改 fy end
               if(SalesRootc.equals('販売店')){
                    //赋值给下面的 合同金额 并置灰不可编辑
                    quote.OCM_Agent1_Price_Page__c=ContractPrice;
                    quote.OCM_Agent1_Price__c=ContractPrice;
                    if(Agent1Agent2Pricec==null){
                         quote.Agency1_Profit__c=DealerFinalPriceFc-ContractPrice;
                         if(DealerFinalPriceFc!=0){
                              quote.Agency1_Profit_Rate__c=(quote.Agency1_Profit__c/DealerFinalPriceFc*100).setScale(2);
                         }
                    }else{
                         quote.Agency1_Profit__c=Agent1Agent2Pricec-ContractPrice;
                         quote.Agency1_Profit_Rate__c=(quote.Agency1_Profit__c/Agent1Agent2Pricec*100).setScale(2);
                    }
                    opportunity.OCM_Agent1_Price__c=ContractPrice;
               }else if(SalesRootc.equals('OCM直接販売')){//OCSM直接销售
                    //赋值给上面的 医院的合同金额 并置灰不可编辑
                    quote.Dealer_Final_Price_Page__c=ContractPrice;
                    quote.Dealer_Final_Price__c=ContractPrice;
                    opportunity.Dealer_Final_Price__c=ContractPrice;
               }
               quote.IsQuoteTrial__c=true;
               if(quote!=null){
                    update quote;
               }
               if(opportunity!=null){
                    update opportunity;
               }
               // 更新报价行和询价产品行
               //OCM売上予測金額(税込) = OCM成約予測金額(税込み) * (小計 / 見積合計)
               System.debug('opportunity.Wholesale_Price__c != null: ' + (opportunity.Wholesale_Price__c != null));
               System.debug('quote.TotalPrice__c  != null: ' + (quote.TotalPrice__c  != null));
               System.debug('quote.TotalPrice__c  > 0: ' + (quote.TotalPrice__c  > 0));
               System.debug('quote:' + quote);
               System.debug('update flag:' + (opportunity.Wholesale_Price__c != null && quote.TotalPrice__c  != null && quote.TotalPrice__c  > 0));
               if (opportunity.Wholesale_Price__c != null && quote.TotalPrice__c  != null && quote.TotalPrice__c  > 0) {
                    System.debug('进入更新行项目操作');
                    // 获取报价行并重新计算报价行的预测金额
                    List<QuoteLineItem> quo_lines = [SELECT 
                                                  Id, 
                                                  TotalPrice__c,          // 总计 ((最新产品定价 + NoDiscount) * 数量)
                                                  OCM_Sales_Forecast__c,  // OCSM売上予測金額（税込み）
                                                  AgencySubtotal__c,      // 经销商小计
                                                  AgencyUnitPrice__c,     // 经销商单价
                                                  GuranteePrice__c,       // 计提金额
                                                  Product_ListPrice__c,   // 最新产品定价
                                                  NoDiscountTotal__c,     // NoDiscount小计
                                                  Quantity                // 数量 
                                                FROM
                                                  QuoteLineItem 
                                                WHERE
                                                  QuoteId = :quote.Id 
                                                AND
                                                  TotalPrice__c > 0];
                    System.debug('quo_lines:' + quo_lines);
                    if (quo_lines != null && quo_lines.size() > 0) {
                         // 更新报价行上的各种值
                         for(QuoteLineItem item : quo_lines) {
                              // 预测成交金额 = 合同总金额 * (行总价 / 报价总价)
                              item.OCM_Sales_Forecast__c = opportunity.Wholesale_Price__c * (item.TotalPrice__c / quote.TotalPrice__c);
                              // 经销商小计 = (合同总金额 - 多年保合计) * (行最新定价总金额 / 标准定价总额) + NoDiscount小计
                              Decimal NoDiscountTotal = item.NoDiscountTotal__c != null ? item.NoDiscountTotal__c : 0;
                              item.AgencySubtotal__c = (opportunity.Wholesale_Price__c - quote.MultiYearWarrantyTotalPrice__c) * (item.Product_ListPrice__c * item.Quantity / quote.Estimation_List_Price__c) + NoDiscountTotal;
                              // 经销商单价 = 经销商小计 / 数量
                              item.AgencyUnitPrice__c = item.Quantity > 0 ? item.AgencySubtotal__c / item.Quantity : item.AgencyUnitPrice__c;
                         }
                         update quo_lines;
                    }
                    // 获取询价产品行并重新计算预测金额
                    List<OpportunityLineItem> opp_lines = [SELECT
                                                  Id,
                                                  TotalPrice__c,             // 总计
                                                  ListPrice_total_price__c,  // 最新ListPrice总额(不含NoDiscount的金额)
                                                  OCM_Sales_Forecast__c,     // OCSM预测成交金额
                                                  AgencySubtotal__c,         // 经销商小计
                                                  AgencyUnitPrice__c,        // 经销商单价
                                                  GuranteePriceSum__c,       // 计提金额合计
                                                  NoDiscountTotal__c,        // NoDiscount小计
                                                  Quantity                   // 数量 
                                                FROM
                                                  OpportunityLineItem
                                                WHERE
                                                  OpportunityId = :opportunity.Id 
                                                AND
                                                  TotalPrice__c > 0];
                    System.debug('opp_lines:' + opp_lines);
                    if (opp_lines != null && opp_lines.size() > 0) {
                         // 再更新询价行上的各种值
                         for (OpportunityLineItem item : opp_lines) {
                              // 预测成交金额 = 合同总金额 * (行总价 / 报价总价)
                              item.OCM_Sales_Forecast__c = opportunity.Wholesale_Price__c * (item.TotalPrice__c / quote.TotalPrice__c);
                              // 经销商小计 = (合同总金额 - 多年保合计) * (行最新定价总金额 / 标准定价总额) + NoDiscount小计
                              Decimal NoDiscountTotal = item.NoDiscountTotal__c != null ? item.NoDiscountTotal__c : 0;
                              item.AgencySubtotal__c = (opportunity.Wholesale_Price__c - quote.MultiYearWarrantyTotalPrice__c) * (item.ListPrice_total_price__c / quote.Estimation_List_Price__c) + NoDiscountTotal;
                              // 经销商单价 = 经销商小计 / 数量
                              item.AgencyUnitPrice__c = item.Quantity > 0 ? item.AgencySubtotal__c / item.Quantity : item.AgencyUnitPrice__c;
                         }
                         update opp_lines;
                    }
               }
               // SWAG-CCY65A 2022-04-19 ssm end
           System.debug('psp'+psp);
          //  String TempStr = Json.serialize(goodsList);
          // return TempStr;
     }
     // 产品类
     public class Discount {
          public  String Id;//产品编码(产品代码)
          public String AssetModelNoc;
          public String Namec;
          public Integer Quantity;
          public String GuranteeTypec;
          public String PromotionNoc;
          public String Name;
          public Double ListPrice;
          public Double AgencyUnitPricec;
          public Double AgencySubtotalc;
          public Double NoDiscountTotalc;
          public String ParamIdStr;
          public String TypeName;
          public String UUID;
          public String ismatch;
          public String PromotionId;
          public Integer UseCountc;
          public String Product2c;
          public Double ServicePricec;
          public Boolean ifFixc;
          public Boolean ifNecessaryc;
          public String CompareId;
          public Double DiscountcInput;
          public String Categoryc;
          public String NormalDiscountcInput;
          public String GuaranteeDiscountcInput;
          public Boolean multiYearWarrantyc;
      }
      //删除产品
      public static  void deleteAllDiscount(String ParamIdStrs){
          QueryWrapper query = new QueryWrapper(PromotionSalesProducts__c.SObjectType);
          query.eq('QuantityId__c',ParamIdStrs);
          List<PromotionSalesProducts__c> arrays = DataBasePlus.listPlus(query);
          // for(PromotionSalesProducts__c promotion:arrays){
          //      delete(promotion);
          // }
          delete arrays;
          // delete(salesss);
     }
     //测试清空表中数据，非正式环境
     @AuraEnabled
     public static  void deleteAllDiscounttable(){
          QueryWrapper query = new QueryWrapper(PromotionSalesProducts__c.SObjectType);
          List<PromotionSalesProducts__c> arrays = DataBasePlus.listPlus(query);
          for(PromotionSalesProducts__c promotion:arrays){
               delete(promotion);
          }
          // delete(salesss);
     }
     // //根据方案id查询类型
     // @AuraEnabled
     // public static String GetPromotionHeadById(String Id){
     //      String sql = 'select recordtype.developername from PromotionHead__c where Id= :Id';
     //      List<PromotionHead__c> arrs = Database.query(sql);
     //      if(arrs.size()>0){
     //           return arrs[0].recordtype.developername;
     //      }
     //      return null;
     // }

     //两种固定价格的区分
     // public class PromotionHeaddlpername{
     //      public String dlpernameType;

     //      PromotionHeaddlpername(String developername){
     //           this.dlpernameType = developername;
     //      }
     // }

     //根据保存的Id查询 Header 表的数据
     @AuraEnabled
     public static  List<PromotionHead__c>  selectUpdateFiexedpriceData(string[] ProId){

          string sql = 'select ';
          String props = CommonUtils.GetSqlToPorps(PromotionHead__c.SObjectType);
          sql += props;
          sql += ' from PromotionHead__c where Id in :ProId';
          List<PromotionHead__c> arrays = Database.query(sql);
          return arrays;
     }

     @AuraEnabled
     public static  List<QuoteLineItem>  selectUpdateQuoteLineItemData(string[] ItemId){
          string sql = 'select ';
          String props = CommonUtils.GetSqlToPorps(QuoteLineItem.SObjectType);
          sql += props;
          sql += ' from QuoteLineItem where Id in :ItemId';
          List<QuoteLineItem> arrays = Database.query(sql);
          return arrays;
     }
     //查询报价行唯一key
     @AuraEnabled
     public static  List<AggregateResult>  selectUniqueKey(string ParamIdStr){
          string sql = 'select QuoteTrialKey__c from PromotionSalesProducts__c where QuantityId__c = :ParamIdStr group by QuoteTrialKey__c';
          List<AggregateResult> arrays = Database.query(sql);
          return arrays;
     }

}