public  class PromotioService{

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

         List<Quote> arrays = Database.query(' select id,Opportunity.Trade__c,Opportunity.Sales_Root__c,Opportunity.IsAuthorized__c,Agency1__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);
          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 ';
          sql += ' from QuoteLineItem where Quoteid = :IdParam ';
         List<QuoteLineItem> arrays = Database.query(sql);
         return arrays;
    }
    //获取经销商姓名
    @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) {
         PromotioDao dao =  new PromotioDao();
         System.debug('search:'+search);
       String[] arrTest = new String[] {'PromotionNo__cEqual','Description__cEqual'}; 
       PagePlus pages = dao.GetPromotionPromotionSearchFn(page,pageLimit,search,sortOrder,sortPlus,arrTest);  
       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) {
         PromotioDao dao =  new PromotioDao();
       String[] arrTest = new String[] {'PromotionNo__cEqual','Description__cLike'}; 
       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) {
       PromotioDao dao =  new PromotioDao();
       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 ';
          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) {
          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.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;
               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.JxsType__c=='一般折扣'){
                    ifYiBan.put('一般折扣','一般折扣');
                    PromotionSalesMap.put(YiBanId.get(item.Category__c+item.NormalDiscount_c_Input__c),item.Id);
               }else{
                    PromotionSalesMap.put(item.PromotionHead__c,item.Id);
               }
               System.debug('ifYiBan==='+ifYiBan);
           }
           
           saveAllDataDiscount(JsonStr2,ParamIdStr,PromotionSalesMap,ifYiBan,QuoteId,SalesRootc,ContractPrice,OpportunityId);
           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;
      }
      //判断所处数据是否为空
      @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(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) {
          deleteAllDiscount(ParamIdStrs);
         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.QuiteLineitem__c = (Id)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(ifYiBans!='一般折扣'){
                    saless.Promotion_id__c=(Id)itms.PromotionId;
               }
               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;
               // System.debug('Product2:'+saless.Product2__c);
               // insert(saless);
               psp.add(saless);
           }
           if(psp!=null){
               insert psp ;
           }
               Quote quote = new Quote();
               Opportunity opportunity = new Opportunity();
               opportunity.Id=OpportunityId;
               quote.Id=QuoteId;
               if(SalesRootc.equals('販売店')){
                    //赋值给下面的 合同金额 并置灰不可编辑
                    quote.OCM_Agent1_Price_Page__c=ContractPrice;
                    quote.OCM_Agent1_Price__c=ContractPrice;
                    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;
               }
           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 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(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;
     }
}