global with sharing class SS_MonthlySubmitDailyReportBatch implements Database.Batchable<sObject> , Schedulable, Database.Stateful{

    /**
	 * スケジュール用メソッド
	 */
    global void execute(SchedulableContext sc) {
        ID batchProcessId = Database.executeBatch(new SS_MonthlySubmitDailyReportBatch(), 20);
    }

    /**
     * 省(文本)が空のレコードが対象になる
     * 
     */
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([Select Id,
        										OwnerId,
        										Province_Text__c,
        										Product_specialist_incharge_product_text__c,
        										Job_Category_Text__c,
        										Salesdepartment_Text__c,
        										Fiscal_Workdays__c,
        										CreatedDate
        								   from SS_monthly_submit_daily_report__c
        								  where Province_Text__c = null]);
    }

    global void execute(Database.BatchableContext BC, list<SS_monthly_submit_daily_report__c> sList) {
    	//useridリストを作る
	    List<Id> usrIds = new List<Id>();
	    for (SS_monthly_submit_daily_report__c ss : sList) {
	        if (ss.OwnerId != null) usrIds.add(ss.OwnerId);
	    }

		//ユーザマップを作る
        Map<Id, User> usrInfoMap = new Map<Id, User>();
        for (User u : [select Id, Province__c, Product_specialist_incharge_product__c, Job_Category__c, Salesdepartment__c, Fiscal_Start_Date__c, Use_Start_Date__c from User where Id in :usrIds]) {
            usrInfoMap.put(u.Id, u);
        }
    	
		//値を設定
        for (SS_monthly_submit_daily_report__c ss : sList) {
            if (usrInfoMap.containsKey(ss.OwnerId)) {
                User u = usrInfoMap.get(ss.OwnerId);

                ss.Province_Text__c = u.Province__c;
                ss.Product_specialist_incharge_product_text__c = u.Product_specialist_incharge_product__c;
                ss.Job_Category_Text__c = u.Job_Category__c;
                ss.Salesdepartment_Text__c = u.Salesdepartment__c;
                //前月末でセット
				ss.CreateDateForBatch__c = Date.newInstance(ss.CreatedDate.year(), ss.CreatedDate.month(), 0);

                //到考核对象月月末的工作日(今年度)をセット
	            Date fromDate4 = u.Fiscal_Start_Date__c;
	            if (u.Use_Start_Date__c != null && u.Use_Start_Date__c > u.Fiscal_Start_Date__c) {
	                fromDate4 = u.Use_Start_Date__c;
	            }
	            decimal workDays = decimal.valueOf(UpdateUserTextColBatch.getOlympusWorkDayCount(fromDate4, ss.CreateDateForBatch__c));
	            ss.Fiscal_Workdays__c = workDays;
            }
        }
        update sList;
	}

	global void finish(Database.BatchableContext BC) {
        // 今回はやることないです
    }
}