/** 备品智能化
 * 2023-11-5 Add by dzk 
 * OPD计划自动顺序排队
 * 获取下月14号——下下月13号,符合条件的OPD计划状态为计划中的备品申请数据
 */

public with sharing class  OPDManualSortController {
    // 获取下月14号——下下月13号,符合条件的OPD计划状态为计划中的备品申请数据
    @AuraEnabled(cacheable=true)
    public static ProLine initRenApply(){
        Date toDate = Date.today();
        // Date toDate = Date.newInstance(2023, 12, 28);// 测试数据切记切记 上线一定注释
        ProLine pro = new ProLine();
        List<RentalApply> renApply = new List<RentalApply>();
        // 获取当前日期是否为本月最后两个工作日
        Boolean weekDayCheck = getWorkDay(toDate);

        Boolean userProfileCheck = false;
        Boolean userProfileSystemCheck = false;
        // 获取从次月14日至再次月13日的日期
        Date startDate = toDate.addMonths(1).toStartOfMonth().addDays(13);
        Date endDate = toDate.addMonths(2).toStartOfMonth().addDays(12);

        // 获取当前用户权限
        User userData = [SELECT Id, Name,Profile.Name,Salesdepartment__c FROM User WHERE Id = :UserInfo.getUserId()];
        String Salesdept = userData.Salesdepartment__c; 
        if(Salesdept == '1.华北'){
            Salesdept = '医疗华北营业本部';
        }else if(Salesdept == '2.东北'){
            Salesdept = '医疗东北营业本部';
        }else if(Salesdept == '3.西北'){
            Salesdept = '医疗西北营业本部';
        }else if(Salesdept == '4.西南'){
            Salesdept = '医疗西南营业本部';
        }else if(Salesdept == '6.华南'){
            Salesdept = '医疗华南营业本部';
        }else if(Salesdept == '消化·呼吸领域解决方案本部'){
            Salesdept = 'Solution本部';
        }else if(Salesdept == '5.华东'){
            Salesdept = '医疗华东营业本部';
        }
        // 判断销售本部,销售本部负责人只能查看本部数据
        if(userData.Name == System.Label.OPDEast || userData.Name == System.Label.OPDNorth 
            || userData.Name == System.Label.OPDNorthEast || userData.Name == System.Label.OPDNorthWest
                || userData.Name == System.Label.OPDSouth || userData.Name == System.Label.OPDSouthWest
                    || userData.Name == System.Label.OPDDigestion || userData.Name == System.Label.OPDSg
                        || userData.Name == System.Label.OPDSolution || userData.Name == System.Label.OPDProduct
                            || userData.Name == System.Label.OPD_MA ){
            userProfileCheck = true;
        }
        else if(userData.Profile.Name == '系统管理员' || userData.Profile.Name == '2B3_备品中心管理者(照片)'){
            userProfileCheck = true;
            userProfileSystemCheck = true;
            Salesdept = '医疗华北营业本部';
        }
        
        try{
            List<Rental_Apply__c> renApplyList = [SELECT Id, Name, 
                                                                OPDPlan__c,
                                                                OPDType__c,//OPD计划来源
                                                                OPDPlanStatus__c,//OPD计划状态
                                                                RA_Status__c,//借出状态
                                                                Rental_Assistant__r.Name,//备品助理
                                                                Internal_asset_location_F__c,//备品存放地
                                                                Request_return_day__c,//预定归还日
                                                                Shipment_Post_Code__c,//邮政编码
                                                                OPDPlan__r.Name,
                                                                OPDPlan__r.RentalApplyNum__c,
                                                                OPDPlan__r.OPDPlanOCM_man_province_Rental__c,
                                                                Hospital__r.Name,
                                                                OPDPlanDate__c,
                                                                demo_purpose2__c,
                                                                Request_shipping_day__c,
                                                                OPDPlan__r.OPD_AdjustmentOrderNum_Flag__c
                                                           FROM Rental_Apply__c
                                                           WHERE Salesdept__c =:Salesdept 
                                                           AND OPDPlan__r.RentalApplyNum__c != null 
                                                           AND OPDPlan__r.OPDPlan_ImplementDate__c >=: startDate
                                                           AND OPDPlan__r.OPDPlan_ImplementDate__c <=: endDate
                                                           AND OPDPlan__r.If_AutoSort__c = 1
                                                           AND RA_Status__c IN ('草案中','申请中','已批准','申请中（OPD未通过）')  //20231224 sx add 备品智能化添加状态申请中（OPD未通过） 优化
                                                           ORDER BY OPDPlan__r.RentalApplyNum__c ASC];   
            for(Rental_Apply__c renApp : renApplyList){
                RentalApply renAppData = new RentalApply();
                renAppData.id = renApp.id;
                renAppData.Name = renApp.Name;
                renAppData.OPDPlan = renApp.OPDPlan__r.Name;
                renAppData.OCSM = renApp.OPDPlan__r.OPDPlanOCM_man_province_Rental__c;
                renAppData.Hospital = renApp.Hospital__r.Name;
                renAppData.OPDUseDate = renApp.OPDPlanDate__c;
                renAppData.Reson = renApp.demo_purpose2__c;
                renAppData.RequestDate = renApp.Request_shipping_day__c;
                renAppData.Num = Integer.valueOf(renApp.OPDPlan__r.RentalApplyNum__c);
                renAppData.OPDPlanId = renApp.OPDPlan__c;
                renAppData.selected = false;
                renAppData.isupdate = true;
                renAppData.OrdNumFlag = renApp.OPDPlan__r.OPD_AdjustmentOrderNum_Flag__c;
                renAppData.OPDType = renApp.OPDType__c;
                renAppData.OPDPlanStatus = renApp.OPDPlanStatus__c;
                renAppData.RAStatus = renApp.RA_Status__c;
                renAppData.RentalAssistantName = renApp.Rental_Assistant__r.Name;
                renAppData.InternalLocation = renApp.Internal_asset_location_F__c;
                renAppData.RequestReturnDay = renApp.Request_return_day__c;
                renApply.add(renAppData);
            }                                            
            pro.renApply = renApply; 
            pro.weekDayCheck = weekDayCheck; 
            pro.userProfileCheck = userProfileCheck;
            pro.userProfileSystemCheck = userProfileSystemCheck;
            pro.Salesdept = Salesdept;
            pro.dataSize = renApply.size();
            return pro;
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
    }

    // 排序最终保存
    @AuraEnabled
    public static String saveRenApply(String records){
        List<Rental_Apply__c> renApplyList = new List<Rental_Apply__c>();
        // List<OPDPlan__c> opdList = new List<OPDPlan__c>();
        Map<String,OPDPlan__c> opdMap = new Map<String,OPDPlan__c>();
        Map<Id,Integer> dataNumMap = new Map<Id,Integer>();
        try{
           List<RentalApply> ProLineList = 
            (List<RentalApply>)System.JSON.deserialize(records, List<RentalApply>.class);
            if(ProLineList.size() > 0){
                for(RentalApply rental : ProLineList){
                    OPDPlan__c opd = new OPDPlan__c();
                    opd.Id = rental.OPDPlanId;
                    
                    if(opdMap.containsKey(rental.OPDPlanId)){
                        if(rental.Num<opdMap.get(rental.OPDPlanId).RentalApplyNum__c){
                            opd.RentalApplyNum__c = rental.Num;
                            opd.OPD_AdjustmentOrderNum_Flag__c = rental.OrdNumFlag;
                        }
                    }else{
                        opd.RentalApplyNum__c = rental.Num;
                        opd.OPD_AdjustmentOrderNum_Flag__c = rental.OrdNumFlag;
                    }
                    opdMap.put(opd.Id,opd);
                }
                // update renApplyList;
                if(opdMap.size() > 0){
                    update opdMap.values();
                }
            }
            
            return 'Success'; 
        }catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
        
    }

    // 页面根据特定条件查询
    @AuraEnabled
    public static ProLine selectRental(String Salesdept){
        try{
            Date toDate = Date.today();
            // Date toDate = Date.newInstance(2023, 12, 28);// 测试数据切记切记 上线一定注释
            // 获取从次月14日至再次月13日的日期
            Date startDate = toDate.addMonths(1).toStartOfMonth().addDays(13);
            Date endDate = toDate.addMonths(2).toStartOfMonth().addDays(12);
            ProLine pro = new ProLine();
            List<RentalApply> renApply = new List<RentalApply>();
            List<Rental_Apply__c> renApplyList = new List<Rental_Apply__c>();
            String query = 'SELECT Id,OPDPlan__c,OPDPlan__r.OPD_AdjustmentOrderNum_Flag__c,OPDPlan__r.RentalApplyNum__c, OPDType__c,OPDPlanStatus__c,RA_Status__c,Rental_Assistant__r.Name,Internal_asset_location_F__c,Request_return_day__c,Shipment_Post_Code__c,Name,OPDPlan__r.Name, Hospital__r.Name,OPDPlan__r.OPDPlanOCM_man_province_Rental__c,OPDPlan__r.HospitalName__c, OPDPlanDate__c, demo_purpose2__c, Request_shipping_day__c FROM Rental_Apply__c';
            query += ' WHERE Salesdept__c = \'' + Salesdept + '\'';
            query += ' AND OPDPlan__r.Status__c = \'计划中\'';
            query += ' AND OPD_OrderNum__c != null';
            query += ' AND OPDPlan__r.RentalApplyNum__c != null';
            query += ' AND OPDPlan__r.OPDPlan_ImplementDate__c >=: startDate ' ;
            query += ' AND OPDPlan__r.OPDPlan_ImplementDate__c <=: endDate';
            query += ' AND RA_Status__c IN (\'草案中\',\'申请中\',\'已批准\',\'申请中（OPD未通过）\') ';         //20231224 sx add 备品智能化添加状态申请中（OPD未通过） 优化
            query += ' AND OPDPlan__r.If_AutoSort__c = 1';
            query += ' ORDER BY OPDPlan__r.RentalApplyNum__c ASC';
            system.debug('query--------------' + query);
            renApplyList  = Database.query(query);
            for(Rental_Apply__c ren : renApplyList){
                RentalApply renAppData = new RentalApply();
                renAppData.id = ren.id;
                renAppData.Name = ren.Name;
                renAppData.OPDPlan = ren.OPDPlan__r.Name;
                renAppData.OCSM = ren.OPDPlan__r.OPDPlanOCM_man_province_Rental__c;
                renAppData.Hospital = ren.Hospital__r.Name;
                renAppData.OPDUseDate = ren.OPDPlanDate__c;
                renAppData.Reson = ren.demo_purpose2__c;
                renAppData.RequestDate = ren.Request_shipping_day__c;
                // renAppData.Num = Integer.valueOf(ren.OPD_OrderNum__c);
                renAppData.Num = Integer.valueOf(ren.OPDPlan__r.RentalApplyNum__c);
                renAppData.OPDPlanId = ren.OPDPlan__c;
                renAppData.selected = false;
                renAppData.isupdate = true;
                // renAppData.OrdNumFlag = ren.OPD_AdjustmentOrderNum_Flag__c;
                renAppData.OrdNumFlag = ren.OPDPlan__r.OPD_AdjustmentOrderNum_Flag__c;
                renAppData.OPDType = ren.OPDType__c;
                renAppData.OPDPlanStatus = ren.OPDPlanStatus__c;
                renAppData.RAStatus = ren.RA_Status__c;
                renAppData.RentalAssistantName = ren.Rental_Assistant__r.Name;
                renAppData.InternalLocation = ren.Internal_asset_location_F__c;
                renAppData.RequestReturnDay = ren.Request_return_day__c;
                renAppData.UpdateCheck = false;
                renApply.add(renAppData);
            }
            pro.renApply = renApply; 
            pro.weekDayCheck = true; 
            pro.userProfileCheck = true;
            pro.dataSize = renApply.size();
            return pro;
        }catch(Exception e){
            return null;
        }
        
    }

    // 判段是否是当月最后两个工作日
    public static Boolean getWorkDay(Date toDate){
        Boolean weekDayCheck = false;
        // 获取是否为本月最后两个工作日
        Date mon1stDate = Date.newInstance(toDate.year(), toDate.month(), 1);
        //每月到今天的工作日
        Integer workdays = UpdateUserTextColBatch.getOlympusWorkDayCount(mon1stDate, toDate);
        //获取这个月的最后一天
        Date days = Date.newInstance(toDate.year(), toDate.month() + 1, 0);
        Integer monDays = days.day();
        Date dayEnd = Date.newInstance(toDate.year(), toDate.month(), monDays);
        //获取这个月有多少个工作日
        Integer monWorkDays = UpdateUserTextColBatch.getOlympusWorkDayCount(mon1stDate, dayEnd);
        //获取判断今天是否是工作日
        List<OlympusCalendar__c> ssDay
            = [Select IsWorkDay__c From OlympusCalendar__c Where Date__c = :toDate];
        if ((monWorkDays - workdays == 1 || monWorkDays - workdays == 0)
                && ssDay != null && ssDay.size() > 0 && ssDay.get(0).IsWorkDay__c == 1 ) {
            weekDayCheck = true;
        }
        // 测试时使用，暂时这样，测试后恢复
        // Boolean weekDayCheck = true;
        return weekDayCheck;
    }

    public class ProLine { 
        @AuraEnabled
        public List<RentalApply> renApply { get; set; } 
        @AuraEnabled
        public String Salesdept { get; set; } 
        @AuraEnabled
        public Boolean weekDayCheck { get; set; } 
        @AuraEnabled
        public Boolean userProfileCheck { get; set; } 
        @AuraEnabled
        public Boolean userProfileSystemCheck { get; set; } 
        @AuraEnabled
        public Integer dataSize { get; set; } 
    }

    public class RentalApply {
        @AuraEnabled
        public String id { get; set; } 
        @AuraEnabled
        public String Name { get; set; } 
        @AuraEnabled
        public String OPDPlan { get; set; } 
        @AuraEnabled
        public String OPDPlanId { get; set; } 
        @AuraEnabled
        public String Hospital { get; set; } 
        @AuraEnabled
        public String OCSM { get; set; } 
        @AuraEnabled
        public Date OPDUseDate { get; set; } 
        @AuraEnabled
        public String Reson { get; set; } 
        @AuraEnabled
        public Date RequestDate { get; set; } 
        @AuraEnabled
        public Integer Num { get; set; } 
        @AuraEnabled
        public Boolean selected { get; set; } 
        @AuraEnabled
        public Boolean isupdate { get; set; } 
        @AuraEnabled
        public Boolean OrdNumFlag { get; set; } 
        @AuraEnabled
        public String OPDType { get; set; }//OPD计划来源
        @AuraEnabled
        public String OPDPlanStatus { get; set; }//OPD计划状态
        @AuraEnabled
        public String RAStatus { get; set; }//借出状态
        @AuraEnabled
        public String RentalAssistantName { get; set; }//备品助理
        @AuraEnabled
        public String InternalLocation { get; set; }//备品存放地
        @AuraEnabled
        public Date RequestReturnDay { get; set; }//预定归还日
        @AuraEnabled
        public Boolean UpdateCheck { get; set; }
        
    }

       
}