global without sharing class SyncProvinceWIndowToSignForm implements Database.Batchable<sObject>,Database.Stateful{

    private Set<String> changedWindowProvince{set;get;}

	global SyncProvinceWIndowToSignForm(Set<String> changedWindowProvince) {
		this.changedWindowProvince = changedWindowProvince;
	}

	global Database.QueryLocator start(Database.BatchableContext BC) {
		String query = 'select Sales_assistant_name_text__c,isProcessed__c,OCM_man_province_cus__c from eSignForm__c ';
		query += ' where isProcessed__c = false ';
		if (changedWindowProvince != null && changedWindowProvince.size() >0 ) {
			query += ' and OCM_man_province_cus__c = :changedWindowProvince ';
			system.debug('SOQL' + query);
			return Database.getQueryLocator(query);
		}
		return null;
	}

   	global void execute(Database.BatchableContext BC, List<eSignForm__c> signFormList) {
   		// 取得OCM管理省信息
		Map<String, OCM_Management_Province__c> provinceMap = DNUpsertBatch.getManagementProvince();
   		// 判断需要更新的签收单
   		List<eSignForm__c>  updList = new List<eSignForm__c>();
   		for (eSignForm__c temp : signFormList) {
			String provinceName = temp.OCM_man_province_cus__c;
			if( provinceName != '' && provinceMap.containsKey(provinceName) && provinceMap.get(provinceName).Window1__c != null){
				temp.Sales_assistant_name_text__c = provinceMap.get(provinceName).Window1__c;
   				updList.add(temp);
   			}
   		}
   		// 签收单更新
		if (updList.size() > 0) {
            Database.SaveResult[] lsr = Database.update(updList, false);
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    System.debug('=====Error Sign: ' + updList[tIdx].Id + ' msg: ' + emsg);
                }
            }
        }
	}

	global void finish(Database.BatchableContext BC) {}


    public static void syncProvinceWIndow(Set<String> changedWindowProvince) {
        Database.executeBatch(new SyncProvinceWIndowToSignForm(changedWindowProvince),200);
    }
}