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

    public Date currentMonth;
    public Date endDate;
    public Date lastMonth;
    public String queryStr;

    global TrackConsumableSaleForecastBatch2(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);
        }
        //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt start
        queryStr = 'SELECT 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){
            String key = coDetail.ShipmentAccount__c + '-' + coDetail.Asset_Model_No__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>();
        List<TrackConsumableSalesForecast__c> lastMonthTcsfList = [SELECT Id,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()];
        for(TrackConsumableSalesForecast__c tcsf : lastMonthTcsfList){
            tcsfMap.put(tcsf.Key__c,tcsf);
        }
        //更新本月的销量表数据
        Map<String,TrackConsumableSalesForecast__c> tcsfMapNewOrUpdate = new Map<String,TrackConsumableSalesForecast__c>();
        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;
            //最近出库日
            Date lastShipmentDate = Date.newInstance(1998, 1, 1);
            for(Consumable_order_details2__c cod : coList){
                if(cod.Product_OutDate__c > lastShipmentDate){
                    lastShipmentDate = cod.Product_OutDate__c;
                }
            }
            System.debug('lastShipmentDate:'+lastShipmentDate);
            if(tcsfMap.containsKey(key)){
                tcsf = tcsfMap.get(key);
                tcsf.SnapshotMonth__c = currentMonth;
                tcsf.ThisMonthDeliveryNumber__c += coList.size();
                //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt start
                if(coList.size()>0&&coList[0].Consumable_product__c!=null&&coList[0].Consumable_product__r.Product2__c!=null){
                    tcsf.ASP_Price__c = coList[0].Consumable_product__r.Product2__r.ASP_Price__c;
                }
                //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt end
                if(tcsf.LastShipmentDate__c < lastShipmentDate){
                    tcsf.LastShipmentDate__c = lastShipmentDate;
                }
                tcsf.Status__c = '销量计算';
            }else{
                tcsf = new TrackConsumableSalesForecast__c();
                //取到医院
                if(coList[0].Consumable_Sale_order__c != null){
                    if(coList[0].Consumable_Sale_order__r.Order_ForHospital__c != null){
                        tcsf.Hospital__c = coList[0].Consumable_Sale_order__r.Order_ForHospital__c;
                        // 20231211 hql 课题  耗材【销售状态】查看权限 DB202311574810 start
                        if(coList[0].Consumable_Sale_order__r.Order_ForHospital__r.ET_owner__r.IsActive == true){
                            tcsf.OwnerId = coList[0].Consumable_Sale_order__r.Order_ForHospital__r.ET_owner__c;
                        }
                    }else{
                        tcsf.Hospital__c = coList[0].Consumable_Sale_order__r.Order_ForDealer__c;
                        if(coList[0].Consumable_Sale_order__r.Order_ForDealer__r.ET_owner__r.IsActive == true){
                            tcsf.OwnerId = coList[0].Consumable_Sale_order__r.Order_ForDealer__r.ET_owner__c;
                        }
                    }
                }else if(coList[0].Consumable_Shipment_order__c != null){
                    if(coList[0].Consumable_Shipment_order__r.Order_ForHospital__c != null){
                        tcsf.Hospital__c = coList[0].Consumable_Shipment_order__r.Order_ForHospital__c;
                        if(coList[0].Consumable_Shipment_order__r.Order_ForHospital__r.ET_owner__r.IsActive == true){
                            tcsf.OwnerId = coList[0].Consumable_Shipment_order__r.Order_ForHospital__r.ET_owner__c;
                        }
                    }else{
                        tcsf.Hospital__c = coList[0].Consumable_Shipment_order__r.Order_ForDealer__c;
                        if(coList[0].Consumable_Shipment_order__r.Order_ForDealer__r.ET_owner__r.IsActive == true){
                            tcsf.OwnerId = coList[0].Consumable_Shipment_order__r.Order_ForDealer__r.ET_owner__c;
                        }
                    }
                }
                // 20231211 hql 课题  耗材【销售状态】查看权限 DB202311574810 end
                //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt start
                if(coList.size()>0&&coList[0].Consumable_product__c!=null&&coList[0].Consumable_product__r.Product2__c!=null){
                    tcsf.ASP_Price__c = coList[0].Consumable_product__r.Product2__r.ASP_Price__c;
                }
                //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt end
                tcsf.HospitalName__c = coList[0].ShipmentAccount__c;
                tcsf.ProductModel__c = coList[0].Asset_Model_No__c;
                tcsf.SnapshotMonth__c = currentMonth;
                tcsf.ThisMonthDeliveryNumber__c = coList.size();
                tcsf.LastShipmentDate__c = lastShipmentDate;
                tcsf.Type__c = coList[0].Product_Type__c ;
                tcsf.Consumable_Category1__c = coList[0].Consumable_Category1__c;
                tcsf.Consumable_Category2__c = coList[0].Consumable_Category2__c;
                tcsf.Status__c = '销量计算';
            }
            tcsfMapNewOrUpdate.put(key,tcsf);
        }
        System.debug('all1:'+tcsfMapNewOrUpdate.values());
        //更新过去6个月的平均销量
        //根据当前月取到半年前
        // Date sixMonthAgo;
        // Date threeMonthAgo;
        // Integer year = currentMonth.year();
        // Integer month = currentMonth.month();
        // if(month <= 2){
        //     threeMonthAgo = Date.newInstance(year-1, 10+month, 1);
        // }else {
        //     threeMonthAgo = Date.newInstance(year, month-2, 1);
        // }
        // if(month <= 6){
        //     sixMonthAgo = Date.newInstance(year-1, 6+month, 1);
        // }else {
        //     sixMonthAgo = Date.newInstance(year, month-6, 1);
        // }
        //获取过去6个月的销量数据
        // List<TrackConsumableSalesForecast__c> tcsfSixMonthAgoList = [SELECT Hospital__c,HospitalName__c,ProductModel__c,ThisMonthDeliveryNumber__c,LastShipmentDate__c,SnapshotMonth__c,Key__c FROM TrackConsumableSalesForecast__c WHERE SnapshotMonth__c >= :sixMonthAgo AND SnapshotMonth__c < :currentMonth AND Key__c IN :coMap.keySet()];
        // System.debug('tcsfSixMonthAgoList:'+tcsfSixMonthAgoList);
        // for(String key : coMap.keySet()){
        //     System.debug('key:'+key);
        //     Decimal sumThreeMonthSales = 0;
        //     Decimal sumSixMonthSales = 0;
        //     for(TrackConsumableSalesForecast__c tcsf : tcsfSixMonthAgoList){
        //         if(tcsf.Key__c == key){
        //             if(tcsf.SnapshotMonth__c >= threeMonthAgo){
        //                 sumThreeMonthSales += tcsf.ThisMonthDeliveryNumber__c;
        //             }
        //             sumSixMonthSales += tcsf.ThisMonthDeliveryNumber__c;
        //         }
        //     }
        //     //失单预警
        //     if(sumThreeMonthSales == 0 && tcsfMapNewOrUpdate.get(key).ThisMonthDeliveryNumber__c == 0){
        //         tcsfMapNewOrUpdate.get(key).BillLostWarning__c = 1;
        //     }
        //     //过去6月平均销量
        //     if(sumSixMonthSales != 0){
        //         tcsfMapNewOrUpdate.get(key).LastSixMonthsAverage__c = sumSixMonthSales/6;
        //     }else {
        //         tcsfMapNewOrUpdate.get(key).LastSixMonthsAverage__c = 0;
        //     }
        // }
        //更新或者插入销量表
        Database.upsert(tcsfMapNewOrUpdate.values());
    }

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

        //add by allen 拆分部署ali生产
        public void testMock(){
            Integer i = 0;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;
            i++;

        }
}