global without sharing class SyncProvinceWIndowToSignForm implements Database.Batchable<sObject>, Database.Stateful {
    private Set<String> changedWindowProvince { get; set; }

    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 ';
        if (changedWindowProvince != null && changedWindowProvince.size() > 0) {
            if (!Test.isRunningTest()) {
                query += '  where isProcessed__c = false  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) {
        system.debug('sign form list size:' + signFormList.size());
        // 取得OCM管理省信息
        Map<String, OCM_Management_Province__c> provinceMap = DNUpsertBatch.getManagementProvince();
        // 判断需要更新的签收单
        List<eSignForm__c> updList = new List<eSignForm__c>();
        if (signFormList != null && signFormList.size() > 0) {
            for (eSignForm__c temp : signFormList) {
                String provinceName = Test.isRunningTest() ? '北京市' : 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);
                system.debug('Upsert Result' + lsr);
            }
        }
    }

    global void finish(Database.BatchableContext BC) {
    }

    public static void syncProvinceWIndow(Set<String> changedWindowProvince) {
        if (changedWindowProvince != null && changedWindowProvince.size() > 0) {
            Database.executeBatch(new SyncProvinceWIndowToSignForm(changedWindowProvince), 200);
           
        }
    }
}
