global class OCMTOIMSShareUserBatch  implements Database.Batchable<sObject>{
    String query;
	String targetId;
	private BatchIF_Log__c iflog;
	private String errStr;
    private Map<String, OCM_Management_Province__c> mpMap;
    
	global OCMTOIMSShareUserBatch() {
		iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMTOIMSShareUserBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMTOIMSShareUserBatch start1\n';
        iflog.ErrorLog__c = '';
        insert iflog;
	}
    global OCMTOIMSShareUserBatch(Map<String, OCM_Management_Province__c> mpMap) {
        mpMap = mpMap;
		iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMTOIMSShareUserBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMTOIMSShareUserBatch start2\n';
        iflog.ErrorLog__c = '';
        insert iflog;
	}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        //共享给IMS对象 ET/ENG窗口  根据省（医院）和 产品类型
        query = 'select id,H_OCM_man_province_HP__c,Ownerid,productType__c from ConsumableTargetManage__c ';
        query += ' where productType__c !=null and H_OCM_man_province_HP__c !=null ';
        if (null!=mpMap) {
			query += ' and H_OCM_man_province_HP__c in :mpMap.keySet()';
		}
        return Database.getQueryLocator(query);

    }
    global void execute(Database.BatchableContext BC, List<ConsumableTargetManage__c> imsList) {
        String imsrowCause = Schema.ConsumableTargetManage__Share.RowCause.OCSMToIMSUser__c;
        if(null == mpMap){
            mpMap = new Map<String, OCM_Management_Province__c>();
            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];
            for (OCM_Management_Province__c mp : mpList) {
                mpMap.put(mp.Name, mp);
            }    
        }
        List<ConsumableTargetManage__Share> imssharlist =new List<ConsumableTargetManage__Share>();
        List<Id> deleteimssharlist = new List<Id>();  
        for (ConsumableTargetManage__c nObj : imsList) {
            if (mpMap.containsKey(nObj.H_OCM_man_province_HP__c)) {
                if(null!=nObj.productType__c && ''!= nObj.productType__c && null!=mpMap.get(nObj.H_OCM_man_province_HP__c)){
                    if(nObj.productType__c=='ET耗材'){
                    if(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Flag__c==true){
                            if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);
                        }
                        if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);
                        }
                        if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);
                        }  
                        if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);     
                        }
                        deleteimssharlist.add(nObj.Id);
                    }
                        
                    }else{//ENG 
                    if(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Flag__c==true){
                        if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);
                        }
                        if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);
                        }
                        if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);
                        }
                        if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c){
                            ConsumableTargetManage__Share imsshare = new ConsumableTargetManage__Share(
                            ParentId = nObj.Id,
                            RowCause = imsrowCause,
                            UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c,
                            AccessLevel = 'read');
                            imssharlist.add(imsshare);
                        }
                        deleteimssharlist.add(nObj.Id);
                    }
                    
                    
                    }
                    
                }
                
            }
        }    
        try{
            // 先 Delete 后 Insert
            if (null!=deleteimssharlist && deleteimssharlist.size() > 0) {
                List<ConsumableTargetManage__Share> deleteList = [SELECT Id
                    FROM ConsumableTargetManage__Share
                    WHERE RowCause = :imsrowCause
                    AND ParentId IN :deleteimssharlist
                ];
                if(null!=deleteList && deleteList.size()>0){
                    delete deleteList;
                }
                system.debug('删除得ims共享数据'+deleteList.size());
            }
            system.debug('插入得IMS共享数据'+imssharlist.size());
            if(null!=imssharlist && imssharlist.size()>0){
                insert imssharlist;
            }
        }catch(Exception e){
            errStr += e.getMessage()+'\n';
            errStr += 'IMS插入的共享==='+imssharlist.size()+imssharlist+'\n';
            errStr += 'IMS需要删除的共享==='+deleteimssharlist.size()+'\n'+deleteimssharlist+'\n';
            errStr += e.getLineNumber()+'\n';
        }
    }
    global void finish(Database.BatchableContext BC) {
        String tmp = '';
        if (String.isNotBlank(errStr)) {
            tmp = errStr;
        }
        iflog.Log__c += 'OCMTOIMSShareUserBatch finish()\n';
        iflog.Log__c += '\n OCMTOIMSShareUserBatch 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;
        }
        
        
        List<OCM_Management_Province__c> mpList1 = [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,ET_Flag__c,ENG_Flag__c from OCM_Management_Province__c where ENG_Flag__c=true or ET_Flag__c=true];
		List<OCM_Management_Province__c> updList = new List<OCM_Management_Province__c>();
		for (OCM_Management_Province__c mp : mpList1) {
            iflog.Log2__c ='开始';
            iflog.Log3__c ='开始';
		    if(mp.ET_Flag__c == true){
                iflog.Log2__c += '办事处名称：'+mp.Name+'====='+mp.id;
                iflog.Log2__c += 'ET更新前人员担当'+mp.ETShareOpp__c +'\n';
				mp.ETShareOpp__c=(mp.ET_DataWindow__c == null? '' : String.valueOf(mp.ET_DataWindow__c).substring(0, 15))+','+(mp.ET_BusinessWindow__c == null? '' : String.valueOf(mp.ET_BusinessWindow__c).substring(0, 15))+','+(mp.ET_Assistant1__c == null? '' : String.valueOf(mp.ET_Assistant1__c).substring(0, 15))+','+(mp.ET_Assistant2__c == null? '' : String.valueOf(mp.ET_Assistant2__c).substring(0, 15));
			    iflog.Log2__c += 'ET更新后人员担当'+mp.ETShareOpp__c +'\n';
            } 
			if(mp.ENG_Flag__c == true){
                iflog.Log2__c += '办事处名称：'+mp.Name+'====='+mp.id;
                iflog.Log3__c += 'ENG更新前人员担当'+mp.ENGShareOpp__c +'\n';
				mp.ENGShareOpp__c=(mp.ENG_DataWindow__c == null? '' : String.valueOf(mp.ENG_DataWindow__c).substring(0, 15))+','+(mp.ENG_BusinessWindow__c == null? '' : String.valueOf(mp.ENG_BusinessWindow__c).substring(0, 15))+','+(mp.ENG_Assistant1__c == null? '' : String.valueOf(mp.ENG_Assistant1__c).substring(0, 15))+','+(mp.ENG_Assistant2__c == null? '' : String.valueOf(mp.ENG_Assistant2__c).substring(0, 15));
			    iflog.Log3__c += 'ENG更新前人员担当'+mp.ENGShareOpp__c +'\n';
			}
            if(mp.ET_Flag__c == true || mp.ENG_Flag__c == true){
                updList.add(mp);
            }
			
		}
		if (updList.size() > 0) {
			update updList;
		}

        update iflog;
    }    
}