public without sharing class OrderDivisionController {
    public static Boolean OrderDivision = false;
    // 链接地址
    public String baseUrl { get; set; }
    public String rtUrl { get; set; }
    // 合同ID、画面项目
    public Id odrId {get;set;}
    public Order odr {get;set;}
    public List<LineInfo> lineinfo {get;set;}

    public boolean is_IE {get;set;}
    public Decimal sh_o {get;set;}
    public Decimal sh_d {get;set;}

    private Decimal total;
    private Decimal total_o;
    private Decimal total_d;

    public Boolean specialDealer { get; set; }
    //public String testlog {get;set;}

    public OrderDivisionController() {
        // 基础Url
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0,path.indexOf('/apex'));
        } else if (path.indexOf('production/') > 0) {
            baseUrl += '/production';
        }
        // 返回地址url
        rtUrl = System.currentPageReference().getParameters().get('retURL');
        if (rtUrl == null || rtUrl == 'null') {
            rtUrl = '';
        }
        // 合同ID
        if (odrId == null) {
            odrId = System.currentPageReference().getParameters().get('odrId');
        }
        // 画面项目初始化
        lineinfo = new List<LineInfo>();
    }

    public OrderDivisionController(ApexPages.StandardController controller) {
        this();
    }

    public void init() {
        // 合同ID检查
        if (odrId == null) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '合同不存在。'));
            return;
        }
        // 取得合同信息
        Schema.DescribeSobjectResult d_odr = Order.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> d_odr_map = d_odr.fields.getMap();
        String soql_odr = 'select ';
        String fields_odr = '';
        for (String field : d_odr_map.keySet()) {
            if (fields_odr.length() > 0) {
                fields_odr += ', ';
            }
            fields_odr += field;
        }
        fields_odr += ', Opportunity.IE_ShippingHandling__c';
        soql_odr += fields_odr;
        soql_odr += ' from Order where Id = \'' + odrId + '\'';
        //List<Order> odrList = [select Id, OpportunityId, QuoteId from Order where Id = :odrId];
        List<Order> odrList = Database.query(soql_odr);
        if (odrList.size() == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '合同不存在。'));
            return;
        }
        odr = odrList[0];

        specialDealer = IfspecialDealer(odr.DealerId__c);
        is_IE = false;
        sh_o = 0;
        sh_d = 0;
        total = 0;
        if (odr.ProductSegment__c == 'IE' || odr.ProductSegment__c == 'RVI'|| odr.ProductSegment__c == 'NDT'|| odr.ProductSegment__c == 'ANI') {
            is_IE =true;
            sh_o = odr.Opportunity.IE_ShippingHandling__c == null ? 0 : odr.Opportunity.IE_ShippingHandling__c;
            total = odr.TotalAmount;
            System.debug(total+'@@@@@@@@@@@'+sh_o);
        }

        // 取得合同产品
        List<OrderItem> oiList = new List<OrderItem>();
        List<DecideQuoteProductSet__c> dqList = new List<DecideQuoteProductSet__c>();
        if(odr.ProductSegment__c != 'BS'){
            oiList = [select Id, QuoteLineItemId, Description, Quantity, PricebookEntry.Product2.Name,PricebookEntry.Product2.ProductCode,PricebookEntry.Product2.Product_ECCode__c,UnitPrice from OrderItem where OrderId = :odrId order by Id];
        }else{
            oiList = [select Id, QuoteLineItemId, Description, Quantity, PricebookEntry.Product2.Name,PricebookEntry.Product2.ProductCode,PricebookEntry.Product2.Product_ECCode__c,UnitPrice from OrderItem where OrderId = :odrId and ODISingleProduct__c = true order by Id];
            dqList = [select Id,Name,OwnerId, DecideProductSet__c,DecideProductSetCount__c,DecideProductSetDiscount__c,DecideProductSetName__c,DecideProductSetUnivalence__c,DecideProductSetCode__c from DecideQuoteProductSet__c where DecideOrder__c = :odrId order by Id];
        }
        System.debug(dqList);
        if (oiList.size() == 0 && odr.ProductSegment__c != 'BS') {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '合同产品不存在。'));
            return;
        }else if(odr.ProductSegment__c == 'BS' && oiList.size() == 0 && dqList.size() == 0 ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '合同产品不存在。'));
            return; 
        }
        // 画面项目做成
        Integer lineno = 0;
        if(odr.ProductSegment__c != 'BS'){
            for (OrderItem oi : oiList) {
                lineno += 1;
                LineInfo li = new LineInfo(lineno, oi);
                lineinfo.add(li);
            }
        }else{
            if(dqList.size() > 0){
                for (DecideQuoteProductSet__c dqp : dqList){
                    lineno += 1;
                    LineInfo li = new LineInfo(lineno,dqp);
                    LineInfo.add(li);
                }
            }

            if(oiList.size() > 0){
                for (OrderItem oi : oiList) {
                    lineno += 1;
                    LineInfo li = new LineInfo(lineno, oi);
                    lineinfo.add(li);
                } 
            }
        }
    }

    public PageReference saveBtn() {
        tes();
        // 是否分割
        boolean divideFlg = false;
        total_o = 0;
        total_d = 0;
        List<String> setIDList = new List<String>();
        if (sh_o < sh_d) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '拆分运保费不正确。'));
            return null;
        }
        for (LineInfo li : lineinfo) {
            if (li.divideCnt != null && li.divideCnt > 0) {
                if (li.divideCnt > li.oi.Quantity) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '拆分产品数量不正确，行：' + li.lineNo + '，数量：' + li.divideCnt));
                    return null;
                }
                divideFlg = true;
            }

            if(li.isSet){
                setIDList.add(li.dqps.DecideProductSet__c);
            }
            if(!li.isSet){
                Decimal dcnt = li.divideCnt != null && li.divideCnt > 0 ? li.divideCnt : 0;
                total_o += (li.oi.Quantity - dcnt) * li.oi.UnitPrice;
                total_d += dcnt * li.oi.UnitPrice;
            }
        }

        if (divideFlg == false) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有拆分合同。'));
            return null;
        }

        // 取得原询价、询价产品、询价联系人
        Opportunity opp = null;
        List<OpportunityLineItem> oliList = null;
        List<OpportunityContactRole> ocrList = null;
        Schema.DescribeSobjectResult d_opp = Opportunity.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> d_opp_map = d_opp.fields.getMap();
        String soql_opp = 'select ';
        String fields_opp = '';
        for (String field : d_opp_map.keySet()) {
            if (fields_opp.length() > 0) {
                fields_opp += ', ';
            }
            fields_opp += field;
        }
        soql_opp += fields_opp;
        soql_opp += ' from Opportunity where Id = \'' + odr.OpportunityId + '\'';
        //List<Opportunity> oppList = [select Id, SyncedQuoteId from Opportunity where Id = :odr.OpportunityId];
        List<Opportunity> oppList = Database.query(soql_opp);
        if (oppList.size() > 0) {
            opp = oppList[0];
            oliList = [select Id, PricebookEntryId, Product_Search__c, Product_Search__r.Id, Product_Search__r.Product__c from OpportunityLineItem where OpportunityId = :odr.OpportunityId];
            ocrList = [select Id, OpportunityId, ContactId, Role, IsPrimary from OpportunityContactRole where OpportunityId = :odr.OpportunityId];
        }
        Map<String, Product_Search__c> psMap = new Map<String, Product_Search__c>();
        if (oliList.size() > 0) {
            for (OpportunityLineItem oli : oliList) {
                psMap.put(oli.PricebookEntryId, oli.Product_Search__r);
            }
        }
        // 取得原报价、报价产品
        Quote quo = null;
        List<QuoteLineItem> qliList = null;
        Map<String, QuoteLineItem> qliMap = new Map<String, QuoteLineItem>();
        Schema.DescribeSobjectResult d_quo = Quote.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> d_quo_map = d_quo.fields.getMap();
        String soql_quo = 'select ';
        String fields_quo = '';
        for (String field : d_quo_map.keySet()) {
            if (fields_quo.length() > 0) {
                fields_quo += ', ';
            }
            fields_quo += field;
        }
        soql_quo += fields_quo;
        soql_quo += ' from Quote where Id = \'' + (odr.QuoteId == null ? '' : odr.QuoteId) + '\'';
        //List<Quote> quoList = [select Id from Quote where Id = :odr.QuoteId];
        List<Quote> quoList = Database.query(soql_quo);
        if (quoList.size() > 0) {
            quo = quoList[0];
            qliList = [select Id, Set__c, Description, Quantity, Discount, ListPrice, PricebookEntryId, QuoteId, UnitPrice, Custom_Price__c,SetName__c from QuoteLineItem where QuoteId = :odr.QuoteId];
            for (QuoteLineItem qli : qliList) {
                qliMap.put(qli.Id, qli);
            }
        }

         //获取产品配套
        List<productSetItem__c> pSetItemList = new List<productSetItem__c>();
        Map<String,List<productSetItem__c>> productSetMap = new Map<String,List<productSetItem__c>>();
        Map<String,List<QuoteLineItem>> set_qliMap = new Map<String,List<QuoteLineItem>>();
        if(setIDList.size() > 0){
            pSetItemList = [select id,Count__c,product__c,productSet__r.Name from productSetItem__c where productSet__c in : setIDList order by productSet__c];
            
            for(productSetItem__c psi : pSetItemList){
                if(productSetMap.size() != 0 && productSetMap.containsKey(psi.productSet__c)){
                     productSetMap.get(psi.productSet__r.Name).add(psi);
                }else{
                    productSetMap.put(psi.productSet__r.Name, new List<productSetItem__c>());
                    productSetMap.get(psi.productSet__r.Name).add(psi);
                }
            }

            List<QuoteLineItem> tempList = qliMap.values();
            System.debug(tempList);
            for(QuoteLineItem qli : tempList){
                System.debug(qli.SetName__c);
                if(set_qliMap.size() !=0 && set_qliMap.containsKey(qli.SetName__c)){
                    set_qliMap.get(qli.SetName__c).add(qli);
                }else{
                    set_qliMap.put(qli.SetName__c, new List<QuoteLineItem>());
                    set_qliMap.get(qli.SetName__c).add(qli);
                }
            } 
            
        }
        System.debug(set_qliMap);
        // 分割保存开始
        Savepoint sp = Database.setSavepoint();
        Map<Integer,String> old = new Map<Integer,String>();
        Map<Integer,String> newd = new Map<Integer,String>();

        Map<String,Decimal> qOld = new Map<String,Decimal>();
        Map<String,Decimal> qnew = new Map<String,Decimal>();

        // 跳过询价状态写入限制
        StaticParameter.StageProgressBarUpdate = true;
        OrderDivisionController.OrderDivision = true;
        try {
            // 复制询价
            Opportunity ins_opp = opp.clone();
            opp.Is_Decided__c = false;
            if (is_IE) {
                Decimal tmp = opp.IE_Custom_Price__c == null ? 0 : opp.IE_Custom_Price__c * total_o / total;
                opp.IE_Custom_Price__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
                tmp = opp.IE_local_cost__c == null ? 0 : opp.IE_local_cost__c * total_o / total;
                opp.IE_local_cost__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
                opp.IE_ShippingHandling__c = sh_o - sh_d;
                System.debug(tmp+'@@@@@'+sh_d);
            }
            update opp;
            System.debug('=====update opp');
            ins_opp.Id = null;
            ins_opp.SyncedQuoteId = null;
            ins_opp.Is_Decided__c = false;
            ins_opp.org_opportunity__c = opp.Id;
            if (is_IE) {
                Decimal tmp = ins_opp.IE_Custom_Price__c == null ? 0 : ins_opp.IE_Custom_Price__c * total_d / total;
                ins_opp.IE_Custom_Price__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
                tmp = ins_opp.IE_local_cost__c == null ? 0 : ins_opp.IE_local_cost__c * total_d / total;
                ins_opp.IE_local_cost__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
                ins_opp.IE_ShippingHandling__c = sh_d;
            }
            insert ins_opp;
            System.debug('=====ins_opp');
            // 复制询价联系人
            List<OpportunityContactRole> ins_ocrList = new List<OpportunityContactRole>();
            for (OpportunityContactRole ocr : ocrList) {
                OpportunityContactRole ins_ocr = ocr.clone();
                ins_ocr.Id = null;
                ins_ocr.OpportunityId = ins_opp.Id;
                ins_ocrList.add(ins_ocr);
            }
            if (ins_ocrList.size() > 0) insert ins_ocrList;
            System.debug('=====ins_ocrList');
            // 复制报价
            Quote ins_quo = null;
            if (quo != null) {
                ins_quo = quo.clone();
                ins_quo.Id = null;
                ins_quo.OpportunityId = ins_opp.Id;
                ins_quo.Is_Decided__c = false;
                for (Integer i = 1; i < = 30; i++) {
                    Decimal qty = (Decimal) ins_quo.get('SetQty' + i + '__c');
                    if (qty > 1) {
                        ins_quo.put('SetQty' + i + '__c', 1);
                    }
                }
            }
            if (ins_quo != null) insert ins_quo;
System.debug('=====ins_quo');
            // 如果复制报价，分割报价产品
            List<QuoteLineItem> upd_qliList = new List<QuoteLineItem>();
            List<QuoteLineItem> del_qliList = new List<QuoteLineItem>();
            List<QuoteLineItem> ins_qliList = new List<QuoteLineItem>();


            Integer setNum = 1;
            Integer allNum = 1;
            if (ins_quo != null) {
                Decimal oldSum = 0;
                Decimal newSum = 0;
                for (LineInfo li : lineinfo) {
                    if(li.isSet == false){
                        // 全部分割
                        if (li.divideCnt == li.oi.Quantity) {
                            // 删除原报价产品
                            QuoteLineItem del_qli = new QuoteLineItem(Id = li.oi.QuoteLineItemId);
                            del_qliList.add(del_qli);
                            // 全部分割到新报价
                            QuoteLineItem ins_qli = qliMap.get(li.oi.QuoteLineItemId).clone();
                            ins_qli.Id = null;
                            ins_qli.QuoteId = ins_quo.Id;

                            ins_qliList.add(ins_qli);
                            newSum += ins_qli.Quantity * ins_qli.UnitPrice;
                        // 部分分割
                        } else if (li.divideCnt > 0 && li.divideCnt <= li.oi.Quantity) {
                            // 更新原报价产品数量
                            QuoteLineItem upd_qli = qliMap.get(li.oi.QuoteLineItemId);
                            upd_qli.Quantity = upd_qli.Quantity - li.divideCnt;
                            upd_qli.Custom_Price__c = upd_qli.Custom_Price__c == null ? 0 : upd_qli.Custom_Price__c * upd_qli.Quantity / (upd_qli.Quantity + li.divideCnt);
                            upd_qliList.add(upd_qli);
                            oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
                            // 部分分割到新报价
                            QuoteLineItem ins_qli = qliMap.get(li.oi.QuoteLineItemId).clone();
                            ins_qli.Id = null;
                            ins_qli.QuoteId = ins_quo.Id;
                            ins_qli.Custom_Price__c = ins_qli.Custom_Price__c * li.divideCnt / ins_qli.Quantity;
                            ins_qli.Quantity = li.divideCnt;
                            ins_qliList.add(ins_qli);
                            newSum += ins_qli.Quantity * ins_qli.UnitPrice;
                        // 未分割
                        } else{
                            // 不做处理
                            QuoteLineItem upd_qli = qliMap.get(li.oi.QuoteLineItemId);
                            oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
                        }
                    }else{
                        // 全部分割
                        if (li.divideCnt == li.dqps.DecideProductSetCount__c){
                            List<QuoteLineItem> tempList = set_qliMap.get(li.productName);
                            System.debug(li.productName+'-----'+tempList);
                            for(QuoteLineItem tempqli : tempList){
                                QuoteLineItem del_qli = new QuoteLineItem(Id = tempqli.Id);
                                del_qliList.add(del_qli);

                                QuoteLineItem ins_qli = qliMap.get(tempqli.Id).clone();
                                ins_qli.Id = null;
                                ins_qli.SetName__c = li.productName;
                                ins_qli.Set__c = 'set'+ (setNum>9?''+setNum:'0'+setNum);
                                ins_qli.QuoteId = ins_quo.Id;
                                ins_qli.SingleProduct__c = false;
                                ins_qliList.add(ins_qli);
                                newSum += ins_qli.Quantity * ins_qli.UnitPrice;
                            }
                            newd.put(setNum,li.productName);
                            qnew.put(li.productName,li.divideCnt);
                            setNum++;
                        } else if (li.divideCnt > 0 && li.divideCnt <= li.dqps.DecideProductSetCount__c) {
                            List<QuoteLineItem> tempList = set_qliMap.get(li.productName);
                             System.debug(li.productName);
                            for(QuoteLineItem tempqli : tempList){
                                 // 更新原报价产品数量
                                QuoteLineItem upd_qli = qliMap.get(tempqli.Id);
                                upd_qli.Quantity = upd_qli.Quantity - li.divideCnt;
                                upd_qli.Custom_Price__c = upd_qli.Custom_Price__c == null ? 0 : upd_qli.Custom_Price__c * upd_qli.Quantity / (upd_qli.Quantity + li.divideCnt);
                                upd_qli.Set__c = 'set'+ (allNum>9?''+allNum:'0'+allNum);
                                upd_qliList.add(upd_qli);
                                oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
                                // 部分分割到新报价
                                QuoteLineItem ins_qli = qliMap.get(tempqli.Id).clone();
                                ins_qli.Id = null;
                                ins_qli.SingleProduct__c = false;
                                ins_qli.SetName__c = li.productName;

                                ins_qli.Set__c = 'set'+ (setNum>9?''+setNum:'0'+setNum);
                                ins_qli.QuoteId = ins_quo.Id;
                                ins_qli.Custom_Price__c = ins_qli.Custom_Price__c * li.divideCnt / ins_qli.Quantity;
                                ins_qli.Quantity = li.divideCnt;
                                ins_qliList.add(ins_qli);
                                newSum += ins_qli.Quantity * ins_qli.UnitPrice; 
                            }
                            newd.put(setNum,li.productName);
                            qnew.put(li.productName,li.divideCnt);
                            old.put(allNum,li.productName);
                            qOld.put(li.productName,li.dqps.DecideProductSetCount__c-li.divideCnt);
                            setNum++;
                            allNum++;
                        } else{
                            List<QuoteLineItem> tempList = set_qliMap.get(li.productName);
                            System.debug(li.productName);
                            for(QuoteLineItem tempqli : tempList){
                                QuoteLineItem upd_qli = qliMap.get(tempqli.Id);
                                upd_qli.Set__c = 'set'+ (allNum>9?''+allNum:'0'+allNum);
                                oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
                            }

                            old.put(allNum,li.productName);
                            qOld.put(li.productName,li.dqps.DecideProductSetCount__c);
                            allNum++;
                        }
                    }
                    System.debug(upd_qliList);
                    System.debug(del_qliList);
                    System.debug(ins_qliList);
                }

                Decimal oldCustomPrice = quo.Custom_Price_Total_Text__c == null ? 0 : quo.Custom_Price_Total_Text__c * oldSum / quo.Subtotal;
                Decimal newCustomPrice = quo.Custom_Price_Total_Text__c == null ? 0 : quo.Custom_Price_Total_Text__c * newSum / quo.Subtotal;

                if (upd_qliList.size() > 0) update upd_qliList;
                if (del_qliList.size() > 0) delete del_qliList;
                if (ins_qliList.size() > 0) insert ins_qliList;
System.debug('=====ins_qliList');

                for (Integer i = 1; i < = 30; i++) {

                    if(old.containsKey(i)){
                        String temp = old.get(i);
                        quo.put('SetName' + i + '__c', temp);
                        quo.put('SetQty' + i + '__c', qOld.get(temp));
                    }else{
                        quo.put('SetName' + i + '__c', '');
                        quo.put('SetQty' + i + '__c', null);
                    }

                    if(newd.containsKey(i)){
                        String temp = newd.get(i);
                        ins_quo.put('SetName' + i + '__c', temp);
                        ins_quo.put('SetQty' + i + '__c', qnew.get(temp));
                    }else{
                        ins_quo.put('SetName' + i + '__c', '');
                        ins_quo.put('SetQty' + i + '__c', null);
                    }

                }
                quo.Custom_Price_Total_Text__c = oldCustomPrice;
                quo.Is_Decided__c = false;
                update quo;

                ins_quo.Custom_Price_Total_Text__c = newCustomPrice;
                update ins_quo;
System.debug('=====update quo');

                ins_opp.SyncedQuoteId = ins_quo.Id;
                update ins_opp;
System.debug('=====update ins_opp');
            } else {
                List<OpportunityLineItem> ins_oliList1 = new List<OpportunityLineItem>();
                List<OpportunityLineItem> ins_oliList2 = new List<OpportunityLineItem>();
                for (LineInfo li : lineinfo) {
                    if (li.divideCnt == li.oi.Quantity) {
                        OpportunityLineItem ins_oli2 = new OpportunityLineItem();
                        ins_oli2.Description = li.oi.Description;
                        ins_oli2.DescriptionD__c = li.oi.Description;
                        ins_oli2.Quantity = li.divideCnt;
                        ins_oli2.QuantityD__c = li.divideCnt;
                        ins_oli2.PricebookEntryId = li.oi.PricebookEntryId;
                        ins_oli2.UnitPrice = li.oi.UnitPrice;
                        ins_oli2.UnitPriceD__c = li.oi.UnitPrice;
                        ins_oli2.OpportunityId = ins_opp.Id;
                        ins_oli2.IsNew__c = false;
                        ins_oli2.Discount = ins_opp.Quote_Discount__c;
                        ins_oli2.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
                        ins_oli2.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
                        ins_oliList2.add(ins_oli2);
                    } else if (li.divideCnt > 0 && li.divideCnt <= li.oi.Quantity) {
                        OpportunityLineItem ins_oli1 = new OpportunityLineItem();
                        ins_oli1.Description = li.oi.Description;
                        ins_oli1.DescriptionD__c = li.oi.Description;
                        ins_oli1.Quantity = li.oi.Quantity - li.divideCnt;
                        ins_oli1.QuantityD__c = li.oi.Quantity - li.divideCnt;
                        ins_oli1.PricebookEntryId = li.oi.PricebookEntryId;
                        ins_oli1.UnitPrice = li.oi.UnitPrice;
                        ins_oli1.UnitPriceD__c = li.oi.UnitPrice;
                        ins_oli1.OpportunityId = opp.Id;
                        ins_oli1.IsNew__c = false;
                        ins_oli1.Discount = opp.Quote_Discount__c;
                        ins_oli1.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
                        ins_oli1.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
                        ins_oliList1.add(ins_oli1);

                        OpportunityLineItem ins_oli2 = new OpportunityLineItem();
                        ins_oli2.Description = li.oi.Description;
                        ins_oli2.DescriptionD__c = li.oi.Description;
                        ins_oli2.Quantity = li.divideCnt;
                        ins_oli2.QuantityD__c = li.divideCnt;
                        ins_oli2.PricebookEntryId = li.oi.PricebookEntryId;
                        ins_oli2.UnitPrice = li.oi.UnitPrice;
                        ins_oli2.UnitPriceD__c = li.oi.UnitPrice;
                        ins_oli2.OpportunityId = ins_opp.Id;
                        ins_oli2.IsNew__c = false;
                        ins_oli2.Discount = ins_opp.Quote_Discount__c;
                        ins_oli2.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
                        ins_oli2.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
                        ins_oliList2.add(ins_oli2);
                    } else {
                        OpportunityLineItem ins_oli1 = new OpportunityLineItem();
                        ins_oli1.Description = li.oi.Description;
                        ins_oli1.DescriptionD__c = li.oi.Description;
                        ins_oli1.Quantity = li.oi.Quantity;
                        ins_oli1.QuantityD__c = li.oi.Quantity;
                        ins_oli1.PricebookEntryId = li.oi.PricebookEntryId;
                        ins_oli1.UnitPrice = li.oi.UnitPrice;
                        ins_oli1.UnitPriceD__c = li.oi.UnitPrice;
                        ins_oli1.OpportunityId = opp.Id;
                        ins_oli1.IsNew__c = false;
                        ins_oli1.Discount = opp.Quote_Discount__c;
                        ins_oli1.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
                        ins_oli1.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
                        ins_oliList1.add(ins_oli1);
                    }
                }

                if (oliList.size() > 0) delete oliList;
                if (ins_oliList1.size() > 0) insert ins_oliList1;
                if (ins_oliList2.size() > 0) insert ins_oliList2;
System.debug('=====ins_oliList1');
            }

            // 同步代理商的数量字段
            List<OpportunityLineItem> upd_oli = new List<OpportunityLineItem>();
            List<OpportunityLineItem> oliList2 = [select Id, Quantity, QuantityD__c from OpportunityLineItem where OpportunityId = :opp.Id];
            for (OpportunityLineItem oli : oliList2) {
                if (oli.Quantity != oli.QuantityD__c) {
                    oli.QuantityD__c = oli.Quantity;
                    upd_oli.add(oli);
                }
            }
            if (upd_oli.size() > 0) update upd_oli;
System.debug('=====update upd_oli');
            // 复制合同
            Opportunity ins_opp_view = [select Id,Quote_Discount__c,Quote_Subtotal__c,Quote_TotalPrice__c,Quote_CustomPrice__c,
                                               SyncedQuoteId,SyncedQuote.Discount,SyncedQuote.Subtotal,SyncedQuote.TotalPrice,SyncedQuote.Custom_Price_Total__c,
                                               SyncedQuote.Custom_Price_Total_Text__c,IE_local_cost__c
                                          from Opportunity where Id = :ins_opp.Id];
            Order ins_odr = odr.clone();
            ins_odr.Id = null;
            ins_odr.OpportunityId = ins_opp.Id;
            if (ins_quo != null) {
                ins_odr.QuoteId = ins_quo.Id;
            }
            ins_odr.org_order__c = odr.Id;
            ins_odr.Name = null;
            ins_odr.ContractCode__c = null;
            ins_odr.Split_Approved__c = false;
            //ins_odr.product_approval__c = false;
            ins_odr.Is_Already_Splited__c = true;
            Decimal quoteDiscount = ins_opp_view.Quote_Discount__c;
            ins_odr.Discount__c = quoteDiscount.setScale(4, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_Discount__c;
            ins_odr.Discount_D__c = quoteDiscount.setScale(4, System.RoundingMode.HALF_UP);
            Decimal quoteSubtotal = ins_opp_view.Quote_Subtotal__c;
            ins_odr.Olympus_Price_BeforeDiscount__c = quoteSubtotal.setScale(2, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_Subtotal__c;
            ins_odr.Olympus_Price_BeforeDiscount_D__c = quoteSubtotal.setScale(2, System.RoundingMode.HALF_UP);
            Decimal quoteTotalPrice = ins_opp_view.Quote_TotalPrice__c;
            if(odr.ProductSegment__c != 'NDT' && odr.ProductSegment__c != 'ANI'){
                ins_odr.OlympusContractPrices__c = quoteTotalPrice.setScale(0, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_TotalPrice__c;
                ins_odr.OlympusContractPricesD__c = quoteTotalPrice.setScale(0, System.RoundingMode.HALF_UP);
            }else{
                ins_odr.OlympusContractPrices__c = quoteTotalPrice;//ins_opp_view.Quote_TotalPrice__c;
                ins_odr.OlympusContractPricesD__c = quoteTotalPrice;
            }
            Decimal quoteCustomPrice = ins_opp_view.Quote_CustomPrice__c;
            ins_odr.CustomerContractPrice__c = quoteCustomPrice.setScale(2, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_CustomPrice__c;
            ins_odr.CustomerContractPriceD__c = quoteCustomPrice.setScale(2, System.RoundingMode.HALF_UP);
            if (is_IE) {
                Decimal oppCost = ins_opp_view.IE_local_cost__c == null ? 0 : ins_opp_view.IE_local_cost__c;
                ins_odr.Cost__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
                ins_odr.Cost_D__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
            }
            if (ins_odr.ApproveStatus__c == 'Submit') {
                ins_odr.ApproveStatus__c = 'Draft';
            } else if (ins_odr.ApproveStatus__c == 'OrderSubmit') {
                ins_odr.ApproveStatus__c = 'OrderDraft';
            } else {
                // 保持状态
                
            }
            ins_odr.IsUpload__c = false;
            insert ins_odr;
System.debug('=====ins_odr');

            List<OrderItem> upd_oiList = new List<OrderItem>();
            List<OrderItem> del_oiList = new List<OrderItem>();
            //List<OrderItem> ins_oiList = new List<OrderItem>();
            if(odr.ProductSegment__c == 'BS'){
                List<QuoteLineItem> tempList = [select Id, QuoteId, Description, Quantity, PricebookEntryId, UnitPrice from QuoteLineItem where QuoteId = :quo.Id];
                for( QuoteLineItem qli : tempList){
                    OrderItem oi = new OrderItem();
                    oi.Description = qli.Description;
                    oi.Quantity = qli.Quantity;
                    oi.PricebookEntryId = qli.PricebookEntryId;
                    oi.UnitPrice = qli.UnitPrice;
                    oi.OrderId = odr.Id;
                    oi.QuoteLineItemId = qli.Id;
                    upd_oiList.add(oi);
                }
                del_oiList = [select Id from OrderItem where OrderId = :odr.Id];

                
            }else{
                for (LineInfo li : lineinfo) {
                    if (li.divideCnt == li.oi.Quantity) {
                        //
                        OrderItem del_oi = new OrderItem(Id = li.oi.Id);
                        del_oiList.add(del_oi);
                        //
                        /*OrderItem ins_oi = li.oi.clone();
                        ins_oi.Id = null;
                        ins_oi.OrderId = ins_odr.Id;
                        ins_oiList.add(ins_oi);*/
                    } else if (li.divideCnt > 0 && li.divideCnt <= li.oi.Quantity) {
                        //
                        OrderItem upd_oi = li.oi;
                        upd_oi.Quantity = upd_oi.Quantity - li.divideCnt;
                        upd_oiList.add(upd_oi);
                        //
                        /*OrderItem ins_oi = li.oi.clone();
                        ins_oi.Id = null;
                        ins_oi.OrderId = ins_odr.Id;
                        ins_oi.Quantity = li.divideCnt;
                        ins_oiList.add(ins_oi);*/
                    } else {
                        // 不做处理
                    }
                }
            }
            
          
                List<DecideQuoteProductSet__c> del_dqpList = new List<DecideQuoteProductSet__c>();
                List<DecideQuoteProductSet__c> ins_dqpList = new List<DecideQuoteProductSet__c>();
                List<DecideQuoteProductSet__c> upd_dqpList = new  List<DecideQuoteProductSet__c>();
                for (LineInfo li : lineinfo) {
                    if(li.isSet == true){
                        // 全部分割
                        if (li.divideCnt == li.dqps.DecideProductSetCount__c) {
                            // 删除原报价产品
                            DecideQuoteProductSet__c del_dqp = new DecideQuoteProductSet__c(Id = li.dqps.Id);
                            del_dqpList.add(del_dqp);
                            // 全部分割到新报价
                            DecideQuoteProductSet__c ins_dqp = li.dqps.clone();
                            ins_dqp.Id = null;
                            ins_dqp.DecideQuote__c = ins_quo.Id;
                            ins_dqp.DecideOrder__c = ins_odr.Id;
                            ins_dqp.DecideOpportunity__c = ins_opp.Id;

                            ins_dqpList.add(ins_dqp);
                        // 部分分割
                        } else if (li.divideCnt > 0 && li.divideCnt <= li.dqps.DecideProductSetCount__c) {
                            // 更新原报价产品数量
                            DecideQuoteProductSet__c upd_dqp = li.dqps;
                            upd_dqp.DecideProductSetCount__c = upd_dqp.DecideProductSetCount__c - li.divideCnt;
                            upd_dqp.DecideProductSetTotalprice__c = upd_dqp.DecideProductSetUnivalence__c * upd_dqp.DecideProductSetCount__c;
                            upd_dqpList.add(upd_dqp);
            
                            // 部分分割到新报价
                           DecideQuoteProductSet__c ins_dqp = li.dqps.clone();
                            ins_dqp.Id = null;
                            ins_dqp.DecideQuote__c = ins_quo.Id;
                            ins_dqp.DecideOrder__c = ins_odr.Id;
                            ins_dqp.DecideOpportunity__c = ins_opp.Id;
                            ins_dqp.DecideProductSetCount__c = li.divideCnt;
                            ins_dqp.DecideProductSetTotalprice__c = ins_dqp.DecideProductSetUnivalence__c * ins_dqp.DecideProductSetCount__c;

                            ins_dqpList.add(ins_dqp);
                        // 未分割
                        } else{
                            // 不做处理
                           
                        } 
                    }
                }
                System.debug(ins_dqpList);
                System.debug(upd_dqpList);
                System.debug(del_dqpList);
                if(ins_dqpList.size() > 0 ) insert ins_dqpList;
                if(upd_dqpList.size() > 0 ) update upd_dqpList;
                if(del_dqpList.size() > 0 ) delete del_dqpList;
           

            


/*            if (upd_oiList.size() > 0) update upd_oiList;
            if (del_oiList.size() > 0) delete del_oiList;
            //if (ins_oiList.size() > 0) insert ins_oiList;
System.debug('=====ins_oiList');*/

            Opportunity opp_view = [select Id,Quote_Discount__c,Quote_Subtotal__c,Quote_TotalPrice__c,Quote_CustomPrice__c,IE_local_cost__c from Opportunity where Id = :opp.Id];
            odr.Split_Approved__c = false;
            //odr.product_approval__c = false;
            odr.Is_Already_Splited__c = true;
            Decimal quoteDiscount1 = opp_view.Quote_Discount__c;
            odr.Discount__c = quoteDiscount1.setScale(4, System.RoundingMode.HALF_UP);//opp_view.Quote_Discount__c;
            odr.Discount_D__c = quoteDiscount1.setScale(4, System.RoundingMode.HALF_UP);
            Decimal quoteSubtotal1 = opp_view.Quote_Subtotal__c;
            odr.Olympus_Price_BeforeDiscount__c = quoteSubtotal1.setScale(2, System.RoundingMode.HALF_UP);//opp_view.Quote_Subtotal__c;
            odr.Olympus_Price_BeforeDiscount_D__c = quoteSubtotal1.setScale(2, System.RoundingMode.HALF_UP);
            Decimal quoteTotalPrice1 = opp_view.Quote_TotalPrice__c;
            if(odr.ProductSegment__c != 'NDT' && odr.ProductSegment__c != 'ANI'){
                odr.OlympusContractPrices__c = quoteTotalPrice1.setScale(0, System.RoundingMode.HALF_UP);//opp_view.Quote_TotalPrice__c;
                odr.OlympusContractPricesD__c = quoteTotalPrice1.setScale(0, System.RoundingMode.HALF_UP);
            }else{
                odr.OlympusContractPrices__c = quoteTotalPrice1;//opp_view.Quote_TotalPrice__c;
                odr.OlympusContractPricesD__c = quoteTotalPrice1;
            }
            Decimal quoteCustomPrice1 = opp_view.Quote_CustomPrice__c;
            odr.CustomerContractPrice__c = quoteCustomPrice1.setScale(2, System.RoundingMode.HALF_UP);//opp_view.Quote_CustomPrice__c;
            odr.CustomerContractPriceD__c = quoteCustomPrice1.setScale(2, System.RoundingMode.HALF_UP);
            if (is_IE) {
                Decimal oppCost = opp_view.IE_local_cost__c == null ? 0 : opp_view.IE_local_cost__c;
                odr.Cost__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
                odr.Cost_D__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
            }
            if (odr.ApproveStatus__c == 'Submit') {
                odr.ApproveStatus__c = 'Draft';
               
           
            } else if (odr.ApproveStatus__c == 'OrderSubmit') {
                odr.ApproveStatus__c = 'OrderDraft';
               
          
            } else {
                // 保持状态

            }
            update odr;
System.debug('=====update odr');

            if (upd_oiList.size() > 0 && odr.ProductSegment__c == 'BS'){
                System.debug('upd_oilist' + upd_oiList);
                insert upd_oiList;
            }else if(upd_oiList.size() > 0) {
                update upd_oiList;
            }
            if (del_oiList.size() > 0) delete del_oiList;
            //if (ins_oiList.size() > 0) insert ins_oiList;
System.debug('=====ins_oiList');
            //OrderWebService.updItems(odr.OpportunityId, odr.Id);
           //王鹏伟 开始 合同分割同步分割贸易管理客户申请表
            if(ins_odr!=null && ins_odr.Id!=null){
                Schema.DescribeSobjectResult tradeFields = TradeCustomerManager__c.sObjectType.getDescribe();
                Map<String, Schema.SObjectField> tradeFields_map = tradeFields.fields.getMap();
                String tradeList_sql = 'select ';
                String fields_trade = '';
                for (String field : tradeFields_map.keySet()) {
                    if (fields_trade.length() > 0) {
                        fields_trade += ', ';
                    }
                    fields_trade += field;
                }
                tradeList_sql += fields_trade;
                tradeList_sql += ' from TradeCustomerManager__c where order__c = \'' + odr.Id + '\'';
                List<TradeCustomerManager__c> tradeList = Database.query(tradeList_sql);
                if(tradeList!=null && tradeList.size()!=0){
                    TradeCustomerManager__c newTrade = tradeList[0].clone();
                    newTrade.Id = null;
                    newTrade.OrderIdSave__c = ins_odr.Id;
                    newTrade.order__c = ins_odr.Id;
                    insert newTrade;
                }
            }
            //王鹏伟 结束

            String url = baseUrl;
            url += '\\' + ins_odr.Id;
            return new Pagereference(url);
            //Database.rollback(sp);
            //return null;
        } catch (Exception ex) {
            Database.rollback(sp);
System.debug('=====Exception:' + ex.getMessage() + ' | Line:' + ex.getLineNumber());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
            return null;
        }
        return null;
    }


    public static Boolean IfspecialDealer(String oppDealerId) {
        if (String.isBlank(oppDealerId)) {
            return false;
        }
        return StaticParameter.specialDealerMap.containsKey(oppDealerId.substring(0, 15)) && UserInfo.getUserType() == 'PowerPartner';
    }

    public PageReference BackBtn() {
        String url = baseUrl;
        if (rtUrl != null && rtUrl.length() > 0) {
            url += rtUrl.replace('/production', '');
        } else {
            url += '\\' + odrId;
        }
        return new Pagereference(url);
    }

    public class LineInfo {
        public Integer lineNo { get; set; }
        public String productName { get; set; }
        public String ProductCode { get; set; }
        public String ECCode { get; set; }
        public OrderItem oi { get; set; }
        public Integer divideCnt { get; set; }
        //产品配套
        public DecideQuoteProductSet__c dqps {get; set; }
        public Boolean isSet {get; set;}

        public LineInfo(Integer in_i, OrderItem in_oi) {
            lineNo = in_i;
            productName = in_oi.PricebookEntry.Product2.Name;
            ProductCode = in_oi.PricebookEntry.Product2.ProductCode;
            ECCode = in_oi.PricebookEntry.Product2.Product_ECCode__c;
            oi = in_oi;
            divideCnt = 0;
            isSet = false;
        }

        public LineInfo(Integer in_i,DecideQuoteProductSet__c in_dqps){
            lineNo = in_i;
            productName = in_dqps.DecideProductSetName__c;
            ProductCode = in_dqps.DecideProductSetCode__c;
            ECCode = '';
            dqps = in_dqps;
            divideCnt = 0;
            isSet = true;
        }
    }






























































































    private void tes(){
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}