global class EquipmentRenewBatch implements Database.Batchable<sObject>,Database.Stateful {
    public String query;
    public Date toDayTime = Date.today();
    public Date start_date1 ;
    public Date end_date1 ;
    public Date start_date2 ;
    public Date end_date2 ;
    public Date deadlineTime;
    private BatchIF_Log__c iflog;

     
    global EquipmentRenewBatch() {
        this.query = '';
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Log__c  = 'EquipmentRenewBatch start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        if (toDayTime.month() >= 4 && toDayTime.month() <= 9) {
            this.start_date1 = Date.newInstance(toDayTime.year()-1,4,1);
            this.end_date1 = Date.newInstance(toDayTime.year()-1,12,31);
            this.start_date2 = Date.newInstance(toDayTime.year(),1,1);
            this.end_date2 = Date.newInstance(toDayTime.year(),6,30);
            this.deadlineTime = Date.newInstance(toDayTime.year(),3,31);
        }else{
            this.start_date1 = Date.newInstance(toDayTime.year()-1,10,1);
            this.end_date1 = Date.newInstance(toDayTime.year(),6,30);
            this.start_date2 = Date.newInstance(toDayTime.year(),7,1);
            this.end_date2 = Date.newInstance(toDayTime.year(),12,31);
            this.deadlineTime = Date.newInstance(toDayTime.year(),9,30);
        }
        query+='select Id,(select Id,CurrentContract__c,CurrentContract__r.Contract_End_Date__c,CurrentContract__r.Contract_Start_Date__c,CurrentContract__r.New_Contract_TypeF_Text__c,Product2.ServiceCategory__c,CurrentContract__r.Status__c,Product2.Category3__c,Product2.Category4__c' 
                + ' from Asset_Hospital__r where CurrentContract__r.Contract_End_Date__c >= :start_date1 and CurrentContract__r.Contract_End_Date__c <= :end_date2)'
                + ' from Account';

        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, list<Account> Accounts) {
        List<Account_Service_Of_Target__c> asots = new List<Account_Service_Of_Target__c>();
        List<Id> accIds = new List<Id>();
        Map<String,Account_Service_Of_Target__c> asotMap = new Map<String,Account_Service_Of_Target__c>();
        for (Account acc1 : Accounts) {
            accIds.add(acc1.id);
        }
        List<Account_Service_Of_Target__c> asotList = [select Id,Account_HP__c,OCSM_Period_half__c from Account_Service_Of_Target__c where Account_HP__c in :accIds];
        if (asotList != null) {
            for (Account_Service_Of_Target__c asot : asotList) {
                for (Id accid : accIds) {
                    if (asot.Account_HP__c == accid) {
                        asotMap.put(accid+asot.OCSM_Period_half__c,asot);
                    }
                }
            }
        }
        
        for (Account acc : Accounts) {
            Account_Service_Of_Target__c asot = new Account_Service_Of_Target__c();
            List<Asset> AssetsTarget = new List<Asset>();
            List<Asset> AssetsReal = new List<Asset>();
                // 续签目标（硬）：泌尿科用硬性镜
                Integer mirror_1 = 0;
                // 续签目标（软）：鼻咽喉镜
                Integer mirror_2 = 0;
                //续签目标（周边）：光源
                Integer mirror_3 = 0;
                // 实际续签数（硬）：泌尿科用硬性镜
                Integer mirror_4 = 0;
                // 实际续签数（硬）：妇科用硬性镜
                Integer mirror_5 = 0;
                // 实际续签数（周边）：光源
                Integer mirror_6 = 0;
                // 实际续签数（软）：电子镜
                Integer mirror_7 = 0;

            for (Asset ass : acc.Asset_Hospital__r) {
                // 分子
                    //1. 设备关联的合同类型是“续签合同” 2. 在2023年3月31日前系统生效完毕
                    if (ass.CurrentContract__r.Contract_End_Date__c <= Date.newInstance(toDayTime.year()+1,3,31) && ass.CurrentContract__r.New_Contract_TypeF_Text__c == '续签合同') {
                            // 标记为是否续签实际设备
                            ass.IF_Renewalrate_Real_Asset__c = '1';
                            AssetsReal.add(ass);
                            
                    }
                    // 分母
                    /*1H考核对象： 1）、2021.4.1-2021.12.31合同结束且截止2022.3.31未续签的设备；
                    2）、2022.1.1-2022.6.30合同结束，不论该设备是否续签
                    2H考核对象： 1）、2021.10.1-2022.6.30合同结束且截止2022.9.30未续签的设备；
                    2）、2022.7.1-2022.12.31 合同结束，不论该设备是否续签
                    */
                    Boolean result = true;
                    if (ass.Product2.ServiceCategory__c != null) {
                        if (ass.CurrentContract__r.Contract_End_Date__c>=start_date1&&ass.CurrentContract__r.Contract_End_Date__c<=end_date1){
                            if (ass.CurrentContract__c == null || ass.CurrentContract__r.Status__c == '合同结束') {
                                ass.IF_Renewalrate_Target_Asset__c = '1';
                                AssetsTarget.add(ass);
                                result = false;
                            }
                            if (result) {
                                if (ass.CurrentContract__r.Contract_Start_Date__c <= deadlineTime) {
                                ass.IF_Renewalrate_Target_Asset__c = '1';
                                AssetsTarget.add(ass);
                                }
                            } 
                        }
                        if (ass.CurrentContract__r.Contract_End_Date__c>=start_date2&&ass.CurrentContract__r.Contract_End_Date__c<=end_date2) {
                            ass.IF_Renewalrate_Target_Asset__c = '1';
                            AssetsTarget.add(ass);
                        }
                    }    
                if (AssetsReal!=null) {
                    try {
                        update AssetsReal;
                    }
                    catch (Exception e) {
                        iflog.ErrorLog__c += 'ERROR'+'['+'update AssetsReal:'+']'+e.getMessage()+'\n';
                     }
                }
                 if (AssetsTarget!=null) {
                    try {
                        update AssetsTarget;
                    }
                    catch (Exception e) {
                        iflog.ErrorLog__c += 'ERROR'+'['+'update AssetsTarget:'+']'+e.getMessage()+'\n';
                     }
                }
            }
             for (Asset AtoHp: AssetsReal) {
                    if (AtoHp.Product2.Category4__c == '泌尿科用硬性镜') {
                        mirror_4++;
                    }
                    if (AtoHp.Product2.Category4__c == '妇科用硬性镜') {
                        mirror_5++;
                    }
                    if (AtoHp.Product2.Category3__c == '光源') {
                        mirror_6++;
                    }
                    if (AtoHp.Product2.ServiceCategory__c =='软性镜') {
                        mirror_7++;
                    }
            }
            for (Asset ata : AssetsTarget) {
                    if (ata.Product2.Category4__c == '泌尿科用硬性镜') {
                        mirror_1++;
                    }
                    if(ata.Product2.ServiceCategory__c =='软性镜'){
                        mirror_2++;
                    }
                    if (ata.Product2.Category3__c == '光源') {
                        mirror_3++;
                    } 
            }
            if (asotMap != null) {
                Account_Service_Of_Target__c asotOne = new Account_Service_Of_Target__c();
                if (toDayTime.month() >= 4 && toDayTime.month() <= 9) {
                    asotOne = asotMap.get(acc.id+'1H');
                }else{
                    asotOne = asotMap.get(acc.id+'2H'); 
                }
                if (asotOne != null) {
                    asotOne.Renew_Target_Rigid_Mirror_2__c = mirror_1;
                    asotOne.Renew_Target_Soft_Mirror_2__c = mirror_2;
                    asotOne.Renew_Target_Correlation_Lightsource__c = mirror_3;
                    asotOne.Renew_Finish_Rigid_Mirror_2__c = mirror_4;
                    asotOne.Renew_Finish_Rigid_Mirror_3__c = mirror_5;
                    asotOne.Renew_Finish_Correlation_Lightsource__c = mirror_6;
                    asotOne.Renew_Finish_Rigid_Mirror_1__c = mirror_7;
                    asots.add(asotOne);
                }  
            }
            if (asotList == null) {
                Account_Service_Of_Target__c asot1 = new Account_Service_Of_Target__c();
                asot1.Account_HP__c = acc.id;
                asot1.Renew_Target_Rigid_Mirror_2__c = mirror_1;
                asot1.Renew_Target_Soft_Mirror_2__c = mirror_2;
                asot1.Renew_Target_Correlation_Lightsource__c = mirror_3;
                asot1.Renew_Finish_Rigid_Mirror_2__c = mirror_4;
                asot1.Renew_Finish_Rigid_Mirror_3__c = mirror_5;
                asot1.Renew_Finish_Correlation_Lightsource__c = mirror_6;
                asot1.Renew_Finish_Rigid_Mirror_1__c = mirror_7;
                if (toDayTime.year()<=2029 && toDayTime.year()>=2023) {
                    asot1.OCSM_Period__c =  'FY'+toDayTime.year();
                    if (toDayTime.month() >= 4 && toDayTime.month() <= 9) {
                        asot1.OCSM_Period_half__c =  '1H';
                    }else{
                        asot1.OCSM_Period_half__c =  '2H';
                    } 
                }
                asots.add(asot1);
            }
        }  
        if (asots!=null) {
            try {
                UpSert asots;
            }
            catch (Exception e) {
                iflog.ErrorLog__c += 'ERROR'+'['+'UpSert asots:'+']'+e.getMessage()+'\n';
            }  
        }  
    }

    global void finish(Database.BatchableContext BC) {
        iflog.Log__c += '\nEquipmentRenewBatch end';
        String tmp = iflog.ErrorLog__c;
        if (tmp.length() > 65000) {
            tmp = tmp.substring(0, 65000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        update iflog;
    }
}