//实际IMS
//每月跑
//获取消耗品明细2的每月数量


global class ConsumableTargetManageBatch2 implements Database.Batchable<sObject> {
    public Date currentMonth;
    public Date endDate;
    public Date startDate;
    public String queryStr;
    public String year;
    public Boolean isIncrementOnly; //是否只跑增量
    public Boolean isHis; //是否只跑增量
    global ConsumableTargetManageBatch2(Date startDate,Date endDate,Boolean isIncrementOnly,Boolean isHis) {
        //当年
        this.isHis=isHis;
        this.startDate=startDate;
        this.endDate=endDate;
        this.isIncrementOnly=isIncrementOnly;
        queryStr = 'SELECT Consumable_Category1__c,Detail_Count__c,Intra_Trade_KRMB__c,Product_OutDate__c,Hospital_ID__c,Consumable_product__r.Product2__r.ConsumCategory3__c,Consumable_product__r.Product2__r.ConsumCategory2__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' +
        ' AND (Inventory_Status__c = \'直销到医院\' OR Inventory_Status__c = \'给二级到医院\') AND ShipmentAccount__c != \'\' AND Consumable_product__r.Product2__c!=null AND Consumable_Category1__c!=null AND Intra_Trade_KRMB__c!=null AND Hospital_ID__c!=null';
        // ' and Consumable_product__r.Product2__r.ConsumCategory3__c=\'高频治疗钳\' and Consumable_product__r.Product2__r.ConsumCategory2__c=\'ESD\' and Hospital_ID__c=\'0011000000V9RHzAAN\''+
        // ' limit 3000';
    }
    global ConsumableTargetManageBatch2(Date startDate,Date endDate,Boolean isIncrementOnly) {
        //当年
        this.isHis=false;
        this.startDate=startDate;
        this.endDate=endDate;
        this.isIncrementOnly=isIncrementOnly;
        queryStr = 'SELECT Consumable_Category1__c,Detail_Count__c,Intra_Trade_KRMB__c,Product_OutDate__c,Hospital_ID__c,Consumable_product__r.Product2__r.ConsumCategory3__c,Consumable_product__r.Product2__r.ConsumCategory2__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' +
        ' AND (Inventory_Status__c = \'直销到医院\' OR Inventory_Status__c = \'给二级到医院\') AND ShipmentAccount__c != \'\' AND Consumable_product__r.Product2__c!=null AND Consumable_Category1__c!=null AND Intra_Trade_KRMB__c!=null AND Hospital_ID__c!=null';
        // ' and Consumable_product__r.Product2__r.ConsumCategory3__c=\'高频治疗钳\' and Consumable_product__r.Product2__r.ConsumCategory2__c=\'ESD\' and Hospital_ID__c=\'0011000000V9RHzAAN\''+
        // ' limit 3000';
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        //数据超过一万条会报错
        if(!isIncrementOnly){
            // Integer year = startDate.year();
            // Integer FYear = year;
            // if(startDate>=Date.newInstance(year, 4, 1)){
            //     FYear = FYear+1;
            // }
            // String  OCSMYear= 'FY'+FYear;
            // List<ConsumableTargetManage__c> ctmList= [SELECT  Hospital__c,OCM_Year__c,Category3__c,Category4__c FROM ConsumableTargetManage__c WHERE OCM_Year__c = :OCSMYear ];
            // if(ctmList.size()>0){
            //     for(ConsumableTargetManage__c ctm:ctmList){
            //         ctm.Reality_IMS_Num1__c=0;
            //         ctm.Reality_IMS_RMB1__c=0;
            //         ctm.Reality_IMS_Num2__c=0;
            //         ctm.Reality_IMS_RMB2__c=0;
            //         ctm.Reality_IMS_Num3__c=0;
            //         ctm.Reality_IMS_RMB3__c=0;
            //         ctm.Reality_IMS_Num4__c=0;
            //         ctm.Reality_IMS_RMB4__c=0;
            //         ctm.Reality_IMS_Num5__c=0;
            //         ctm.Reality_IMS_RMB5__c=0;
            //         ctm.Reality_IMS_Num6__c=0;
            //         ctm.Reality_IMS_RMB6__c=0;
            //         ctm.Reality_IMS_Num7__c=0;
            //         ctm.Reality_IMS_RMB7__c=0;
            //         ctm.Reality_IMS_Num8__c=0;
            //         ctm.Reality_IMS_RMB8__c=0;
            //         ctm.Reality_IMS_Num9__c=0;
            //         ctm.Reality_IMS_RMB9__c=0;
            //         ctm.Reality_IMS_Num10__c=0;
            //         ctm.Reality_IMS_RMB10__c=0;
            //         ctm.Reality_IMS_Num11__c=0;
            //         ctm.Reality_IMS_RMB11__c=0;
            //         ctm.Reality_IMS_Num12__c=0;
            //         ctm.Reality_IMS_RMB12__c=0;
            //     }
            //     update ctmList;
            // }
            
        }

        return Database.getQueryLocator(queryStr);
    }

    global void execute(Database.BatchableContext BC,  list<Consumable_order_details2__c> scope) {
        System.debug('获取到消耗品明细2:');
        System.debug(scope);
        Integer year = startDate.year();
        Integer FYear = year;
        if(startDate>=Date.newInstance(year, 4, 1)){
            FYear = FYear+1;
        }
        String  OCSMYear= 'FY'+FYear;


        Set<String> ctmKeySet=new Set<String>();
        Map<String,List<Consumable_order_details2__c>> codMap = new Map<String,List<Consumable_order_details2__c>>();
        for(Consumable_order_details2__c cod:scope){
            if(cod.Consumable_product__r == null || cod.Consumable_product__r.Product2__c == null || cod.Consumable_Category1__c==null){
                continue;
            }
            String key = cod.Consumable_Category1__c+'-分割符-'+cod.Consumable_product__r.Product2__r.ConsumCategory2__c+'-分割符-'+cod.Consumable_product__r.Product2__r.ConsumCategory3__c+'-分割符-'+cod.Hospital_ID__c;
            ctmKeySet.add(cod.Hospital_ID__c+'-'+cod.Consumable_product__r.Product2__r.ConsumCategory2__c+'-'+cod.Consumable_product__r.Product2__r.ConsumCategory3__c+'-'+OCSMYear);
            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);
            }
        }


        List<ConsumableTargetManage__c> ctmList= [SELECT  Hospital__r.Name,productType__c,Reality_IMS_Num1__c,Reality_IMS_RMB1__c,Reality_IMS_Num2__c,Reality_IMS_RMB2__c,Reality_IMS_Num3__c,Reality_IMS_RMB3__c,Reality_IMS_Num4__c,Reality_IMS_RMB4__c,
                                        Reality_IMS_Num5__c,Reality_IMS_RMB5__c,Reality_IMS_Num6__c,Reality_IMS_RMB6__c,Reality_IMS_Num7__c,Reality_IMS_RMB7__c,
                                        Reality_IMS_Num8__c,Reality_IMS_RMB8__c,Reality_IMS_Num9__c,Reality_IMS_RMB9__c,Reality_IMS_Num10__c,Reality_IMS_RMB10__c,
                                        Reality_IMS_Num11__c,Reality_IMS_RMB11__c,Reality_IMS_Num12__c,Reality_IMS_RMB12__c,

                                        Hospital__c,OCM_Year__c,Category3__c,Category4__c FROM ConsumableTargetManage__c WHERE OCM_Year__c = :OCSMYear AND ConsumableTargetManageKey__c in :ctmKeySet];
        System.debug('获取到现存IMS:');
        System.debug(ctmList);

        for(ConsumableTargetManage__c ctm:ctmList){
            String key = ctm.productType__c+'-分割符-'+ctm.Category3__c+'-分割符-'+ctm.Category4__c+'-分割符-'+ctm.Hospital__c;
            if(codMap.containsKey(key)){
                List<Consumable_order_details2__c> codList=codMap.get(key);
                String statu='';
                Date lastDate=Date.newInstance(year, 4, 1);
                System.debug('更新前:');
                System.debug(ctm);
                for(Consumable_order_details2__c cod:codList){
                    if(cod.Product_OutDate__c >= Date.newInstance(FYear, 1, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 2, 1)){
                        ctm.Reality_IMS_Num1__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB1__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear, 2, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 3, 1)){
                        ctm.Reality_IMS_Num2__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB2__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear, 3, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 4, 1)){
                        ctm.Reality_IMS_Num3__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB3__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 4, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 5, 1)){
                        ctm.Reality_IMS_Num4__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB4__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 5, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 6, 1)){
                        ctm.Reality_IMS_Num5__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB5__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 6, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 7, 1)){
                        ctm.Reality_IMS_Num6__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB6__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 7, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 8, 1)){
                        ctm.Reality_IMS_Num7__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB7__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 8, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 9, 1)){
                        ctm.Reality_IMS_Num8__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB8__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 9, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 10, 1)){
                        ctm.Reality_IMS_Num9__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB9__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 10, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 11, 1)){
                        ctm.Reality_IMS_Num10__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB10__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 11, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 12, 1)){
                        ctm.Reality_IMS_Num11__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB11__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 12, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 1, 1)){
                        ctm.Reality_IMS_Num12__c+=cod.Detail_Count__c;
                        ctm.Reality_IMS_RMB12__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                    }
                }

                System.debug('更新后:');
                System.debug(ctm);

                codMap.remove(key);
            }
        }
        // List<String> hpList=new List<String>();
        
        // for(String key:codMap.keySet()){
        //     List<String> keyItems=key.split('-分割符-');
        //     if(keyItems.size()<2){
        //         continue;
        //     }
        //     if(keyItems.size()==3){
        //         hpList.add(keyItems.get(2));
        //     }
        // }

        // Map<String,Account> etMap = new Map<String,Account>([select Id,ET_owner__c from Account where Id  in :hpList]);
        // System.debug('获取到医院:');
        // System.debug(etMap);
        List<ConsumableTargetManage__c> newCtm=new List<ConsumableTargetManage__c>();
        System.debug('获取到的消耗品明细2Map');
        System.debug(codMap);
        for(String key:codMap.keySet()){
            List<Consumable_order_details2__c> codList=codMap.get(key);
            ConsumableTargetManage__c ctm=new ConsumableTargetManage__c();
            ctm.Reality_IMS_Num1__c=0;
            ctm.Reality_IMS_RMB1__c=0;
            ctm.Reality_IMS_Num2__c=0;
            ctm.Reality_IMS_RMB2__c=0;
            ctm.Reality_IMS_Num3__c=0;
            ctm.Reality_IMS_RMB3__c=0;
            ctm.Reality_IMS_Num4__c=0;
            ctm.Reality_IMS_RMB4__c=0;
            ctm.Reality_IMS_Num5__c=0;
            ctm.Reality_IMS_RMB5__c=0;
            ctm.Reality_IMS_Num6__c=0;
            ctm.Reality_IMS_RMB6__c=0;
            ctm.Reality_IMS_Num7__c=0;
            ctm.Reality_IMS_RMB7__c=0;
            ctm.Reality_IMS_Num8__c=0;
            ctm.Reality_IMS_RMB8__c=0;
            ctm.Reality_IMS_Num9__c=0;
            ctm.Reality_IMS_RMB9__c=0;
            ctm.Reality_IMS_Num10__c=0;
            ctm.Reality_IMS_RMB10__c=0;
            ctm.Reality_IMS_Num11__c=0;
            ctm.Reality_IMS_RMB11__c=0;
            ctm.Reality_IMS_Num12__c=0;
            ctm.Reality_IMS_RMB12__c=0;
            ctm.OCM_Year__c=OCSMYear;


            Map<String, List<String>> res=getFieldDependencies('ConsumableTargetManage__c','Category3__c','Category4__c');
            if(!res.containsKey(codList[0].Consumable_product__r.Product2__r.ConsumCategory2__c)){
                continue;
            }else{
                List<String> c4List=res.get(codList[0].Consumable_product__r.Product2__r.ConsumCategory2__c);
                if(!c4List.contains(codList[0].Consumable_product__r.Product2__r.ConsumCategory3__c)){
                    continue;
                }
            }
            ctm.productType__c=codList[0].Consumable_Category1__c;
            ctm.Category3__c=codList[0].Consumable_product__r.Product2__r.ConsumCategory2__c;
            ctm.Category4__c=codList[0].Consumable_product__r.Product2__r.ConsumCategory3__c;
            ctm.Hospital__c=codList[0].Hospital_ID__c;
            ctm.StrategicDepartment__c=codList[0].Hospital_ID__c;
            ctm.ConsumableTargetManageKey__c=ctm.Hospital__c+'-'+ctm.Category3__c+'-'+ctm.Category4__c+'-'+ctm.OCM_Year__c;

            for(Consumable_order_details2__c cod:codList){
                if(cod.Product_OutDate__c >= Date.newInstance(FYear, 1, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 2, 1)){
                    ctm.Reality_IMS_Num1__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB1__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear, 2, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 3, 1)){
                    ctm.Reality_IMS_Num2__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB2__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear, 3, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 4, 1)){
                    ctm.Reality_IMS_Num3__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB3__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 4, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 5, 1)){
                    ctm.Reality_IMS_Num4__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB4__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 5, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 6, 1)){
                    ctm.Reality_IMS_Num5__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB5__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 6, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 7, 1)){
                    ctm.Reality_IMS_Num6__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB6__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 7, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 8, 1)){
                    ctm.Reality_IMS_Num7__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB7__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 8, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 9, 1)){
                    ctm.Reality_IMS_Num8__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB8__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 9, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 10, 1)){
                    ctm.Reality_IMS_Num9__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB9__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 10, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 11, 1)){
                    ctm.Reality_IMS_Num10__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB10__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 11, 1) && cod.Product_OutDate__c < Date.newInstance(FYear-1, 12, 1)){
                    ctm.Reality_IMS_Num11__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB11__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }else if(cod.Product_OutDate__c >= Date.newInstance(FYear-1, 12, 1) && cod.Product_OutDate__c < Date.newInstance(FYear, 1, 1)){
                    ctm.Reality_IMS_Num12__c+=cod.Detail_Count__c;
                    ctm.Reality_IMS_RMB12__c+=cod.Detail_Count__c*cod.Intra_Trade_KRMB__c;
                }
            }
            newCtm.add(ctm);
        }
        if(ctmList.size()>0){
            update ctmList;
        }
        if(newCtm.size()>0){
            insert newCtm;
        }

    }

    global void finish(Database.BatchableContext BC) {
        if(!isHis){
        	Id batjobId = Database.executeBatch(new ConsumableTargetManageBatch3(startDate,endDate,this.isIncrementOnly), 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;
    }
}