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

    public Date currentMonth;
    public Date endDate;
    public Date lastMonth;
    public String queryStr;
    public Boolean hisFLag;
    public Integer fyear;//20240308 lwt 出库价，销售状态修改
    global TrackConsumableSaleForecastBatch2C(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);
        }
        //20240308 lwt 出库价，销售状态修改 start
        this.fyear=year;
        if(month>4){
            this.fyear+=1;
        }
        //20240308 lwt 出库价，销售状态修改 end
        this.hisFLag=false;
        //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt start
        //20240308 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';
            // ' AND Consumable_product__r.Product2__r.ConsumCategory2__c=\'基干\' ANd Consumable_product__r.Product2__r.ConsumCategory3__c=\'注射针（肠镜）-400\' AND Hospital_ID__c=\'0011000000V9OKqAAN\'';
    }
    global TrackConsumableSaleForecastBatch2C(Date currentMonth,Date endDate,Boolean hisFLag) {
        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=hisFLag;
        //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';
            // ' AND Consumable_product__r.Product2__r.ConsumCategory2__c=\'基干\' ANd Consumable_product__r.Product2__r.ConsumCategory3__c=\'注射针（肠镜）-400\' AND Hospital_ID__c=\'0011000000V9QrPAAV\'';
    }
    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);
        }
        //更新本月的销量表数据
        Map<String,TrackConsumableSalesForecast__c> tcsfMapNewOrUpdate = new Map<String,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;
            //最近出库日
            Date lastShipmentDate = Date.newInstance(1998, 1, 1);
            Decimal LeastUnit = 0;
            Decimal DCount=0;
            DCount=0;
            LeastUnit = 0;
            DCount=0;
            LeastUnit = 0;
            DCount=0;
            LeastUnit = 0;
            DCount=0;
            LeastUnit = 0;
            DCount=0;
            LeastUnit = 0;
            Decimal outC;
            outC=0;
            Decimal inC;
            inC=0;
            Set<String> SaleOrderNameSet=new Set<String>();
            String SaleOrderNameSetString='';
            Decimal touRMB=0;
            touRMB=0;
            touRMB=0;
            if(tcsfMap.containsKey(key)){
                if(String.isNotBlank(tcsfMap.get(key).Sale_OrderName_Set__c)){
                    List<String> SaleOrderNameList=tcsfMap.get(key).Sale_OrderName_Set__c.split('ON切割');
                    for(String orderName: SaleOrderNameList){
                        
                        if(SaleOrderNameSet.size()>=2){
                            break;
                        }
                        if(String.isNotBlank(orderName)){
                            SaleOrderNameSet.add('ON切割'+orderName);
                        }
                        
                    }
                    
                }
            }
            for(Consumable_order_details2__c cod : coList){
                if(cod.Detail_Count__c!=null){
                    DCount+=cod.Detail_Count__c;
                }
                if(cod.ProductPacking_list_manual__c!=null && cod.Detail_Count__c!=null){
                    LeastUnit+=cod.ProductPacking_list_manual__c*cod.Detail_Count__c;
                }
                if(cod.Product_OutDate__c > lastShipmentDate){
                    lastShipmentDate = cod.Product_OutDate__c;
                }
                if(SaleOrderNameSet.size()<2&&String.isNotBlank(cod.Sale_orderName__c)){
                   SaleOrderNameSet.add('ON切割'+cod.Sale_orderName__c);
                }
                if(cod.Intra_Trade_KRMB__c!=null && cod.Detail_Count__c!=null){
                    touRMB+=cod.Intra_Trade_KRMB__c*cod.Detail_Count__c;
                }
            }
            for(String item:SaleOrderNameSet){
                SaleOrderNameSetString+=item;
            }
            System.debug('lastShipmentDate:'+lastShipmentDate);
            if(tcsfMap.containsKey(key)){
                tcsf = tcsfMap.get(key);
                tcsf.SnapshotMonth__c = currentMonth;
                tcsf.ThisMonthDeliveryNumber__c += DCount;
                tcsf.ThisYearDeliveryNumber__c += DCount;
                //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;
                    tcsf.Consumable_Category3__c = coList[0].Consumable_product__r.Product2__r.ConsumCategory3__c;
                }
                //20231225  DB202312609378【IMS/TMS】ASP价格上传--平均价格，平均月销量 lwt end
                if(tcsf.LastShipmentDate__c < lastShipmentDate){
                    tcsf.LastShipmentDate__c = lastShipmentDate;
                }
                tcsf.Status__c = '销量计算';
                if(SaleOrderNameSet.size()>=2){
                    tcsf.IMS_Flag__c=true;
                }else{
                    tcsf.IMS_Flag__c=false;
                }
                tcsf.Least_Unit__c+=LeastUnit;
                tcsf.Sale_OrderName_Set__c=SaleOrderNameSetString;
                if(tcsf.Least_Unit__c>5&&tcsf.IMS_Flag__c){
					//20240308 lwt 出库价，销售状态修改 start
                    tcsf.put('FY_SaleStatus_Batch_'+fyear+'__c','存量');
                }else{

                    tcsf.put('FY_SaleStatus_Batch_'+fyear+'__c',null);
                    //20240308 lwt 出库价，销售状态修改 end
                }
                tcsf.ThisMonthDelivery_Price_IMS__c+=touRMB;
            }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){
                    String ASPPrice;
                    String ConsumCategory3;
                    // tcsf.ASP_Price__c = coList[0].Consumable_product__r.Product2__r.ASP_Price__c;
                    if(coList[0].Consumable_product__r.Product2__r.ConsumCategory3__c!=null){
                        tcsf.Consumable_Category3__c = coList[0].Consumable_product__r.Product2__r.ConsumCategory3__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 = DCount;
                tcsf.ThisYearDeliveryNumber__c = DCount;
                tcsf.LastShipmentDate__c = lastShipmentDate;
                tcsf.Type__c = coList[0].Product_Type__c ;
                tcsf.RecordTypeId = recordIdC;
                tcsf.Consumable_Category1__c = coList[0].Consumable_Category1__c;
                tcsf.Consumable_Category2__c = coList[0].Consumable_Category2__c;
                tcsf.Status__c = '销量计算';
                tcsf.Least_Unit__c=LeastUnit;
                
                if(SaleOrderNameSet.size()>=2){
                    tcsf.IMS_Flag__c=true;
                }else{
                    tcsf.IMS_Flag__c=false;
                }
                tcsf.Sale_OrderName_Set__c=SaleOrderNameSetString;
                if(tcsf.Least_Unit__c>5&&tcsf.IMS_Flag__c){
                    //20240308 lwt 出库价，销售状态修改 start
                    tcsf.put('FY_SaleStatus_Batch_'+fyear+'__c','存量');
                }else{
                    tcsf.put('FY_SaleStatus_Batch_'+fyear+'__c',null);
                    //20240308 lwt 出库价，销售状态修改 end
                }
                tcsf.ThisMonthDelivery_Price_IMS__c=touRMB;
            }
            tcsfMapNewOrUpdate.put(key,tcsf);
        } 

        
        System.debug('all1:'+tcsfMapNewOrUpdate.values());

        //更新或者插入销量表
        Database.upsert(tcsfMapNewOrUpdate.values());
    }

    global void finish(Database.BatchableContext BC) {
        
        //20240308 lwt 出库价，销售状态修改 start
        //20240226 lwt IMS/TMS:目标耗材数据跑完后，要到IMS同步销售状态 start
        if(this.hisFlag){
            Id batjobId = Database.executeBatch(new TrackConsumableSaleForecastBatch3(currentMonth,endDate,this.hisFlag), 200);
        }else{
            Id batjobId = Database.executeBatch(new TrackConsumableSaleForecastBatch3(currentMonth,endDate), 200);
        }
        //if(this.hisFLag){
        //    Id batjobId = Database.executeBatch(new ConsumableTargetManageBatch1(currentMonth,endDate,this.hisFLag), 200);
        //}else{
        //    Id batjobId = Database.executeBatch(new ConsumableTargetManageBatch1(currentMonth,endDate,false), 200);
        //}

        //20240226 lwt IMS/TMS:目标耗材数据跑完后，要到IMS同步销售状态 start end
        // Id batjobId = Database.executeBatch(new TrackConsumableSaleForecastBatch3(currentMonth,endDate), 200);
        //20240308 lwt 出库价，销售状态修改 end
    }
}