//新建ASP
global class ASPPriceYearBatch1 implements Database.Batchable<sObject> {
    public String query;
    public String FYyear;
    public Date startDate;
    public Date endDate;

    global ASPPriceYearBatch1(Date startDate) {
        
        Integer year = startDate.year();
        this.FYyear='FY'+year;
        this.startDate=startDate;
        this.query = 'SELECT Detail_Count__c,Intra_Trade_List_RMB__c,Product_OutDate__c,Hospital_ID__c,Consumable_Shipment_order__r.Order_ForHospital__r.Hospita_Salesdepartment_Text__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 Lose_Flag__c = FALSE AND Dealer_Returned__c = FALSE AND Dealer_Saled__c=true AND Product_OutDate__c >= :startDate AND Product_OutDate__c  <= :endDate limit 1' ;
        // ' 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) {
        try{
            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 AND Salesdepartment__c!='0.全国'  AND id not in ('a1hHy000001gtOAIAY')];
            Map<String,ET_ASP__c> etMap = new Map<String,ET_ASP__c>();
            for(ET_ASP__c etASP:etASPList){
                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.DosageNumTotal__c=0;
                                ea.DosageAmountTotal__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);
                                }
                            }
                        }
                    }
                    
                    // 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 = '7.全国';
                    //         ea.ConsumCategory2__c = key;
                    //         ea.ConsumCategory3__c = val;
                    //         ea.yearly__c = this.FYyear;
                    //         ea.ET_ASP_KEY__c = ea.Salesdepartment__c+'-'+ea.yearly__c+'-'+ea.ConsumCategory2__c+'-'+ea.ConsumCategory3__c;
                    //         eaList.add(ea);
                    //     }
                    // }
                    System.debug('新增EA:');
                    System.debug(eaList.size());
                    System.debug(eaList);
                    insert eaList;
                    System.debug(eaList.get(0).ID);
                }

                
            }
        }catch(Exception e){
            System.debug(e);
        }
 

        
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Consumable_order_details2__c> scope) {

    }

    global void finish(Database.BatchableContext BC) {
        Database.executeBatch(new ASPPriceYearBatch2(startDate),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;
    }

}