global class OCMManagementProvinceBatch implements Database.Batchable<sObject> {

	String query;
	String targetId;

	global OCMManagementProvinceBatch() {}

	global OCMManagementProvinceBatch(String oppId) {
		targetId = oppId;
	}

	global Database.QueryLocator start(Database.BatchableContext BC) {
		// 只更新询价【状态1】为"询价"和"注残"的
		List<String> stageList = new List<String>();
		stageList.add('引合');
		stageList.add('注残');
		// 取得询价对象
		query = 'select id, Opportunity_Category__c, Owner.Dept__c, Sales_assistant_name_text__c, Account.OCM_Management_Province_HP__c, OCM_man_province__c, OCM_man_province_no_eng__c from Opportunity ';
		query += ' where StageName = :stageList ';
		if (targetId != null && targetId != '') {
			query += ' and id = :targetId ';
		}
		return Database.getQueryLocator(query);
	}

   	global void execute(Database.BatchableContext BC, List<Opportunity> oppList) {
   		// 取得OCM管理省信息
   		List<OCM_Management_Province__c> mpList = [select id, Name, GI_assistant__c, SP_assistant__c, Energy_assistant__c from OCM_Management_Province__c];
   		Map<String, OCM_Management_Province__c> mpMap = new Map<String, OCM_Management_Province__c>();
   		for (OCM_Management_Province__c mp : mpList) {
   			mpMap.put(mp.Name, mp);
   		}
   		// 判断需要更新的询价
   		List<Opportunity> updList = new List<Opportunity>();
   		for (Opportunity opp : oppList) {
   			OCM_Management_Province__c mp = mpMap.get(opp.OCM_man_province_no_eng__c);

   			Id uid = null;
   			if (opp.OCM_man_province__c == '能量') {
   				uid = mp == null ? null : mp.Energy_assistant__c;
   			} else if (opp.Opportunity_Category__c == 'GI' || opp.Opportunity_Category__c == 'BF' || opp.Opportunity_Category__c == 'ET') {
   				uid = mp == null ? null : mp.GI_assistant__c;
   			} else {
   				uid = mp == null ? null : mp.SP_assistant__c;
   			}
   			// 询价助理是否有变化
   			if (opp.Sales_assistant_name_text__c != uid) {
   				Opportunity upd = new Opportunity(
   					id = opp.Id,
   					Sales_assistant_name_text__c = uid
   				);
   				updList.add(upd);
   			}
   		}
   		// 询价更新
   		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 Opp: ' + updList[tIdx].Id + ' msg: ' + emsg);
                }
            }
        }
	}

	global void finish(Database.BatchableContext BC) {}

}