//目标耗材-ASP价格表。
//每年一月一日跑一次
//新建上年4-12月的数据
//从消耗品明细2获取各个部门目标耗材整年平均价格
//部门的目标耗材无销量就从
global class ASPPriceYearBatch2 implements Database.Batchable<sObject> {
    public String query;
    public String FYyear;
    public Date startDate;
    public Date endDate;
    public Date currentDate;
    //当前时间，默认xxxx年1月1日，这时跑上一年的4月1日到上一年底的数据
    global ASPPriceYearBatch2(Date currentDate) {
        
        Integer year = currentDate.year();
        Integer fYear = year+1;
        this.FYyear='FY'+fYear;
        this.startDate=Date.newInstance(year-1, 4, 1);
        this.endDate=Date.newInstance(year-1, 12, 31);
        this.currentDate=currentDate;
        this.query = 'SELECT SalesDepartment_Dealer__c,Detail_Count__c,Intra_Trade_List_RMB__c,Product_OutDate__c,Hospital_ID__c,' +
        ' Consumable_product__r.Product2__r.ConsumCategory3__c,Consumable_product__r.Product2__r.ConsumCategory2__c,Consumable_product__r.Product2__r.Intra_Trade_List_RMB__c'+
        ' FROM Consumable_order_details2__c '+
        ' WHERE (Dealer_Saled__c=true OR Dealer_Shipment__c=true) AND Dealer_Returned__c=false' +
        ' AND Inventory_Status__c != \'互相调货\'' +
        ' AND Product_OutDate__c >= :startDate AND Product_OutDate__c  <= :endDate' ;
        // ' and Consumable_product__r.Product2__r.ConsumCategory3__c=\'高频治疗钳\' and Consumable_product__r.Product2__r.ConsumCategory2__c=\'ESD\' and Hospital_ID__c=\'0011000000V9RHzAAN\''+
        // ' limit 100';
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        List<ET_ASP__c> etASPList=[SELECT id,ET_ASP_KEY__c,Salesdepartment__c,ConsumCategory2__c,ConsumCategory3__c,yearly__c,ASP_year__c,DosageAmountTotal__c,DosageNumTotal__c from ET_ASP__c WHERE yearly__c=:FYyear];
        Map<String,ET_ASP__c> etMap = new Map<String,ET_ASP__c>();
        for(ET_ASP__c etASP:etASPList){
            etASP.ASP_year__c=0;
            etASP.DosageNumTotal__c=0;
            etASP.DosageAmountTotal__c=0;
            etASP.ASP_year_ListRMB__c=0;
            etASP.List_RMB__c=0;
            etASP.List_Num__c=0;
            etMap.put(etASP.ET_ASP_KEY__c, etASP);
        }
        Map<String, List<String>> res=getFieldDependencies('Event__c','etapp_third_category__c','etapp_forth_category__c');

        if(!res.isEmpty()){
            Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe();
            Schema.SObjectType objType = globalDescribe.get('ET_ASP__c');
            if (objType != null) {
                Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
                Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
                List<Schema.PicklistEntry> SalesdepartmentMap=fieldMap.get('Salesdepartment__c').getDescribe().getPicklistValues();
                List<String> SalesdepartmentList=new List<String>();
                for(Schema.PicklistEntry st:SalesdepartmentMap){
                    if(st.isActive()){
                        SalesdepartmentList.add(st.getValue());
                    }
                }
                Set<String> keySet=res.keySet();
                List<ET_ASP__c> eaList=new List<ET_ASP__c>();
                for(String sd:SalesdepartmentList){
                    for(String key:keySet){
                        List<String> valList=res.get(key);
                        for(String val:valList){
                            ET_ASP__c ea=new ET_ASP__c();
                            ea.Salesdepartment__c = sd;
                            ea.ConsumCategory2__c = key;
                            ea.ConsumCategory3__c = val;
                            ea.yearly__c = this.FYyear;
                            ea.ASP_year__c=0;
                            ea.DosageNumTotal__c=0;
                            ea.DosageAmountTotal__c=0;
                            ea.ASP_year_ListRMB__c=0;
                            ea.List_RMB__c=0;
                            ea.List_Num__c=0;
                            ea.ET_ASP_KEY__c = ea.Salesdepartment__c+'-'+ea.yearly__c+'-'+ea.ConsumCategory2__c+'-'+ea.ConsumCategory3__c;
                            if(!etMap.containsKey(ea.ET_ASP_KEY__c)){
                                eaList.add(ea);
                            }
                        }
                    }
                }
                System.debug('新增EA:');
                System.debug(eaList.size());
                System.debug(eaList);
                insert eaList;
                update etASPList;
            }

            
        }
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Consumable_order_details2__c> scope) {
        Map<String,List<Consumable_order_details2__c>> codMap = new Map<String,List<Consumable_order_details2__c>>();
        for(Consumable_order_details2__c cod:scope){
            String salesDep=cod.SalesDepartment_Dealer__c;
            
            String key2 = cod.Consumable_product__r.Product2__r.ConsumCategory2__c+'-'+cod.Consumable_product__r.Product2__r.ConsumCategory3__c+'-'+salesDep;
            String key = cod.Consumable_product__r.Product2__r.ConsumCategory2__c+'-'+cod.Consumable_product__r.Product2__r.ConsumCategory3__c+'-全国';
            if(codMap.containsKey(key)){
                codMap.get(key).add(cod);
            }else{
                List<Consumable_order_details2__c> codList = new List<Consumable_order_details2__c>();
                codList.add(cod);
                codMap.put(key,codList);
            }

            if(codMap.containsKey(key2)){
                codMap.get(key2).add(cod);
            }else{
                List<Consumable_order_details2__c> codList = new List<Consumable_order_details2__c>();
                codList.add(cod);
                codMap.put(key2,codList);
            }
        }

        List<ET_ASP__c> etASPList=[SELECT id,Salesdepartment__c,ConsumCategory2__c,ConsumCategory3__c,yearly__c,ASP_year__c,DosageAmountTotal__c,DosageNumTotal__c from ET_ASP__c WHERE yearly__c=:FYyear];
        for(ET_ASP__c etASP:etASPList){
            String key='';
            if( etASP.Salesdepartment__c == '0.全国'){
                key = etASP.ConsumCategory2__c+'-'+etASP.ConsumCategory3__c+'-全国';
            }else{
                key = etASP.ConsumCategory2__c+'-'+etASP.ConsumCategory3__c+'-'+etASP.Salesdepartment__c;
            }
            
            if(etASP.DosageAmountTotal__c==null){
                etASP.DosageAmountTotal__c=0;
            }
            if(etASP.DosageNumTotal__c==null){
                etASP.DosageNumTotal__c=0;
            }
            if(codMap.containsKey(key)){
                List<Consumable_order_details2__c> codList = codMap.get(key);
                for(Consumable_order_details2__c cod:codList){
                    if(cod.Intra_Trade_List_RMB__c!=null && cod.Detail_Count__c!=null){
                        etASP.DosageAmountTotal__c+=cod.Detail_Count__c*cod.Intra_Trade_List_RMB__c;
                        etASP.DosageNumTotal__c+=cod.Detail_Count__c;
                    }
                }
            }
            if(etASP.DosageAmountTotal__c!=0 && etASP.DosageNumTotal__c!=0){
                etASP.ASP_year__c = etASP.DosageAmountTotal__c / etASP.DosageNumTotal__c / 1.13 /1000;
            }else{
                etASP.ASP_year__c = 0;
            }
            
        }
        update etASPList;

    }

    global void finish(Database.BatchableContext BC) {
        Database.executeBatch(new ASPPriceYearBatch3(currentDate),200);
    }
    public static Map<String, List<String>> getFieldDependencies(String objectName, String controllingField, String dependentField) {  
        Map<String, List<String>> controllingInfo = new Map<String, List<String>>();  
      
        Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);  
        List<Schema.PicklistEntry> controllingValues = objType.getDescribe().fields.getMap().get(controllingField).getDescribe().getPicklistValues();  
        List<Schema.PicklistEntry> dependentValues = objType.getDescribe().fields.getMap().get(dependentField).getDescribe().getPicklistValues();  
      
        for(Schema.PicklistEntry currControllingValue : controllingValues) {  
            controllingInfo.put(currControllingValue.getLabel(), new List<String>());  
        }  
      
        for(Schema.PicklistEntry currDependentValue : dependentValues) {  
            PicklistValueInfo info = (PicklistValueInfo) JSON.deserialize(JSON.serialize(currDependentValue), PicklistValueInfo.class);  
            String hexString = EncodingUtil.convertToHex(EncodingUtil.base64Decode(info.ValidFor)).toUpperCase();  

            Integer baseCount = 0;  
      
            for(Integer curr : hexString.getChars()) {  
                Integer val = 0;  
      
                if(curr >= 65) {  
                    val = curr - 65 + 10;  
                } else {  
                    val = curr - 48;  
                }  
      
                if((val & 8) == 8) {  
                    controllingInfo.get(controllingValues[baseCount + 0].getLabel()).add(currDependentValue.getLabel());  
                }  
                if((val & 4) == 4) {  
                    controllingInfo.get(controllingValues[baseCount + 1].getLabel()).add(currDependentValue.getLabel());  
                }  
                if((val & 2) == 2) {  
                    controllingInfo.get(controllingValues[baseCount + 2].getLabel()).add(currDependentValue.getLabel());  
                }  
                if((val & 1) == 1) {  
                    controllingInfo.get(controllingValues[baseCount + 3].getLabel()).add(currDependentValue.getLabel());  
                }  
                baseCount += 4;  
            }  
        }  
        System.debug('ControllingInfo: ' + controllingInfo);  
        return controllingInfo;
    }
}