/**
 * 跨区销售切换合作代理商和原代理商
 */
public without sharing class CopyOpportunityController {

    // 链接地址
    public String baseUrl { get; set; }
    public String rtUrl { get; set; }

    public String OppId {get; set;}      // 询价id
    public String QuoteId {get; set;}   // 报价id

    public Opportunity opportunity {get; set;} //原询价
    public Quote quote {get; set;}      //原报价

    /**
     * 无参构造方法
     * @author Dai Y
     * @date   2022-02-28
     * @return null
     */
    public CopyOpportunityController() {
        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 = '';
        }
        OppId = System.currentPageReference().getParameters().get('OppId');
        QuoteId = System.currentPageReference().getParameters().get('QuotesId');
    }

    /**
     * 初始化方法
     * @author Dai Y
     * @date   2022-02-28
     * @return null
     */
    public void  init(){        
        opportunity = [select id,ProductSegment__c,Dealer__c,DealerSelectOwner__c,HeadOfCooperationArea__c,CrossCooperativeDealer__c from Opportunity where id =:OppId];
        Opportunity.Dealer__c = null;
        Opportunity.DealerSelectOwner__c = null;
        Opportunity.HeadOfCooperationArea__c = null;
        Opportunity.CrossCooperativeDealer__c = null;

    }

    /**
     * 保存方法
     * @author Dai Y
     * @date   2022-02-28
     */
    public PageReference Save(){

        Opportunity opp = null;
        List<OpportunityLineItem> oliList = null;
        List<OpportunityContactRole> ocrList = null;
        List<OpportunityTeamMember> otmList = null;
        //Schema.DescribeSobjectResult d_opp = Opportunity.sObjectType.getDescribe();
        schema.describeSObjectresult d = schema.Opportunity.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> d_opp_map = d.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 = \'' + OppId + '\'';
        //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 = :OppId];
            ocrList = [select Id, OpportunityId, ContactId, Role, IsPrimary from OpportunityContactRole where OpportunityId = :OppId];
            otmList = [select id, userId,teamMemberRole,opportunityId,OpportunityAccessLevel from OpportunityTeamMember where OpportunityId = :OppId];
        }
        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 = schema.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 = \'' + 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 = :QuoteId];
            for (QuoteLineItem qli : qliList) {
                qliMap.put(qli.Id, qli);
            }
        }


        System.debug(opp);
        System.debug(oliList);
        System.debug(ocrList);
        System.debug(quo);
        System.debug(qliList);


        // 跳过询价状态写入限制
        StaticParameter.StageProgressBarUpdate = true;

        Savepoint sp = Database.setSavepoint();
        try {

            Opportunity ins_opp = opp.clone();
            opp.Is_Decided__c = false;
            update opp;

            System.debug('=====update opp');
            ins_opp.Id = null;
            ins_opp.SyncedQuoteId = null;
            ins_opp.Is_Decided__c = false;
            ins_opp.DealerSelectOwner__c = opportunity.DealerSelectOwner__c;
            ins_opp.HeadOfCooperationArea__c = opportunity.HeadOfCooperationArea__c;
            ins_opp.Dealer__c = opportunity.Dealer__c;
            ins_opp.CrossCooperativeDealer__c = opportunity.CrossCooperativeDealer__c;
            ins_opp.the_Upload_of_quotation_number__c = null;
            //ins_opp.org_opportunity__c = opp.Id;
            insert 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;

            List<OpportunityTeamMember> ins_otmList = new List<OpportunityTeamMember>();
            for (OpportunityTeamMember otm : otmList ) {
                OpportunityTeamMember ins_otm = otm.clone();
                ins_otm.OpportunityId = ins_opp.Id;
                ins_otm.Id = null;
            }

            if (ins_otmList.size() >0 ) {
                insert ins_otmList;
            }

            // 复制报价
            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;

            List<QuoteLineItem> ins_qliList = new List<QuoteLineItem>();
            if (ins_quo != null) {
                for (QuoteLineItem qli : qliList) {
                    QuoteLineItem ins_qli = qli.clone();
                    ins_qli.Id = null;
                    ins_qli.QuoteId = ins_quo.Id;

                    ins_qliList.add(ins_qli);
                }
            }

            if (ins_qliList.size() > 0) insert ins_qliList;

            String url = baseUrl;
            url += '\\' + ins_opp.Id;
            return new Pagereference(url);

        }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 PageReference BackBtn() {
        return null;
    }
    /**
     * 数据检查方法   
     * @author Dai Y
     * @date   2022-03-01
     * @return 数据合格返回 true
     */
    private boolean DateCheck (){
        Boolean flag = true ; //合格标记，初始为true

        

        return flag;
    }

}