public with sharing class SpecialPriceController {
    public String accountId { get; set; }
    public String dpId { get; set; }
    public Boolean isInput { get; set;}
    //public List<product2Info> productInfoList = new List<product2Info>();
    public List<product2Info> productInfoListview { get; set; }
    public Account acc { get; set; }
    public Dealer_Product__c dpc { get; set; }
    public Integer productRecoedsCount { get; set; }
    //错误信息
    public String alertMessage {set;get;}
    //
    public Boolean productSearch;

    //page
    Public Integer pagesize{get; set;} 
    Public Integer totalcount{get; set;} 
    Public Integer pagecount{get; set;} 
    Public Integer currentpage{get; set;} 
    public Boolean hasPrevious{get; set;}
    public Boolean hasNext{get; set;}

    Map<Id,Dealer_Product__c> ExistProdSDMap = new Map<Id,Dealer_Product__c> ();

    //1-5分类选项
    public String keyword { get; set; }
    public String category1 { get; set; }
    public String category2 { get; set; }
    public String category3 { get; set; }
    public String category4 { get; set; }
    public String category5 { get; set; }
    public String SpecialDiscount{ get; set; }
    public List<SelectOption> category1OptionList{get;set;}
    public List<SelectOption> category2OptionList{get;set;}
    public List<SelectOption> category3OptionList{get;set;}
    public List<SelectOption> category4OptionList{get;set;}
    public List<SelectOption> category5OptionList{get;set;}

    public SpecialPriceController() {
        productSearch = false;
        accountId = ApexPages.currentPage().getParameters().get('userid');
        dpId = ApexPages.currentPage().getParameters().get('id');
        //page
        pagesize = Integer.valueof(system.label.orderdetLimitsize);
        currentpage = 0;
    }

    public void init(){
        geCategory();
        //查询合同
        if (accountId != null && accountId != '') {
            acc = [SELECT Id,Name,Parent.Name,Parent.Management_Code__c,ET_SP_Dealer__c,ENG_Dealer__c FROM Account WHERE Id = :accountId];
        }else{
            return ;
        }
        String soql = 'select Id, Name,Name__c,Asset_Model_No__c,Category1__c,Category2__c,Category3__c,Category4__c,Category5__c,SFDA_Status__c FROM Product2__c ';
        soql += ' where Estimation_Entry_Possibility__c = \'○\' ';
        if (acc.ET_SP_Dealer__c) {
            soql += ' AND Pro2_Dealer_Object__c = true ';
        }
        if (acc.ENG_Dealer__c) {
            soql += ' AND Pro2_Dealer_ENG__c = true ';
        }
        soql += ' order by Name__c';
        List<Product2__c> product2Selected = new List<Product2__c>();
        product2Selected = Database.query(soql);

        ExistProdSDMap = new Map<Id,Dealer_Product__c>();
        //待展示的产品
        List<product2Info> productInfoList = new List<product2Info>();
        productInfoListview = new List<product2Info>();
        dpc = new Dealer_Product__c();

        for (Integer i = 0; i < product2Selected.size(); i++) {
            productInfoList.add(new product2Info(product2Selected[i]));
        }

        //已存在的特殊折扣
        List<Dealer_Product__c> dealerProductList = [select Id, Special_Discount__c,Dealer_Product2__c,Special_Campaign_Price__c  
                                    FROM Dealer_Product__c
                                    WHERE Dealer_Contact__c = :acc.Id
                                    AND (Special_Discount__c != null or Special_Campaign_Price__c != null) 
                                    AND Campaign_StartDate__c = null 
                                    AND Campaign_EndDate__c = null];
        for(Dealer_Product__c ahlc : dealerProductList){
            ExistProdSDMap.put(ahlc.Dealer_Product2__c, ahlc);
        }


        //1.编辑界面进来
        if (dpId != null && dpId != '' && accountId != null && accountId != '') {
            //判断特价产品申请的状态 -> 只有草案中可以编辑
            DiscountProductApplication__c dpc = [select id,Dealer_Contact__c,ApplicationStatus__c from DiscountProductApplication__c where id = :dpId];
            if (dpc.ApplicationStatus__c == '草案中') {
                isInput = false;
            }else{
                isInput = true;
                category1OptionList = new List<SelectOption>();
                category1OptionList.add(new SelectOption('', '--无--'));
            }

            // 获取特价产品明细
            //需要修改的产品-->需要默认选中的产品
            Map<String,DiscountProductApplicationDetail__c> checkMap = new Map<String,DiscountProductApplicationDetail__c>();
            List<DiscountProductApplicationDetail__c> dpadcList = [select Id,Special_Discount__c,ProductDiscount__c,Product2__c from DiscountProductApplicationDetail__c where DiscountProductApplication__c = :dpId];
            if (dpadcList != null && dpadcList.size() > 0) {
                for (DiscountProductApplicationDetail__c dpadc : dpadcList ) {
                    checkMap.put(dpadc.Product2__c,dpadc);
                }
            }

            List<product2Info> pd2List = new List<product2Info>();
            for(product2Info prd : productInfoList){
                if (checkMap.containsKey(prd.pro.Id)) {
                    prd.check = true;
                    if(ExistProdSDMap.containsKey(prd.pro.Id)){
                        prd.dealerPro = ExistProdSDMap.get(prd.pro.Id);
                    }
                    prd.dpac = checkMap.get(prd.pro.Id);
                    pd2List.add(prd);
                }
            }
            productInfoList = pd2List;
        }else {
            //不是编辑界面进来
            for(product2Info prd : productInfoList){
                if(ExistProdSDMap.containsKey(prd.pro.Id)){
                    Dealer_Product__c dpc = ExistProdSDMap.get(prd.pro.Id);
                    prd.dealerPro = dpc;
                    prd.dpac.Special_Discount__c = dpc.Special_Discount__c;
                    prd.dpac.ProductDiscount__c = dpc.Special_Campaign_Price__c;
                    prd.orderby = true;
                }
            }
            productInfoList.sort();
        }

        //总件数
        totalcount = productInfoList.size();
        //页数
        pagecount=(totalcount  +  pagesize  - 1) / pagesize;
        //显示第一页
        moveToFirst();
        makeCurrentPageRecords(productInfoList);
        // productInfoListview.sort();

    }


    public void geCategory(){
        AggregateResult[] categoryList = [select Count(id), Category1_text__c c1c from Product2__c group by Category1_text__c];
        category1OptionList = new List<SelectOption>();
        category1OptionList.add(new SelectOption('', '--无--'));
        for(AggregateResult category3Search : categoryList) {
            String deliverycnt = String.valueOf(category3Search.get('c1c'));
            if(String.isNotBlank(deliverycnt)){
                category1OptionList.add(new SelectOption(deliverycnt,deliverycnt));
            }
        }
        category2OptionList = new List<SelectOption>();
        category2OptionList.add(new SelectOption('', '--无--'));
        category3OptionList = new List<SelectOption>();
        category3OptionList.add(new SelectOption('', '--无--'));
        category4OptionList = new List<SelectOption>();
        category4OptionList.add(new SelectOption('', '--无--'));
        category5OptionList = new List<SelectOption>();
        category5OptionList.add(new SelectOption('', '--无--'));
    }

    public void showcategory2() {
        AggregateResult[] categoryList = [select Count(id), Category2_text__c c2c from Product2__c WHERE Category1_text__c = :category1  group by Category2_text__c];
        category2OptionList = new List<SelectOption>();
        category2OptionList.add(new SelectOption('', '--无--'));
        for(AggregateResult category3Search : categoryList) {
            String deliverycnt = String.valueOf(category3Search.get('c2c'));
            if(String.isNotBlank(deliverycnt)){
                category2OptionList.add(new SelectOption(deliverycnt,deliverycnt));
            }
        }

    }

    public void showcategory3() {
        AggregateResult[] categoryList = [select Count(id), Category3_text__c c3c from Product2__c WHERE Category1_text__c = :category1 AND Category2_text__c = :category2  group by Category3_text__c];
        category3OptionList = new List<SelectOption>();
        category3OptionList.add(new SelectOption('', '--无--'));
        for(AggregateResult category3Search : categoryList) {
            String deliverycnt = String.valueOf(category3Search.get('c3c'));
            if(String.isNotBlank(deliverycnt)){
                category3OptionList.add(new SelectOption(deliverycnt,deliverycnt));
            }
        }

    }
    public void showcategory4() {
        AggregateResult[] categoryList = [select Count(id), Category4_text__c c4c from Product2__c WHERE Category1_text__c = :category1 AND Category2_text__c = :category2 AND Category3_text__c = :category3  group by Category4_text__c];
        category4OptionList = new List<SelectOption>();
        category4OptionList.add(new SelectOption('', '--无--'));
        for(AggregateResult category3Search : categoryList) {
            String deliverycnt = String.valueOf(category3Search.get('c4c'));
            if(String.isNotBlank(deliverycnt)){
                category4OptionList.add(new SelectOption(deliverycnt,deliverycnt));
            }
        }

    }
    public void showcategory5() {
        AggregateResult[] categoryList = [select Count(id), Category5_text__c c5c from Product2__c WHERE Category1_text__c = :category1 AND Category2_text__c = :category2 AND Category3_text__c = :category3 AND Category4_text__c = :category4  group by Category5_text__c];
        category5OptionList = new List<SelectOption>();
        category5OptionList.add(new SelectOption('', '--无--'));
        for(AggregateResult category3Search : categoryList) {
            String deliverycnt = String.valueOf(category3Search.get('c5c'));
            if(String.isNotBlank(deliverycnt)){
                category5OptionList.add(new SelectOption(deliverycnt,deliverycnt));
            }
        }

    }

    public PageReference save() {        
        //错误信息展示
        Integer count = 0;
        for(product2Info proinfo:productInfoListview){
            if(proinfo.check == true){
                count ++;
            }
        }
        if (count == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请选择产品'));
            return null;
        }
        //需要添加的数据 特价产品申请 & 特价产品申请明细
        DiscountProductApplication__c dis = new DiscountProductApplication__c();
        List<DiscountProductApplicationDetail__c> Inds = new List<DiscountProductApplicationDetail__c>();

        Savepoint sp = Database.setSavepoint();
        try{
            //新建特价申请时
            if (String.isBlank(dpId)) {
                dis.Dealer_Contact__c = accountId;
                dis.ApplicationStatus__c = '草案中';
                dis.RecordTypeId = [select Id from RecordType where IsActive = true and DeveloperName = 'ProductDiscount'].Id;
                insert dis;
                
            }
            //修改特价申请时 -> 将该特价申请下的所有明细都删掉 再新增
            if (String.isNotBlank(dpId)) {
                dis.id = dpId;
                dis.ApplicationStatus__c = '草案中';
                update dis;

                //直接判断该特价申请下的明细即可 因为只有草案中的时候才可以进行编辑
                List<DiscountProductApplicationDetail__c> dpadcList = [select Id,Special_Discount__c,ProductDiscount__c,Product2__c from DiscountProductApplicationDetail__c where DiscountProductApplication__c = :dpId];
                if (dpadcList!= null && dpadcList.size() > 0) {
                    delete dpadcList;
                }
            }
            for(product2Info proinfo:productInfoListview){
                //如果该产品被选中
                if(proinfo.check == true){
                    DiscountProductApplicationDetail__c dpadc = new DiscountProductApplicationDetail__c();
                    dpadc.DiscountProductApplication__c = dis.Id;
                    dpadc.Special_Discount__c = proinfo.dpac.Special_Discount__c;
                    dpadc.ProductDiscount__c = proinfo.dpac.ProductDiscount__c;
                    dpadc.Product2__c = proinfo.pro.Id;
                    if (proinfo.dealerPro != null) {
                        dpadc.DealerProductId__c = proinfo.dealerPro.Id;
                    }
                    Inds.add(dpadc);
                }
            }
            
            if (Inds.size() > 0 ) {
                upsert Inds;
            } 
            dpId = dis.Id;
        }catch(Exception e){
            ApexPages.addMessages(e);
            Database.rollback(sp);
            return null;
        }
        return setpage();
    }


    public PageReference setpage(){
        PageReference ref = new Pagereference('/' + dpId);
        ref.setRedirect(true);
        return ref;
    }

    // 检索
    public void searchProduct() {

        productSearch = true;
        //所有的产品
        List<product2Info> productInfoList = new List<product2Info>();
        //检索产品
        String soql = this.makeSoql(category1,category2,category3,category4,category5,keyword);
        List<Product2__c> product2Selected = Database.query(soql);
        for (Integer i = 0; i < product2Selected.size(); i++) {
            productInfoList.add(new product2Info(product2Selected[i]));
        }
        List<Dealer_Product__c> dealerProductList = [select Id, Special_Discount__c,Dealer_Product2__c,Special_Campaign_Price__c  
                                    FROM Dealer_Product__c
                                    WHERE Dealer_Contact__c = :accountId
                                    AND (Special_Discount__c != null or Special_Campaign_Price__c != null)
                                    AND Campaign_StartDate__c = null 
                                    AND Campaign_EndDate__c = null];
        for(Dealer_Product__c ahlc : dealerProductList){
            ExistProdSDMap.put(ahlc.Dealer_Product2__c, ahlc);
        }

        for(product2Info prd : productInfoList){
            if(ExistProdSDMap.containsKey(prd.pro.Id)){
                prd.dealerPro = ExistProdSDMap.get(prd.pro.Id);
                prd.orderby = true;
            }
        }

        List<product2Info> tempInfoList = new List<product2Info>();
        //获取选中的产品
        Map<Id,product2Info> infoMap = new Map<Id,product2Info>();

        for (product2Info info : productInfoListview) {       
            if (info.check) {
                infoMap.put(info.pro.Id, info);    
                tempInfoList.add(info);     
            }
        }

        for(product2Info prd : productInfoList){
            if (!infoMap.containsKey(prd.pro.Id)) {
                prd.dpac.Special_Discount__c = prd.dealerPro.Special_Discount__c;
                prd.dpac.ProductDiscount__c = prd.dealerPro.Special_Campaign_Price__c;
                tempInfoList.add(prd);
            }
            // if (infoMap.containsKey(prd.pro.Id)) {
            //     prd.check = true;
         //        prd.dpac = infoMap.get(prd.pro.Id).dpac;
            // }else {
         //        prd.dpac.Special_Discount__c = prd.dealerPro.Special_Discount__c;
         //        prd.dpac.ProductDiscount__c = prd.dealerPro.Special_Campaign_Price__c;
         //    }
        }
        tempInfoList.sort();

        //总件数
        // totalcount = productInfoList.size();
        totalcount = tempInfoList.size();
        //页数
        pagecount=(totalcount  +  pagesize  - 1) / pagesize; 
        //显示第一页
        moveToFirst();
        // makeCurrentPageRecords(productInfoList);
        makeCurrentPageRecords(tempInfoList);
        // getInfo(productInfoList);
        // productInfoListview.addAll(productInfoList);

    }

    //产品检索
    public String makeSoql(String category1,String category2,String category3,String category4,String category5,String keyword){
        String soql = 'select Id, Name,Name__c,Asset_Model_No__c,Category1__c,Category2__c,Category3__c,Category4__c,';
        soql += ' Category5__c,SFDA_Status__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\'';
        if(String.isNotBlank(category1)){
            soql += ' AND Category1__c = \'' +  category1 + '\'';
        }
        if(String.isNotBlank(category2)){
            soql += ' AND Category2__c = \'' +  category2 + '\'';
        }
        if(String.isNotBlank(category3)){
            soql += ' AND Category3__c = \'' +  category3 + '\'';
        }
        if(String.isNotBlank(category4)){
            soql += ' AND Category4__c = \'' +  category4 + '\'';
        }
        if(String.isNotBlank(category5)){
            soql += ' AND Category5__c = \'' +  category5 + '\'';
        }
        if(String.isNotBlank(keyword)){
            soql += ' AND Name__c like \'%' + String.escapeSingleQuotes(keyword.replaceAll('%', '\\%')) + '%\'';
        }
        //add by rentx 2020-12-23 start
        // if(Pro2DealerFlag){
        //     soql += ' AND Pro2_Dealer_Object__c = true';
        // }
        if (acc.ET_SP_Dealer__c) {
            soql += ' AND Pro2_Dealer_Object__c = true ';
        }
        if (acc.ENG_Dealer__c) {
            soql += ' AND Pro2_Dealer_ENG__c = true ';
        }
        //add by rentx 2020-12-23 end
        soql += ' order by Name__c ';

        return soql;
    }

    //首页
    public void moveToFirst(){
        if(currentpage == 1) return;
        currentpage = 1;
        canMove();
    }

    //尾页
    public void moveToLast(){
        if(currentpage >= pagecount) return;
        currentpage = pagecount;
        canMove();
    }

    //上一页
    public void moveToPrevious(){
        if(currentpage == 1) return;
        currentpage = currentpage -1;
        canMove();
    }

    //下一页
    public void moveToNext(){
        if(currentpage >= pagecount) return;

        currentpage = currentpage + 1;
        canMove();
    }

    //判断是否可翻页
    public void canMove(){
        hasPrevious = false;
        hasNext = false;
        if(pagecount > 1 && currentpage > 1) hasPrevious = true;
        if(pagecount > 1 && currentpage < pagecount)  hasNext = true;
    }

    //获取所有产品
    public List<product2Info> searchAllProduct(){
        //所有的产品
        List<product2Info> allProductList = new List<product2Info>();
        List<Product2__c> accountInfo = [select Id, Name,
                                                Name__c,
                                                Asset_Model_No__c,
                                                Category1__c,
                                                Category2__c,
                                                Category3__c,
                                                Category4__c,
                                                Category5__c,
                                                SFDA_Status__c
                                            FROM Product2__c
                                            where Estimation_Entry_Possibility__c = '○'
                                            order by Name__c];
        for (Integer i = 0; i < accountInfo.size(); i++) {
            allProductList.add(new product2Info(accountInfo[i]));
        }
        return allProductList;
    }

    //刷新当前页
    public PageReference refreshPageSize() {
        //所有的产品
        List<product2Info> productInfoList = new List<product2Info>();
        //if(productSearch){
            //检索产品
            String soql = this.makeSoql(category1,category2,category3,category4,category5,keyword);
            List<Product2__c> product2Selected = Database.query(soql);
            for (Integer i = 0; i < product2Selected.size(); i++) {
                productInfoList.add(new product2Info(product2Selected[i]));
            }

            //已存在的特殊折扣
            ExistProdSDMap.clear();
            List<Dealer_Product__c> DealerProductList = [select Id, Special_Discount__c,Dealer_Product2__c,Special_Campaign_Price__c  
                                        FROM Dealer_Product__c
                                        WHERE Dealer_Contact__c = :accountId
                                        AND Special_Discount__c != null];
            for(Dealer_Product__c ahlc : dealerProductList){
                ExistProdSDMap.put(ahlc.Dealer_Product2__c, ahlc);
            }

            // for(product2Info prd : productInfoList){
            //     if(ExistProdSDMap.containsKey(prd.pro.Id)){
            //         prd.dealerPro = ExistProdSDMap.get(prd.pro.Id);
            //         prd.dpac
            //     }
            // }

            List<product2Info> tempInfoList = new List<product2Info>();
            //获取选中的产品
            Map<Id,product2Info> infoMap = new Map<Id,product2Info>();

            for (product2Info info : productInfoListview) {       
                if (info.check) {
                    infoMap.put(info.pro.Id, info);    
                    tempInfoList.add(info);     
                }
            }

            for(product2Info prd : productInfoList){
                if (!infoMap.containsKey(prd.pro.Id)) {
                    prd.dpac.Special_Discount__c = prd.dealerPro.Special_Discount__c;
                    prd.dpac.ProductDiscount__c = prd.dealerPro.Special_Campaign_Price__c;
                    tempInfoList.add(prd);
                }
                // if (infoMap.containsKey(prd.pro.Id)) {
                //     prd.check = true;
             //        prd.dpac = infoMap.get(prd.pro.Id).dpac;
                // }else {
             //        prd.dpac.Special_Discount__c = prd.dealerPro.Special_Discount__c;
             //        prd.dpac.ProductDiscount__c = prd.dealerPro.Special_Campaign_Price__c;
             //    }
            }

        //总件数
        // totalcount = productInfoList.size();
        totalcount = tempInfoList.size();
        //页数
        pagecount=(totalcount  +  pagesize  - 1) / pagesize;
        // makeCurrentPageRecords(productInfoList);
        makeCurrentPageRecords(tempInfoList);
        return null;
    }

    //编辑当前页内容
    public void makeCurrentPageRecords(List<product2Info> productInfoList){
        Integer startIdx;
        Integer endIdx;

        startIdx = (currentpage-1) * pagesize;
        endIdx = (currentpage-1) * pagesize+ pagesize;
        

        productInfoListview = new List<product2Info>();
        List<product2Info> prodlist = new List<product2Info>();
        for (product2Info info : productInfoList) {
            if (info.check) {
                productInfoListview.add(info);
            }else{
                prodlist.add(info);
            }
        }
        if (endIdx > prodlist.size()){
            endIdx = prodlist.size() - productInfoListview.size();
        } 

        for(Integer i=startIdx; i < endIdx ; i++){
            productInfoListview.add(prodlist.get(i));
        }


        // productInfoListview.addAll(prodlist);

        // for(Integer i=startIdx; i < endIdx ; i++){
        //     productInfoListview.add(productInfoList.get(i));    
        // }

        productRecoedsCount = productInfoListview.size();

   }


    class product2Info implements Comparable {
        public Boolean check { get; set; }
        public Boolean orderby { get; set; }
        public Product2__c pro { get; set; }
        public Dealer_Product__c dealerPro { get; set; }
        //特价产品申请明细
        public DiscountProductApplicationDetail__c dpac {get;set;}


        public product2Info(Product2__c e) {
            check = false;
            pro = e;
            dealerPro = new Dealer_Product__c();
            dpac = new DiscountProductApplicationDetail__c();
            orderby = false;
        }
        public Integer compareTo(Object compareTo) {
            product2Info compareToesd =(product2Info)compareTo;
            Integer returnValue = 0;
            if(check == true){
                returnValue = -1;
            }else{
                if (orderby == true){
                    returnValue = -1;
                }else{
                    // if (specialDiscount > compareToesd.specialDiscount) {
                    //     returnValue = -1;
                    // } else if (specialDiscount < compareToesd.specialDiscount) {
                        returnValue = 1;
                    // }
                }
            }
            return returnValue;
        }
    }
}