global class NewQuoteEntryWebService {

    WebService static List<Product2> getProduct2(List<String> ids) {
        List<Product2> p2 =
            [select Id, Name, SFDA_Status__c, Intra_Trade_Cost_RMB__c,
             Intra_Trade_List_RMB__c, Foreign_Trade_Cost_US__c,
             Foreign_Trade_List_US__c, Sales_Possibility__c,
             Estimation_Entry_Possibility__c, StorageStatus__c
             // 多年保修 start
             , GuranteeType__c
             , Entend_gurantee_period_all__c
             //, Foreign_Trade_Gurantee_US__c
             , Intra_Trade_Gurantee_RMB__c
             //, If_Consumable__c
             , Intra_Trade_Service_RMB__c
             ,Maintenance_Price_Year__c
             //外贸多年保 检索外贸字段 精琢技术 wql 2021/01/29 start
             ,NoDiscount_Foreign__c
             ,Intra_Trade_Foreign_RMB__c
             ,Repair_Contract_USD__c  
             //外贸多年保 检索外贸字段 精琢技术 wql 2021/01/29 start
             
             // 多年保修 end
             FROM Product2
             Where Id in :ids];
        return p2;
    }

    WebService static List<QuoteLineItem> getQuoteLineItem(String quoId) {
        System.debug(Logginglevel.ERROR, 'NewQuoteEntryWebService  getQuoteLineItem  Start ' + quoId);

        // 印刷日がある場合、かつ変更がある場合、確認メッセージを出す
        List<QuoteLineItem> items = new List<QuoteLineItem>();
        if (String.isBlank(quoId) == false) {
            items = [Select Quote.Quote_Date__c, Quote.BidAnnounce__c, PricebookEntry.Product2.Packing_list_manual__c,
                     PricebookEntryId, SFDA_Status__c, Cost__c, UnitPrice__c, ListPrice__c, Quantity, Qty_Unit__c,
                     Id, ProductCode__c, Asset_Model_No__c, Name__c, Subtotal, AgencySubtotal__c  , AgencyUnitPrice__c, Present__c
                     // CHAN-B4YAB8 2018/11/09 业务机会产品的赠送、经销商小计、单价
                     // 多年保修 start
                     , multiYearWarranty__c ,  GuaranteePeriod__c,warrantyType__c, NoDiscountTotal__c
                     // 多年保修 end
                     From QuoteLineItem where Quoteid = :quoId Order by Item_Order__c];
        }

        return items;
    }

    WebService static Boolean selectQuotation(String oppId, String quoId) {
        Boolean rt = false;
        // 可以选择，没有被取消过的报价
        List<Quote> quotes = [select Id, Estimation_List_Price__c, Dealer_Final_Price__c, Agency1__c, Agency1_Profit__c, Agency1_Profit_Rate__c,
                              Agency2__c, Agent1_Agent2_Price__c, Agency2_Profit__c, Agency2_Profit_Rate__c, Stocking_Price__c, Quote_No__c, Name,
                              OCM_Sales_Forecast__c, OCM_Agent1_Price__c, Opportunity.RecordType.DeveloperName, TotalPrice__c
                              from Quote where Id = :quoId and Cancel_Decide__c = false];
        List<QuoteLineItem> qlis = [select Id, Id__c, SFDA_Status__c, Name__c, ListPrice__c, Quantity, UnitPrice__c, Qty_Unit__c, Cost__c,
                                    BSS_Category__c, Subtotal__c, PricebookEntryId
                                    from QuoteLineItem where Quoteid = :quoId Order by Item_Order__c, Id];
        Savepoint sp = Database.setSavepoint();
        try {
            if (quotes.size() > 0) {
                Quote quo = quotes[0];
                Opportunity o = New Opportunity();
                List<Opportunity> os = New List<Opportunity>();
                os = [select Id, Estimation_List_Price__c, Dealer_Final_Price__c, Estimation_List_Price_Without_Tax__c,
                      Agency1__c, OCM_Agent1_Price__c, Agency1_Profit__c, Agency1_Profit_Rate__c, Stocking_Price__c,
                      Agency2__c, Agent1_Agent2_Price__c, Agency2_Profit__c, Agency2_Profit_Rate__c
                      From Opportunity Where Id = :oppid];
                if (os.size() > 0) {
                    o = os[0];
                    o.Estimation_List_Price__c = quo.Estimation_List_Price__c;
                    o.Wholesale_Price__c = quo.OCM_Sales_Forecast__c;
                    o.Dealer_Final_Price__c = quo.Dealer_Final_Price__c;
                    o.Agency1__c = quo.Agency1__c;
                    o.OCM_Agent1_Price__c = quo.OCM_Agent1_Price__c;
                    o.Agency1_Profit__c = quo.Agency1_Profit__c;
                    o.Agency1_Profit_Rate__c = quo.Agency1_Profit_Rate__c;
                    o.Agency2__c = quo.Agency2__c;
                    o.Agent1_Agent2_Price__c = quo.Agent1_Agent2_Price__c;
                    o.Agency2_Profit__c = quo.Agency2_Profit__c;
                    o.Agency2_Profit_Rate__c = quo.Agency2_Profit_Rate__c;
                    o.Stocking_Price__c = quo.Stocking_Price__c;
                    o.Estimation_No__c = quo.Quote_No__c;
                    o.Estimation_Name__c = quo.Name;
                    o.Estimation_Id__c = quo.Id;

                    ControllerUtil.updOpp(o);

                    List<OpportunityLineItem> ols = New List<OpportunityLineItem>();
                    OpportunityLineItem ol = New OpportunityLineItem();
                    ols = [select Id from OpportunityLineItem Where OpportunityId = :oppid];
                    if (ols.size() > 0) {
                        //delete
                        ControllerUtil.delOppLine(ols);
                    }

                    Integer i = 1;
                    ols = New List<OpportunityLineItem>();
                    if (qlis.size() > 0) {
                        for (QuoteLineItem ql : qlis) {
                            if (ql.PricebookEntryId != null) {
                                ol = New OpportunityLineItem();
                                ol.OpportunityId = oppId;
                                ol.Id__c = ql.Id__c;
                                ol.SFDA_Status__c = ql.SFDA_Status__c;
                                ol.Name__c = ql.Name__c;
                                ol.ListPrice__c = ql.ListPrice__c;
                                ol.Quantity = ql.Quantity;
                                ol.UnitPrice = 0;
                                ol.UnitPrice__c = ql.UnitPrice__c;
                                ol.Qty_Unit__c = ql.Qty_Unit__c;
                                //コストは小計済を登録
                                ol.Cost__c = ql.Cost__c;
                                ol.BSS_Category__c = ql.BSS_Category__c;

                                //OCM売上予測金額 * (小計/見積合計)
                                if (ql.Subtotal__c != null && quo.OCM_Sales_Forecast__c != null && quo.TotalPrice__c != null) {
                                    if (ql.Subtotal__c > 0 && quo.TotalPrice__c > 0) {
                                        ol.OCM_Sales_Forecast__c =  quo.OCM_Sales_Forecast__c * (ql.Subtotal__c / quo.TotalPrice__c);
                                    }
                                }
                                //価格表
                                ol.PricebookEntryId = ql.PricebookEntryId;
                                //並び順
                                ol.Item_Order__c = i;
                                ols.add(ol);
                                i++;
                            }
                        }
                        ControllerUtil.insOppLine(ols);
                    }
                    rt = true;
                }
            }
        } catch (DmlException de) {
            Database.rollback(sp);
            throw de;
        } catch (Exception e) {
            Database.rollback(sp);
            throw e;
        }
        return rt;
    }
    //SWAG-C3BAVY 【委托】询价新旧code 替换 精琢技术 wql 20210607 start
    //用于报价单条替换产品otcode
    WebService static Boolean updateOTCode(String tempQuoId){
        Boolean successFlag = true;
        //定义询价id
        String tempOppId = '';
        // SWAG-CGZB9J 20220808 ssm 内贸/外贸
        String oppTrade = '';

        //存放所有报价行 产品id
        List<String> product2Ids = new List<String>();
        //产品list
        List<Product2> Product2List = new List<Product2>();
        //key:旧的产品型号；value:对应的新产品id
        Map<String,String> newProIdsMap = new Map<String,String>();
        //key:新产品id；value:新价格手册id
        Map<String,String> newPriceBookIdMap = new Map<String,String>();
        
        //list封装类 用此封装类 跳过 不能直接更新行项目上产品
        List<QELine> activities;
        //clone报价行
        List<QuoteLineItem> QuoteLineItemCloneList = new List<QuoteLineItem>();
        //clone询价行
        List<OpportunityLineItem> OpportunityLineItemCloneList = new List<OpportunityLineItem>();

/* ----------------------------------------前期数据准备  wql start ----------------------------------------- */
        //先获取询价id
        // SWAG-CGZB9J 20220808 ssm 检索增加询价内贸/外贸字段
        List<quote> quoteList= [select OpportunityId, Opportunity.Trade__c from quote where id =:tempQuoId];
        if(quoteList.size()>0){
            tempOppId = quoteList[0].OpportunityId;
            oppTrade = quoteList[0].Opportunity.Trade__c != null && '外貿'.equals(quoteList[0].Opportunity.Trade__c) ? 'USD' : 'CNY';
        }
        //获取所有报价行 （该sql作为直接insert克隆用 最好不要添加其他会有影响的字段）
        List<QuoteLineItem> QuoteLineItemList =
            [Select id,Asset_Model_No__c,ProductCode__c,PricebookEntry.Product2Id, PricebookEntry.Product2.SFDA_Status__c,SFDA_Status__c, BSS_Category__c,Qty_Unit__c, Cost__c, UnitPrice__c,UnitPrice, ListPrice__c, Quantity, PricebookEntryId, UnitPrice_Page__c,AgencyUnitPrice__c, AgencySubtotal__c, Present__c, multiYearWarranty__c , If_Cancel_Guarantee__c , GuaranteePeriod__c, ServicePrice__c , GuranteePrice__c, ProductEntend_gurantee_period_all__c,ProductGuranteePrice__c,  GuranteeType__c,warrantyType__c, productServicePrice__c, NoDiscountTotal__c, provistonPeriod__c, Maintenance_Price_Year__c,Quoteid,Id__c,OCM_Sales_Forecast__c,NameForPrint__c,NameForPrintDelimiter__c,Asset_Model_No_forPrint__c,Cost_Subtotal__c,Name__c,Subtotal__c,Quantity__c,ProductSetName__c,CanNotCancelFlag__c  From QuoteLineItem where Quoteid =:tempQuoId Order by Item_Order__c, Id];
        //判断是否有行项目
        if(QuoteLineItemList.size()>0){
            for(QuoteLineItem qli :QuoteLineItemList){
                Product2Ids.add(qli.PricebookEntry.Product2Id );
            }
        }
        /* ---------------这部分其实需要用两次 但是webservice没办法写共通  wql start ------------------------ */        
        //如果产品id有值
        if(product2Ids.size()>0){
            //根据现有的产品id 查询产品型号和对应新的产品id
            Product2List = [select ProductCode,Correspond_Code__c from Product2 where id in:product2Ids and Correspond_Code__c !=null];
        }
        //存放key:旧的产品型号；value:对应的新产品id
        if(Product2List.size()>0){
            for(Product2 p :Product2List){
                newProIdsMap.put(p.ProductCode,p.Correspond_Code__c);
            }
        }
        //根据新产品id，获取价格手册id  这里因为每个产品对应两条价格手册 CNY / USD  ,先直接默认取CNY的价格手册
        // SWAG-CGZB9J 20220808 ssm 根据询价内贸/外贸，确定使用CNY价格手册还是USD价格手册
        List<PriceBookEntry> priceBookList = [SELECT Id,Product2Id FROM PriceBookEntry WHERE Product2Id in:newProIdsMap.values() and CurrencyIsoCode = :oppTrade];
        if(priceBookList.size()>0){
            for(PriceBookEntry pbe:priceBookList){
                newPriceBookIdMap.put(pbe.Product2Id,pbe.Id);
            }
        }
        /* ---------------这部分其实需要用两次 但是webservice没办法写共通  wql end ------------------------ */ 
        
/* ----------------------------------------前期数据准备  wql end ----------------------------------------- */        

/* ------------------------------- 报价行 全删全增 替换产品otcode  wql start ------------------------------------- */        
        activities =new List<QELine>();
        if(QuoteLineItemList.size()>0){
            for(QuoteLineItem q :QuoteLineItemList){
                QELine c = null;
                if(q.PricebookEntry.Product2.SFDA_Status__c =='停止'){
                    System.debug('111:');
                    System.debug('newProIdsMap:'+newProIdsMap);
                    System.debug('newPriceBookIdMap:'+newPriceBookIdMap);
                    System.debug('q.Asset_Model_No__c');
                     c = new QELine(q,'需要替换',newProIdsMap.get(q.ProductCode__c),newPriceBookIdMap.get(newProIdsMap.get(q.ProductCode__c)));
                }else{
                    System.debug('222:');
                     c = new QELine(q,'',newProIdsMap.get(q.ProductCode__c),newPriceBookIdMap.get(newProIdsMap.get(q.ProductCode__c)));
                }
                
                System.debug('C::'+c);
                activities.add(c);
            }
        }
        try {
            //报价行先删后增 start
            if(QuoteLineItemList.size()>0){
                delete QuoteLineItemList;
            }
            if(activities.size()>0){
                for(QELine  qe:activities){
                    //new 行项目
                    QuoteLineItem quo = new QuoteLineItem();
                    //复制报价行
                    quo = qe.pageObject;
                    //addlist
                    QuoteLineItemCloneList.add(quo);
                }
            }
            system.debug('QuoteLineItemCloneList:'+QuoteLineItemCloneList);
            //报价行先删后增 start
            if(QuoteLineItemCloneList.size()>0){
                insert QuoteLineItemCloneList;
            }
            //报价行先删后增 end
        } catch (Exception e) {
            successFlag = false;
        }
        
        
/* ------------------------------- 报价行 全删全增 替换产品otcode  wql end ------------------------------------- */        

/* ------------------------------- 询价行 全删全增 替换产品otcode  wql start ------------------------------------- */        
List<OpportunityLineItem>  OpportunityLineItemList=[Select id,OpportunityId,PricebookEntry.Product2Id, Asset_Model_No__c,PricebookEntry.Product2.SFDA_Status__c, SFDA_Status__c, Name__c, ProductCode__c,Qty_Unit__c, Cost__c, ListPrice__c, Quantity, BSS_Category__c, TotalPrice,Product_Cost__c, Product_ListPrice__c,PricebookEntryId,UnitPrice__c, TotalPrice__c, AgencyUnitPrice__c, AgencySubtotal__c, Present__c, multiYearWarranty__c , If_Cancel_Guarantee__c , GuaranteePeriod__c,ServicePrice__c , GuranteePrice__c,ProductEntend_gurantee_period_all__c,ProductGuranteePrice__c, GuranteeType__c,warrantyType__c, productServicePrice__c,NoDiscountTotal__c, provistonPeriod__c, Maintenance_Price_Year__c,OCM_Sales_Forecast__c,NumberOfObjective_146P__c,Id__c,OCM_man_province_txt__c,Objective_146P__c,Important_Rroduct__c,If_170Pro__c,If_EP_T1_F__c,If_AHPro__c,Is_DangerousChemicals__c,CanNotCancelFlag__c,Item_Order__c,target__c,Register_alleffective__c,strategyProductText__c From OpportunityLineItem Where OpportunityId =:tempOppId Order by Item_Order__c, Id];
        //判断是否有行项目
        Product2Ids = new List<String>();
        Product2List = new List<Product2>();
        newProIdsMap.clear();
        newPriceBookIdMap.clear();
        priceBookList = new List<PriceBookEntry>();

        if(OpportunityLineItemList.size()>0){
            for(OpportunityLineItem oli :OpportunityLineItemList){
                Product2Ids.add(oli.PricebookEntry.Product2Id );
            }
        }
        /* ---------------这部分其实需要用两次 但是webservice没办法写共通  wql start ------------------------ */        
        //如果产品id有值
        if(product2Ids.size()>0){
            //根据现有的产品id 查询产品型号和对应新的产品id
            Product2List = [select ProductCode,Correspond_Code__c from Product2 where id in:product2Ids and Correspond_Code__c !=null];
        }
        //存放key:旧的产品型号；value:对应的新产品id
        if(Product2List.size()>0){
            for(Product2 p :Product2List){
                newProIdsMap.put(p.ProductCode,p.Correspond_Code__c);
            }
        }
        //根据新产品id，获取价格手册id  这里因为每个产品对应两条价格手册 CNY / USD  ,先直接默认取CNY的价格手册
        priceBookList = [SELECT Id,Product2Id FROM PriceBookEntry WHERE Product2Id in:newProIdsMap.values() and CurrencyIsoCode ='CNY'];
        if(priceBookList.size()>0){
            for(PriceBookEntry pbe:priceBookList){
                newPriceBookIdMap.put(pbe.Product2Id,pbe.Id);
            }
        }
        /* ---------------这部分其实需要用两次 但是webservice没办法写共通  wql end ------------------------ */
        activities =new List<QELine>();
        System.debug('最开始的：OpportunityLineItemList：'+OpportunityLineItemList);
        System.debug('最开始的数量：'+OpportunityLineItemList.size());
        if(OpportunityLineItemList.size()>0){
            for(OpportunityLineItem opp :OpportunityLineItemList){
                QELine c = null;
                if(opp.PricebookEntry.Product2.SFDA_Status__c =='停止'){
                     System.debug('zzzzz:');
                     System.debug('newProIdsMap:'+newProIdsMap);
                     System.debug('opp.ProductCode__c:'+opp.ProductCode__c);
                     c = new QELine(opp,'需要替换',newProIdsMap.get(opp.ProductCode__c),newPriceBookIdMap.get(newProIdsMap.get(opp.ProductCode__c)));
                }else{
                     c = new QELine(opp,'',newProIdsMap.get(opp.ProductCode__c),newPriceBookIdMap.get(newProIdsMap.get(opp.ProductCode__c)));
                }
                System.debug('C::'+c);
                activities.add(c);
            }
        }
        try {
            //询价行先删后增 start
            if(OpportunityLineItemList.size()>0){
                delete OpportunityLineItemList;
            }
            system.debug('询价行的行数：'+activities.size());
            //询价行先删后增 end
            if(activities.size()>0){
                for(QELine  ql:activities){
                    //new 行项目
                    OpportunityLineItem oppli = new OpportunityLineItem();
                    //询价报价行
                    oppli = ql.pageOppObject;
                    //addlist
                    OpportunityLineItemCloneList.add(oppli);
                }
            }
            
            system.debug('OpportunityLineItemCloneList:'+OpportunityLineItemCloneList);
            //报价行先删后增 start
            if(OpportunityLineItemCloneList.size()>0){
                insert OpportunityLineItemCloneList;
            }
        } catch (Exception e) {
            successFlag = false;
        }
        
/* ------------------------------- 询价行 全删全增 替换产品otcode  wql end ------------------------------------- */        
        return successFlag;
    }

    //报价替换产品code 封装类
    public class QELine {
        //报价行
        public QuoteLineItem pageObject;
        //询价行
        public OpportunityLineItem pageOppObject;
        //有参构造
        public QELine(QuoteLineItem qli,String otcode,String proId,String tempPriceBookEntryId){
            this.pageObject = qli.clone();
            //替换产品和价格手册
            System.debug('333:');
            if(String.isNotBlank(otcode)){
                System.debug('444:');
                if(tempPriceBookEntryId!=null){
                    this.pageObject.PricebookEntryId=tempPriceBookEntryId  ;
                }
                // if(proId!=null){
                //     System.debug('555:');
                //     this.pageObject.PricebookEntry.Product2Id=proId  ;
                // }
                
            }
        }
        //询价行遍历
        public QELine(OpportunityLineItem oli,String otcode,String proId,String tempPriceBookEntryId){
            this.pageOppObject = oli.clone();
            //insert 报价不需要id
            // this.Id  	=	qli.Id;
            //替换产品和价格手册
            if(String.isNotBlank(otcode)){
                if(tempPriceBookEntryId!=null){
                    this.pageOppObject.PricebookEntryId=tempPriceBookEntryId  ;
                }
                // if(proId!=null){
                //     this.pageOppObject.PricebookEntry.Product2Id=proId ;
                // }
                
            }
        }
    }
    //SWAG-C3BAVY 【委托】询价新旧code 替换 精琢技术 wql 20210607 end
}