global without sharing class TrackConsumableSaleForecastASPBatch3 implements Database.Batchable<sObject>{

    public Date currentMonth;
    public Date endDate;
    public Date lastMonth;
    public String queryStr;
    public Boolean hisFLag;
    public Integer fyear;
    global TrackConsumableSaleForecastASPBatch3(Date currentMonth,Date endDate) {
        this.currentMonth = currentMonth;
        this.endDate = endDate;
        Integer year = currentMonth.year();
        Integer month = currentMonth.month();
        this.currentMonth = Date.newInstance(year, month, 1);
        if(month == 1){
            lastMonth = Date.newInstance(year-1, 12, 1);
        }else {
            lastMonth = Date.newInstance(year, month-1, 1);
        }
        this.fyear=year;
        if(month>4){
            this.fyear+=1;
        }
        this.hisFLag=false;
        //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt start
        queryStr = 'SELECT Intra_Trade_KRMB__c,Sale_orderName__c,Detail_Count__c,ProductPacking_list_manual__c,Hospital_ID__c,Consumable_product__r.Product2__r.ConsumCategory2__c,Consumable_product__r.Product2__r.ConsumCategory3__c,Consumable_product__r.Product2__r.ASP_Price__c,Consumable_Sale_order__c,Consumable_Shipment_order__c,Consumable_Sale_order__r.Order_ForHospital__c,Consumable_Sale_order__r.Order_ForHospital__r.ET_owner__r.IsActive,Consumable_Sale_order__r.Order_ForDealer__c,Consumable_Sale_order__r.Order_ForDealer__r.ET_owner__r.IsActive,Consumable_Shipment_order__r.Order_ForHospital__c,Consumable_Shipment_order__r.Order_ForHospital__r.ET_owner__r.IsActive,Consumable_Shipment_order__r.Order_ForDealer__c,Consumable_Shipment_order__r.Order_ForDealer__r.ET_owner__r.IsActive,ShipmentAccount__c,Asset_Model_No__c,Product_OutDate__c,Product_Type__c,Consumable_Category1__c,Consumable_Category2__c FROM Consumable_order_details2__c WHERE Product_Type__c != \'\' AND Asset_Model_No__c != \'\' AND (Inventory_Status__c = \'直销到医院\' OR Inventory_Status__c = \'给二级到医院\') AND ShipmentAccount__c != \'\' AND Product_OutDate__c >= :lastMonth AND Product_OutDate__c < :currentMonth';
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(queryStr);
    }

    global void execute(Database.BatchableContext BC, List<Consumable_order_details2__c> scope){
        Map<String,List<Consumable_order_details2__c>> coMap = new Map<String,List<Consumable_order_details2__c>>();
        //根据医院和产品对本月所有出库的消耗品明细2进行分类
        for(Consumable_order_details2__c coDetail : scope){
            if(coDetail.Consumable_product__r == null || coDetail.Consumable_product__r.Product2__c == null){
                continue;
            }
            
            String key = coDetail.Consumable_product__r.Product2__r.ConsumCategory2__c + '-' + coDetail.Consumable_product__r.Product2__r.ConsumCategory3__c + '-' + coDetail.ShipmentAccount__c;
            if(coMap.containsKey(key)){
                coMap.get(key).add(coDetail);
            }else {
                List<Consumable_order_details2__c> coList = new List<Consumable_order_details2__c>();
                coList.add(coDetail);
                coMap.put(key,coList);
            }
        }
        //取到从上月复制到本月的销量表数据
        Map<String,TrackConsumableSalesForecast__c> tcsfMap = new Map<String,TrackConsumableSalesForecast__c>();

        String recordIdC = Schema.SObjectType.TrackConsumableSalesForecast__c.getRecordTypeInfosByDeveloperName().get('ConsumableCategory3').getRecordTypeId();
        List<TrackConsumableSalesForecast__c> lastMonthTcsfList = [SELECT ThisMonthDelivery_Price_IMS__c,ThisYearDeliveryNumber__c,Sale_OrderName_Set__c,IMS_Flag__c,Id,Least_Unit__c,Consumable_Category3__c,ASP_Price__c,Hospital__c,HospitalName__c,ProductModel__c,ThisMonthDeliveryNumber__c,LastShipmentDate__c,Key__c FROM TrackConsumableSalesForecast__c WHERE SnapshotMonth__c = :currentMonth AND Key__c IN :coMap.keySet() AND RecordTypeId=:recordIdC];
        for(TrackConsumableSalesForecast__c tcsf : lastMonthTcsfList){
            tcsfMap.put(tcsf.Key__c,tcsf);
        }
        //更新本月的销量表数据
        List<TrackConsumableSalesForecast__c> tcsfMapNewOrUpdate = new List<TrackConsumableSalesForecast__c>();
        System.debug('目标耗材维度统计:');
        System.debug(coMap);

        for(String key : coMap.keySet()){
            List<Consumable_order_details2__c> coList;
            if(coMap.get(key) != null){
                coList = coMap.get(key);
            }else {
                coList = new List<Consumable_order_details2__c>();
            }
            TrackConsumableSalesForecast__c tcsf;
            Decimal touRMB=0;
            for(Consumable_order_details2__c cod : coList){
                if(cod.Intra_Trade_KRMB__c!=null && cod.Detail_Count__c!=null){
                    touRMB+=cod.Intra_Trade_KRMB__c*cod.Detail_Count__c;
                }
            }


            if(tcsfMap.containsKey(key)){
                tcsf = tcsfMap.get(key);
                if(tcsf.ThisMonthDelivery_Price_IMS__c==null){
                    tcsf.ThisMonthDelivery_Price_IMS__c=0;
                }
                tcsf.ThisMonthDelivery_Price_IMS__c+=touRMB;
                tcsfMapNewOrUpdate.add(tcsf);
            }
        } 

        
        update tcsfMapNewOrUpdate;
    }

    global void finish(Database.BatchableContext BC) {
           Id batjobId = Database.executeBatch(new TrackConsumableSaleForecastASPBatch4(currentMonth,endDate), 200);
    }
}