global class BeforeSSOpportunityBatch implements Database.Batchable<sObject> {
    private BatchIF_Log__c iflog;
    
    global BeforeSSOpportunityBatch() {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Log__c  = 'BeforeSSOpportunityBatch start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        //List<Opportunity> updateList = [select id,Inquiry_forcast_date_formular__c,Inquiry_forcast_date_copy__c from Opportunity
        //    where RecordType.DeveloperName in ('Opportunity','SI_Oppor')];
        //for(Opportunity op : updateList){
        //    op.Inquiry_forcast_date_copy__c = op.Inquiry_forcast_date_formular__c;
        //}
        //if(updateList.size() > 0){
        //    update updateList;
        //}
        //return Database.getQueryLocator([select id,Monthly_ship_target_txt__c,Monthly_ship_target__c,
        //                                        Monthly_order_target_txt__c,Monthly_order_target__c,
        //                                        NextMonthly_ship_target_txt__c,NextMonthly_ship_target__c,
        //                                        NextMonthly_order_target_txt__c,NextMonthly_order_target__c
        //    from Opportunity
        //    where RecordType.DeveloperName in ('Opportunity','SI_Oppor')]);
        //    
        //
        Date nowDay = Date.today();
        nowDay = nowDay.addDays(-15);
        Integer iyear = nowDay.year();
        if (nowDay.month() < 4) {
            iyear -= 1;
        }
        Date thisYd = Date.valueOf(iyear + '-4-1');    
        return Database.getQueryLocator([select id from Opportunity
            where RecordType.DeveloperName in ('Opportunity','SI_Oppor')
                and (StageName = '引合' or StageName = '注残' or StageName = '出荷'
                or ((StageName = '完了' or StageName = '削除' or StageName = '敗戦') and SFDCLast_Process_Date__c >= : thisYd)
                or (StageName = '完了' and Shipping_Finished_Day_Func__c >= : thisYd))]);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        // SWAG-CE55BX 预测优化 start
        StaticParameter.EscapeOppandStaTrigger = true;
        // SWAG-CE55BX 预测优化 end
        List<Opportunity> oppUpdateList = new List<Opportunity>();
        List<Opportunity> updateList = [select id,Inquiry_forcast_date_formular__c,Inquiry_forcast_date_copy__c
                                                ,OCM_man_province_cus__c,OCM_man_province_cus_txt__c
                                                // ,ownerId,owner.IsActive,Sales_assistant_name_text__c
                                                ,Opportunity_No__c
                                        from Opportunity
            where id in : scope];
        for(Opportunity op : updateList){
            if(op.Inquiry_forcast_date_copy__c != op.Inquiry_forcast_date_formular__c
                || op.OCM_man_province_cus__c != op.OCM_man_province_cus__c
                // || op.owner.IsActive == false
                ){
                op.Inquiry_forcast_date_copy__c = op.Inquiry_forcast_date_formular__c;
                op.OCM_man_province_cus_txt__c = op.OCM_man_province_cus__c;
                // op.OwnerId = op.owner.IsActive == false ? op.Sales_assistant_name_text__c :op.OwnerId; 
                oppUpdateList.add(op);

            }
        }
        if(oppUpdateList.size() > 0){
            Database.SaveResult[] lsr = Database.update(oppUpdateList, false);
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
System.debug('sr.isSuccess:' + sr.isSuccess());
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    iflog.ErrorLog__c += 'ERROR ' + oppUpdateList[tIdx].Opportunity_No__c + ' Opportunity:' + emsg + '\n';
                }
            }
            //update oppUpdateList;
        }


        oppUpdateList = new List<Opportunity>();
        List<Opportunity> OppList = new List<Opportunity>();
        OppList = [select id,Monthly_ship_target_txt__c,Monthly_ship_target__c,
                                                Monthly_order_target_txt__c,Monthly_order_target__c,
                                                NextMonthly_ship_target_txt__c,NextMonthly_ship_target__c,
                                                NextMonthly_order_target_txt__c,NextMonthly_order_target__c
            from Opportunity
            where id in : scope];
        
        for(Opportunity opp : OppList){
            if(opp.Monthly_ship_target_txt__c != (opp.Monthly_ship_target__c ? '1':'0')
                || opp.Monthly_order_target_txt__c != (opp.Monthly_order_target__c ? '1':'0')
                || opp.NextMonthly_ship_target_txt__c != (opp.NextMonthly_ship_target__c ? '1':'0')
                || opp.NextMonthly_order_target_txt__c != (opp.NextMonthly_order_target__c ? '1':'0')){
                opp.Monthly_ship_target_txt__c = opp.Monthly_ship_target__c ? '1':'0';
                opp.Monthly_order_target_txt__c = opp.Monthly_order_target__c ? '1':'0';
                opp.NextMonthly_ship_target_txt__c = opp.NextMonthly_ship_target__c ? '1':'0';
                opp.NextMonthly_order_target_txt__c = opp.NextMonthly_order_target__c ? '1':'0';
                oppUpdateList.add(opp);
            }
        }

        if(oppUpdateList.size() >0){
            update oppUpdateList;
        }
    }
    
    global void finish(Database.BatchableContext BC) {
        // 
        if (Test.isRunningTest() == false) {
            Database.executeBatch(new SSOpportunityBatch(null), 100);
        }
        // 
        iflog.Log__c += '\nBeforeSSOpportunityBatch 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;
    }
    
}