global class OCMManagementProvinceBatch implements Database.Batchable<sObject> {

	String query;
	String targetId;
	private BatchIF_Log__c iflog;
	private String errStr;
	private Map<String, OCM_Management_Province__c> mpMap; 
    
	List<String> oppList = new List<String>(); 
	global OCMManagementProvinceBatch() {
		iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMManagementProvinceBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMManagementProvinceBatch start1\n';
        iflog.ErrorLog__c = '';
        insert iflog;
	}

	global OCMManagementProvinceBatch(String oppId) {
		targetId = oppId;
		iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMManagementProvinceBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMManagementProvinceBatch start2\n';
        iflog.ErrorLog__c = '';
        insert iflog;
	}
	global OCMManagementProvinceBatch(List<String> oppList) {
        this.oppList = oppList;
		iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMManagementProvinceBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMManagementProvinceBatch start3\n';
        iflog.ErrorLog__c = '';
        insert iflog;
    }  

	global Database.QueryLocator start(Database.BatchableContext BC) {
		
		// 只更新询价【状态1】为"询价"和"注残"的
		List<String> stageList = new List<String>();
		stageList.add('引合');
		stageList.add('注残');
		//办事处ET/ENG担当共享 you 20230222 只更新“注残”，“出荷”，“完了” 
		stageList.add('出荷');
		stageList.add('完了');
		
		// 取得询价对象
		//询价：计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 start
		// 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 = 'select id,Ownerid, Opportunity_Category__c, Owner.Dept__c, Sales_assistant_name_text__c, Account.OCM_Management_Province_HP__c, OCM_man_province__c, OCM_man_province_new__c,StageName,SAP_Province__c,Opp_order_Type__c from Opportunity ';
		//询价：计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 end
		
		query += ' where StageName = :stageList ';
		
		if (targetId != null && targetId != '') {
			query += ' and id = :targetId ';
		}
		if(null!= oppList && oppList.size()>0){
			query += ' and Id In :oppList ';
		 }
		 query += ' order by OCM_man_province_new__c';
		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,Province__c,ET_DataWindow__c,ET_BusinessWindow__c,ET_Assistant1__c,ET_Assistant2__c,ENG_DataWindow__c,ENG_BusinessWindow__c,ENG_Assistant1__c,ENG_Assistant2__c,ENGShareOpp__c,ETShareOpp__c,ENG_Flag__c,ET_Flag__c from OCM_Management_Province__c];
   		mpMap = new Map<String, OCM_Management_Province__c>();
		Map<String, OCM_Management_Province__c> mpshareoppMap = new Map<String, OCM_Management_Province__c>();
   		for (OCM_Management_Province__c mp : mpList) {
   			mpMap.put(mp.Name, mp);
			mpshareoppMap.put(mp.Province__c, mp);
   		}
   		// 判断需要更新的询价
   		List<Opportunity> updList = new List<Opportunity>();
   		for (Opportunity opp : oppList) {
			//询价：计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 start
   			// OCM_Management_Province__c mp = mpMap.get(opp.OCM_man_province_no_eng__c);
			   OCM_Management_Province__c mp = mpMap.get(opp.OCM_man_province_new__c);
			//询价：计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 end
   			Id uid = null;
			if(opp.StageName == '注残' || opp.StageName == '引合'){
				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);
                }
            }
        }
		//询价共享 根据 省和耗材分类
		//删掉原来的ET/ENG担当，插入新的担当  
		Map<Id, Opportunity>  otmMap = new Map<Id, Opportunity>();
        //新增的询价共享
		List<OpportunityShare> addoppsharlist =new List<OpportunityShare>();
		//需要删除的原担当的共享
		List<OpportunityShare> deleteoppsharlist =new List<OpportunityShare>();
		Set<String> mpset = new Set<String>(); //询价对应省 如贵州 用来限制TMS和IMS得查询数据量(因为处理ims数据时超50001)
		
		for (Opportunity opp : oppList) {
			
			if(opp.StageName == '注残' || opp.StageName == '出荷'|| opp.StageName == '完了'){
				if(null!=opp.Opp_order_Type__c && ''!=opp.Opp_order_Type__c){
					otmMap.put(opp.Id,opp);  //oppid 担当id
					mpset.add(opp.OCM_man_province_new__c);
				}
                
			}
		}
		if(!otmMap.isEmpty()){
			// 手动共享不能删除原来已经存在的共享  
            List<OpportunityShare> osList = [select id,UserOrGroupId,OpportunityId from OpportunityShare where OpportunityId in :otmMap.keySet() and OpportunityAccessLevel = 'read' and rowCause = 'Manual'];
			
			Map<Id,list<String>> allmap = new Map<Id,list<String>>();
			
			for(OpportunityShare oppshare : osList){
			    list<String> allFSEUserIDList = new list<String>();
				if(otmMap.containsKey(oppshare.OpportunityId)){
				    OCM_Management_Province__c mpshareopp = mpshareoppMap.get(otmMap.get(oppshare.OpportunityId).SAP_Province__c);
					if(otmMap.get(oppshare.OpportunityId).Opp_order_Type__c=='ET'){
						if(null!=mpshareopp && null!=mpshareopp.ETShareOpp__c && mpshareopp.ET_Flag__c==true){
							String[] etnames = mpshareopp.ETShareOpp__c.split(',');
							for(String etname : etnames) {
								if (String.isNotBlank(etname)) {
								allFSEUserIDList.add(etname);//需要删掉的et用户id
								}
							}
						}
					    
					}else{
						if(null!=mpshareopp && null!=mpshareopp.ENGShareOpp__c && mpshareopp.ENG_Flag__c==true){
							String[] engnames = mpshareopp.ENGShareOpp__c.split(',');
							for(String engname : engnames) {
								if (String.isNotBlank(engname)) {
								allFSEUserIDList.add(engname);//需要删掉的eng用户id
								}
							}
						}
						
					}
				}
				allmap.put(oppshare.OpportunityId,allFSEUserIDList); 
			}
			
			//List<OpportunityShare> oppsharlist =new List<OpportunityShare>();
			Map<String ,OpportunityShare> oppsharlist =new Map<String ,OpportunityShare>();
			system.debug('====opp==='+otmMap.size());
			for(Id oppid:otmMap.keySet()){
                 Opportunity oppobj=otmMap.get(oppid);//获得当前对象
				 if (mpshareoppMap.containsKey(oppobj.SAP_Province__c)) {
				   OCM_Management_Province__c mpshareopp = mpshareoppMap.get(oppobj.SAP_Province__c);
				   if(null!=oppobj.Opp_order_Type__c && ''!= oppobj.Opp_order_Type__c){
					//String aa='005C8000000219sIAA,00GC80000001UR7MAM,00GC80000000ujBMAQ,00GC80000002F7pMAE,00GC80000000uj8MAA,00GC80000001USsMAM,00GC80000000v68MAA,00GC80000000ujKMAQ,00GC80000000upQMAQ';
					  if(oppobj.Opp_order_Type__c=='ET'){
						if(mpshareopp.ET_Flag__c==true || System.Label.OCMManagementProvinceBatchFlag == '0'){
							if(null!=mpshareopp && null!=mpshareopp.ET_DataWindow__c && !''.equals(mpshareopp.ET_DataWindow__c) && oppobj.Ownerid !=mpshareopp.ET_DataWindow__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ET_DataWindow__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ET_DataWindow__c;
								oppsharlist.put(key,oppshare);
							}
							if(null!=mpshareopp && null!=mpshareopp.ET_BusinessWindow__c && !''.equals(mpshareopp.ET_BusinessWindow__c) && oppobj.Ownerid !=mpshareopp.ET_BusinessWindow__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ET_BusinessWindow__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ET_BusinessWindow__c;
								oppsharlist.put(key,oppshare);
							}
							if(null!=mpshareopp && null!=mpshareopp.ET_Assistant1__c && !''.equals(mpshareopp.ET_Assistant1__c) && oppobj.Ownerid !=mpshareopp.ET_Assistant1__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ET_Assistant1__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ET_Assistant1__c;
								oppsharlist.put(key,oppshare);
							}
							if(null!=mpshareopp && null!=mpshareopp.ET_Assistant2__c && !''.equals(mpshareopp.ET_Assistant2__c) && oppobj.Ownerid !=mpshareopp.ET_Assistant2__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ET_Assistant2__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ET_Assistant2__c;
								oppsharlist.put(key,oppshare);
							}
							system.debug('ET==='+oppsharlist);  
						}
						
					  }else{//SP,ENG 
						if(mpshareopp.ENG_Flag__c==true ||  System.Label.OCMManagementProvinceBatchFlag == '0'){
							if(null!=mpshareopp && null!=mpshareopp.ENG_DataWindow__c && !''.equals(mpshareopp.ENG_DataWindow__c) && oppobj.Ownerid !=mpshareopp.ENG_DataWindow__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ENG_DataWindow__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ENG_DataWindow__c;
								oppsharlist.put(key,oppshare);
							}
							if(null!=mpshareopp && null!=mpshareopp.ENG_BusinessWindow__c && !''.equals(mpshareopp.ENG_BusinessWindow__c) && oppobj.Ownerid !=mpshareopp.ENG_BusinessWindow__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ENG_BusinessWindow__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ENG_BusinessWindow__c;
								oppsharlist.put(key,oppshare);
							}
							if(null!=mpshareopp && null!=mpshareopp.ENG_Assistant1__c && !''.equals(mpshareopp.ENG_Assistant1__c) && oppobj.Ownerid !=mpshareopp.ENG_Assistant1__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ENG_Assistant1__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ENG_Assistant1__c;
								oppsharlist.put(key,oppshare);
							}
							if(null!=mpshareopp && null!=mpshareopp.ENG_Assistant2__c && !''.equals(mpshareopp.ENG_Assistant2__c) && oppobj.Ownerid !=mpshareopp.ENG_Assistant2__c){
								OpportunityShare oppshare = new OpportunityShare(
								OpportunityId = oppid,
								UserOrGroupId = mpshareopp.ENG_Assistant2__c,
								RowCause = 'Manual',
								OpportunityAccessLevel = 'read');
								//oppsharlist.add(oppshare);
								String key = oppid +'-' + mpshareopp.ENG_Assistant2__c;
								oppsharlist.put(key,oppshare);
							}
							system.debug('SP==='+oppsharlist);  
						}
						
					  }
				   }
                }    
                
		    }	
			List<OpportunityShare> DeshList = new List<OpportunityShare>();
            for ( Opportunityshare ops : osList) {
                if (allmap.containsKey(ops.OpportunityId)&& allmap.get(ops.OpportunityId).contains(ops.UserOrGroupId)) {
                    DeshList.add(ops);
                }
            } 
			//询价共享先注释
			// try{		
			// 	if (DeshList.size() > 0) delete DeshList;	
			// 	system.debug('插入的共享==='+oppsharlist.size()+'=========='+oppsharlist);
			// 	if(null!=oppsharlist && oppsharlist.size()>0){
			// 		//insert oppsharlist;
			// 		insert oppsharlist.values();
			// 	}
			// }catch(Exception e){
			// 		errStr = e.getMessage()+'\n';
			// 		errStr += '询价插入的共享==='+oppsharlist.size()+oppsharlist+'\n';
			// 		errStr += '需要删除的共享==='+DeshList.size()+'\n'+DeshList+'\n';
			// 		errStr += e.getLineNumber()+'\n';
			// }	
		}
		system.debug('省份信息'+mpset);	

	}

	global void finish(Database.BatchableContext BC) {
		String tmp = '';
        if (String.isNotBlank(errStr)) {
            tmp = errStr;
        }
        iflog.Log__c += 'OCMManagementProvinceBatch finish()\n';
        iflog.Log__c += '\n OCMManagementProvinceBatch end';

        tmp += iflog.ErrorLog__c;
        if (tmp.length() > 60000) {
          tmp = tmp.substring(0, 60000);
          tmp += ' ...have more lines...';
          iflog.ErrorLog__c = tmp;
        }
        String tmp2 = iflog.Log__c;
        if (tmp2.length() > 60000) {
          tmp2 = tmp2.substring(0, 60000);
          tmp2 += ' ...have more lines...';
          iflog.Log__c = tmp2;
        }
        
        update iflog;
		if(null!=mpMap && System.Label.OCMManagementProvinceBatchFlag == '1'){  
		  Database.executeBatch(new OCMTOTMSShareUserBatch(mpMap),200);
		}
	}
	
	
		

}