global class ConsumablesApplyOrLendBatch implements Database.Batchable<sObject> {
    private String query;
    private String strategicDept;
    private BatchIF_Log__c iflog;
    private String errStr;

    global ConsumablesApplyOrLendBatch() {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'ConsumablesApplyOrLendBatch start1\n';
        iflog.ErrorLog__c = '';
        insert iflog;
    }

    //2021-1-4 update by rentx SFDC-BWQ3MX start 
    // global ConsumablesApplyOrLendBatch(String dePartment) {
    global ConsumablesApplyOrLendBatch(String strategicDept) {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'ConsumablesApplyOrLendBatch start2\n';
        iflog.ErrorLog__c = '';
        insert iflog;
        // this.strategicDept = dePartment;
        this.strategicDept = strategicDept;
    }
    //2021-1-4 update by rentx SFDC-BWQ3MX end

    //add by rentx 2020-12-03 start 新建共享数据
    private Rental_Apply__Share makeData(String parentId,String userId){
        Rental_Apply__Share ras = new Rental_Apply__Share();
        ras.RowCause= 'Manual';
        ras.ParentId = parentId;
        ras.UserOrGroupId = userId;
        ras.AccessLevel = 'Edit';
        return ras;
    }
    //add by rentx 2020-12-03 end 新建共享数据

    //add  wangweipeng   新增备品的产品担当人共享     2021/10/15   start
    //产品担当人共享原因的对象
    private Rental_Apply__Share makeData3(String parentId,String userId){
        Rental_Apply__Share ras = new Rental_Apply__Share();
        ras.RowCause= 'RentalApplyProducLeaderShare__c';//手动
        ras.ParentId = parentId;//opd id
        ras.UserOrGroupId = userId;//共享给谁
        ras.AccessLevel = 'Read';//只读
        return ras;
    }
    //add  wangweipeng   新增备品的产品担当人共享     2021/10/15   end

    global Database.QueryLocator start(Database.BatchableContext bc) {

        if (strategicDept == null || strategicDept == '') {
            //update by rentx 2020-11-16 SFDC-BVA5VJ start
            // query = 'SELECT id,OwnerId,Approver_of_Service_Department__c,Strategic_user__c,Strategic_dept__c,ShareStrategicUser__c FROM Rental_Apply__c WHERE ShareFlag__c =true  ORDER BY Strategic_dept__c';
            //update  wangweipeng   新增备品的产品担当人共享     2021/10/15      start
            query = 'SELECT id,OwnerId,Approver_of_Service_Department__c,Strategic_user__c,Strategic_dept__c,ShareStrategicUser__c, ';
            query += 'OCM_dept_category__c,ShareFlag__c,Job_Category__c,Strategic_userFSEGI__c,hospitalLeaderGI__c,Strategic_userFSESP__c,hospitalLeaderSP__c, ';
            query += 'hospitalLeaderGIchange__c,hospitalLeaderSPchange__c, OPDPlan__r.Status__c,Shippment_ng_num__c,ProducLeader_Share__c, ';
            query += ' Hospital__r.GI_Product_Leader__c,Hospital__r.BF_Product_Leader__c,Hospital__r.GS_Product_Leader__c,Hospital__r.URO_Produc_Leader__c,Hospital__r.GYN_Product_Leader__c,Hospital__r.ENT_Product_Leader__c,Hospital__r.ET_Product_Leader__c ';
            query += ' FROM Rental_Apply__c WHERE (ShareFlag__c = true or hospitalLeaderGIchange__c = true or hospitalLeaderSPchange__c = true or (Shippment_ng_num__c = 0 and OPDPlan__c != null and OPDPlan__r.Status__c IN (\'完毕未报告\',\'待提交报告\'))) ORDER BY Strategic_dept__c';
        }else{
            // query = 'SELECT id,OwnerId,Approver_of_Service_Department__c,Strategic_user__c,Strategic_dept__c,ShareStrategicUser__c FROM Rental_Apply__c WHERE ShareFlag__c =true AND Strategic_dept__c= \''+strategicDept+'\' ORDER BY Strategic_dept__c';
            query = 'SELECT id,OwnerId,Approver_of_Service_Department__c,Strategic_user__c,Strategic_dept__c,ShareStrategicUser__c, ';
            query += 'OCM_dept_category__c,ShareFlag__c,Job_Category__c,Strategic_userFSEGI__c,hospitalLeaderGI__c,Strategic_userFSESP__c,hospitalLeaderSP__c, ';
            query += 'hospitalLeaderGIchange__c,hospitalLeaderSPchange__c, OPDPlan__r.Status__c,Shippment_ng_num__c,ProducLeader_Share__c, ';
            query += ' Hospital__r.GI_Product_Leader__c,Hospital__r.BF_Product_Leader__c,Hospital__r.GS_Product_Leader__c,Hospital__r.URO_Produc_Leader__c,Hospital__r.GYN_Product_Leader__c,Hospital__r.ENT_Product_Leader__c,Hospital__r.ET_Product_Leader__c ';
            query += ' FROM Rental_Apply__c WHERE (ShareFlag__c = true or hospitalLeaderGIchange__c = true or hospitalLeaderSPchange__c = true or (Shippment_ng_num__c = 0 and OPDPlan__c != null and OPDPlan__r.Status__c IN (\'完毕未报告\',\'待提交报告\'))) AND Strategic_dept__c= \''+strategicDept+'\' ORDER BY Strategic_dept__c';
        }
        //update  wangweipeng   新增备品的产品担当人共享     2021/10/15      end
        //update by rentx 2020-11-16 SFDC-BVA5VJ end
        iflog.Log__c += query+'\n';
        update iflog;
        return Database.getQueryLocator(query);
    }
    //注释 by rentx 2021-01-04 SFDC-BWQ3MX
    /*global void execute(Database.BatchableContext BC, list<Sobject> scope) {

        //add by rentx 2020-11-17 start
        List<Rental_Apply__c> ratList = new List<Rental_Apply__c>();
        List<Rental_Apply__c> raoList = new List<Rental_Apply__c>();
        //add by rentx 2020-11-17 end


        //共享权限变更
        List<Rental_Apply__c> RentalApply = new List<Rental_Apply__c>();
        List<Rental_Apply__c> raList = new List<Rental_Apply__c>();
        List<Rental_Apply__Share> delStrategList = new List<Rental_Apply__Share>();
        List<Rental_Apply__Share> addStrategList = new List<Rental_Apply__Share>();
        List<String> ParentIdList = new List<String>();
        List<String> UserOrGroupIdList = new List<String>();
        Map<String, String> PUMap = new Map<String, String>();

        List<String> UserIDList = new List<String>();
        List<String> IsActiveNoList = new List<String>();
        RentalApply = scope;
        if(RentalApply.size()>0){
            //用户未启用无法插入到共享表 start
            for(Rental_Apply__c ra:RentalApply){
                if(ra.Strategic_user__c !=null){
                    UserIDList.add(ra.Strategic_user__c); 
                }
                //add by rentx 2020-11-27
                if (ra.Strategic_userFSEGI__c != null) {
                    UserIDList.add(ra.Strategic_userFSEGI__c);
                }
                if (ra.Strategic_userFSESP__c != null) {
                    UserIDList.add(ra.Strategic_userFSESP__c);
                    
                }
                //add by rentx 2020-11-27

            }
            for(User user:[Select Id,Name,IsActive From User WHERE Id in:UserIDList]){
                //未启用
                if(!user.IsActive){
                    String  userId = (String)user.Id;
                    userId = userId.substring(0,15);
                    IsActiveNoList.add(userId);
                }
            }
            //用户未启用无法插入到共享表  end
            for(Rental_Apply__c ra:RentalApply){
                //删除原来的共享 
                if(String.isNotBlank(ra.ShareStrategicUser__c)){
                    PUMap.put(ra.Id,ra.ShareStrategicUser__c);
                    ParentIdList.add(ra.Id);
                    UserOrGroupIdList.add(ra.ShareStrategicUser__c); 
                }
                //增加新的
                //所有者还有服务服务部审批人相同不用加 用户未启用无法插入到共享表
                if(ra.Strategic_user__c !=null&& !IsActiveNoList.contains(ra.Strategic_user__c)){
                    if(
                        ((ra.Approver_of_Service_Department__c !=null&&!ra.Strategic_user__c.equals(ra.Approver_of_Service_Department__c))||ra.Approver_of_Service_Department__c ==null)
                        &&!ra.Strategic_user__c.equals(ra.OwnerId)){
                        Rental_Apply__Share ras = new Rental_Apply__Share(
                                RowCause = 'Manual',
                                ParentId = ra.Id,
                                UserOrGroupId = ra.Strategic_user__c,
                                AccessLevel = 'read'
                            );

                        addStrategList.add(ras);
                    }
                    Rental_Apply__c r_a = new Rental_Apply__c();
                    r_a.Id = ra.Id;
                    r_a.ShareStrategicUser__c = ra.Strategic_user__c;
                    raList.add(r_a);   
                }

                //add by rentx 2020-11-16 SFDC-BVA5VJ start 
                //判断战略科室  直接删了再加
                String dept = ra.OCM_dept_category__c;
                if ((ra.Job_Category__c =='销售服务') && (dept.equals('消化科') ||dept.equals('呼吸科') || dept.equals('ET') || dept.equals('其他'))
                     && ra.Strategic_userFSEGI__c != null && !IsActiveNoList.contains(ra.Strategic_userFSEGI__c) && !ra.OwnerId.equals(ra.Strategic_userFSEGI__c)) {
                    //加入共享
                    Rental_Apply__Share ras = makeData(ra.Id,ra.Strategic_userFSEGI__c);
                    addStrategList.add(ras);
                    //删除原来的共享
                    PUMap.put(ra.Id,ra.hospitalLeaderGI__c);
                    ParentIdList.add(ra.Id);
                    UserOrGroupIdList.add(ra.hospitalLeaderGI__c); 
                    if (String.isNotBlank(ra.hospitalLeaderSP__c)) {
                        PUMap.put(ra.Id,ra.hospitalLeaderSP__c);
                        UserOrGroupIdList.add(ra.hospitalLeaderSP__c);        
                    }
                    //更新字段
                    Rental_Apply__c rac = new Rental_Apply__c();
                    rac.Id = ra.Id;
                    rac.hospitalLeaderGI__c = ra.Strategic_userFSEGI__c;
                    ratList.add(rac);

                }
                if ((ra.Job_Category__c =='销售服务') && 
                    (dept.equals('普外科') ||dept.equals('泌尿科') || dept.equals('妇科') || dept.equals('耳鼻喉科') || dept.equals('其他'))
                     && ra.Strategic_userFSESP__c != null && !IsActiveNoList.contains(ra.Strategic_userFSESP__c) && !ra.OwnerId.equals(ra.Strategic_userFSESP__c)) {
                    //加入共享
                    Rental_Apply__Share ras = makeData(ra.Id,ra.Strategic_userFSESP__c);
                    addStrategList.add(ras);
                    //删除原来的共享
                    PUMap.put(ra.Id,ra.hospitalLeaderSP__c);
                    ParentIdList.add(ra.Id);
                    UserOrGroupIdList.add(ra.hospitalLeaderSP__c); 
                    if (String.isNotBlank(ra.hospitalLeaderGI__c)) {
                        PUMap.put(ra.Id,ra.hospitalLeaderGI__c);
                        UserOrGroupIdList.add(ra.hospitalLeaderGI__c); 
                    }
                    //更新字段
                    Rental_Apply__c rac = new Rental_Apply__c();
                    rac.Id = ra.Id;
                    rac.hospitalLeaderSP__c = ra.Strategic_userFSESP__c;
                    raoList.add(rac);

                }


            }
            //删除原来的共享
            delStrategList  = [SELECT Id,ParentId,UserOrGroupId FROM Rental_Apply__Share WHERE  RowCause ='Manual' AND ParentId in :ParentIdList AND UserOrGroupId in :UserOrGroupIdList];
            for(Integer m=0; m<delStrategList.size(); m++){
                if(String.isBlank(PUMap.get(delStrategList[m].ParentId))){
                    delStrategList.remove(m);
                }
            }           
            if(delStrategList.size()>0){
                delete delStrategList;
            }
            //增加
            if (addStrategList.size() > 0) {
                insert addStrategList;
            }
            //更新备品借出
            if(raList.size()>0){
                update raList;
            }

            //更新备品借出 -- hospleaderGI字段
            if (ratList.size() > 0) {
                update ratList;
            }
            //更新备品借出 -- hospleaderSP字段
            if (raoList.size() > 0) {
                update raoList;
            }
        }  
    }*/
    //update by rentx 2021-01-04 SFDC-BWQ3MX
    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
        //原来的是将战略科室所有人加入到共享表中  现在需要将GI/SP主担当也加入并且删除之前的共享
        //add by rentx 2020-11-17 start
        List<Rental_Apply__c> ratList = new List<Rental_Apply__c>();
        List<Rental_Apply__c> raoList = new List<Rental_Apply__c>();
        //add by rentx 2020-11-17 end

        //共享权限变更
        List<Rental_Apply__c> RentalApply = new List<Rental_Apply__c>();
        List<Rental_Apply__c> raList = new List<Rental_Apply__c>();
        List<Rental_Apply__Share> delStrategList = new List<Rental_Apply__Share>();
        List<Rental_Apply__Share> addStrategList = new List<Rental_Apply__Share>();
        List<String> ParentIdList = new List<String>();
        List<String> UserOrGroupIdList = new List<String>();
        Map<String, String> PUMap = new Map<String, String>();

        List<String> UserIDList = new List<String>();
        List<String> IsActiveNoList = new List<String>();

        //add  wangweipeng   新增备品的产品担当人共享     2021/10/15      start
        //收集产品担当人中文名
        List<String> productLeaderNameList = new List<String>();
        //收集所有的数据，注意:最新的共享情况,包括当前类所处理的备品数据
        //使用map，方便后期处理数据
        Map<String,Rental_Apply__c> RentalApplyMapData = new Map<String,Rental_Apply__c>();
        //删除掉备品的产品担当人共享人
        List<String> delRentalApplyShare = new List<String>();
        //新增借出备品申请产品担当共享人
        List<Rental_Apply__Share> insRentalApplyShare = new List<Rental_Apply__Share>();
        //修改借出备品申请的产品担当人共享记录
        List<Rental_Apply__c> updateRac = new List<Rental_Apply__c>();
        //获取所有满足条件的备品id
        List<String> raIdList = new List<String>();
        //获取备品的产品担当人共享数据
        Map<String,List<Rental_Apply__Share>> raShareMap = new Map<String,List<Rental_Apply__Share>>();
        //add  wangweipeng   新增备品的产品担当人共享     2021/10/15      end


        RentalApply = scope;
        if(RentalApply.size()>0){
            //用户未启用无法插入到共享表 start
            for(Rental_Apply__c ra:RentalApply){
                if(ra.Strategic_user__c !=null){
                    UserIDList.add(ra.Strategic_user__c); 
                }
                //add by rentx 判断用户是否启用
                if (ra.Strategic_userFSEGI__c != null) {
                    UserIDList.add(ra.Strategic_userFSEGI__c);
                }
                if (ra.Strategic_userFSESP__c != null) {
                    UserIDList.add(ra.Strategic_userFSESP__c);
                }
                //add by rentx 
                //add  wangweipeng   新增备品的产品担当人共享     2021/10/15      start
                //收集产品担当人   只收集 opd计划为完毕未报告   备品 出库未完了数  等于0（已出库）
                //收集的产品担当人为中文名
                if(('完毕未报告'.equals(ra.OPDPlan__r.Status__c) || '待提交报告'.equals(ra.OPDPlan__r.Status__c)) && ra.Shippment_ng_num__c == 0){
                    List<String> getProductLeaderNameList = getProductLeaderName(ra);
                    if(getProductLeaderNameList != null && getProductLeaderNameList.size() > 0){
                        for(String productLeaderName : getProductLeaderNameList){
                            if(productLeaderName != ''){
                                productLeaderNameList.add(productLeaderName);
                            }
                        }
                        RentalApplyMapData.put(ra.id,ra);
                        raIdList.add(ra.id);
                    }
                }
                //add  wangweipeng   新增备品的产品担当人共享     2021/10/15      end
            }
            for(User user:[Select Id,Name,IsActive From User WHERE Id in:UserIDList]){
                //未启用
                if(!user.IsActive){
                    String  userId = (String)user.Id;
                    userId = userId.substring(0,15);
                    IsActiveNoList.add(userId);
                }
            }

            //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      start
            //由于产品担当获取的都是中文名字，所以需要获取到他的id，并且去掉没启用的人员
            List<User> userList;
            if(productLeaderNameList.size() > 0){
                for(String ss : productLeaderNameList){
                    // System.debug('---------------'+ss);
                }
                //获取担当人的user对象
                userList = [select id,name,Alias,Alias__c from user where IsActive = true and Alias__c != null and Alias__c = :productLeaderNameList order by CreatedDate desc];
            }else{
                userList = new List<User>();
            }
            if(raIdList.size() > 0){
                List<Rental_Apply__Share> raShareList = [SELECT Id, ParentId, UserOrGroupId, AccessLevel, RowCause, LastModifiedDate, LastModifiedById, IsDeleted FROM Rental_Apply__Share where RowCause not in ('RentalApplyProducLeaderShare__c','Manual','Owner','Rule') and ParentId in :raIdList];
                //处理数据，方便后期获取数据，不用一直循环查询数据
                if(raShareList != null && raShareList.size() > 0){
                    for(Rental_Apply__Share ras : raShareList){
                        List<Rental_Apply__Share> oneRas;
                        if(raShareMap.containsKey(ras.ParentId)){
                            oneRas = raShareMap.get(ras.ParentId);
                        }else{
                            oneRas = new List<Rental_Apply__Share>();
                        }
                        oneRas.add(ras);                        
                        raShareMap.put(ras.ParentId,oneRas);
                    }
                }
            }
            //add  wangweipeng   新增备品的产品担当人共享     2021/10/15      end
            
            //用户未启用无法插入到共享表  end
            for(Rental_Apply__c ra:RentalApply){
                //如果战略科室主担当发生变更 --之前的逻辑 update by rentx 2021-01-04 SFDC-BWQ3MX  
                if (ra.ShareFlag__c == true) {
                    //删除原来的共享 
                    if(String.isNotBlank(ra.ShareStrategicUser__c)){
                        PUMap.put(ra.Id,ra.ShareStrategicUser__c);
                        ParentIdList.add(ra.Id);
                        UserOrGroupIdList.add(ra.ShareStrategicUser__c); 
                    }
                    //增加新的
                    //所有者还有服务服务部审批人相同不用加 用户未启用无法插入到共享表
                    if(ra.Strategic_user__c !=null&& (IsActiveNoList.size() ==0 || !IsActiveNoList.contains(ra.Strategic_user__c))){
                        if(
                            ((ra.Approver_of_Service_Department__c !=null&&!ra.Strategic_user__c.equals(ra.Approver_of_Service_Department__c))||ra.Approver_of_Service_Department__c ==null)
                            &&!ra.Strategic_user__c.equals(ra.OwnerId)){
                            Rental_Apply__Share ras = new Rental_Apply__Share(
                                    RowCause = 'Manual',
                                    ParentId = ra.Id,
                                    UserOrGroupId = ra.Strategic_user__c,
                                    AccessLevel = 'read'
                                );

                            addStrategList.add(ras);
                        }
                        Rental_Apply__c r_a = new Rental_Apply__c();
                        r_a.Id = ra.Id;
                        r_a.ShareStrategicUser__c = ra.Strategic_user__c;
                        raList.add(r_a);   

                        //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      start
                        //权限表中的战略科室主担当 字段发生变化，那么记录一下当前修改的内容
                        if(RentalApplyMapData.containsKey(ra.Id)){
                            Rental_Apply__c raa = RentalApplyMapData.get(ra.Id);
                            raa.ShareStrategicUser__c = ra.Strategic_user__c;
                            RentalApplyMapData.put(raa.id,raa);
                        }
                        //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      end
                    }
                }
                //update by rentx 2021-01-04 SFDC-BWQ3MX  
                //如果战略科室GI担当发生变更
                if (ra.hospitalLeaderGIchange__c == true) {
                    //删除原来的共享 
                    if(String.isNotBlank(ra.hospitalLeaderGI__c)){
                        PUMap.put(ra.Id,ra.hospitalLeaderGI__c);
                        ParentIdList.add(ra.Id);
                        UserOrGroupIdList.add(ra.hospitalLeaderGI__c); 
                    }
                    //判断
                    String dept = ra.OCM_dept_category__c;
                    if (ra.Strategic_userFSEGI__c != null && (IsActiveNoList.size() ==0 || !IsActiveNoList.contains(ra.Strategic_userFSEGI__c)) && !ra.OwnerId.equals(ra.Strategic_userFSEGI__c)) {
                        //加入共享
                        Rental_Apply__Share ras = makeData(ra.Id,ra.Strategic_userFSEGI__c);
                        addStrategList.add(ras);
                    }
                    //更新字段
                    Rental_Apply__c rac = new Rental_Apply__c();
                    rac.Id = ra.Id;
                    rac.hospitalLeaderGI__c = ra.Strategic_userFSEGI__c;
                    ratList.add(rac);

                    //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      start
                    //战略科室FSEGI担当 发生变化，记录一下备品修改的内容
                    if(RentalApplyMapData.containsKey(ra.Id)){
                        Rental_Apply__c raa = RentalApplyMapData.get(ra.Id);
                        raa.hospitalLeaderGI__c = ra.Strategic_userFSEGI__c;
                        RentalApplyMapData.put(raa.id,raa);
                    }
                    //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      end
                }
                //update by rentx 2021-01-04 SFDC-BWQ3MX 
                //如果战略科室SP担当发生变更
                if (ra.hospitalLeaderSPchange__c == true) {
                    //删除原来的共享 
                    if(String.isNotBlank(ra.hospitalLeaderSP__c)){
                        PUMap.put(ra.Id,ra.hospitalLeaderSP__c);
                        ParentIdList.add(ra.Id);
                        UserOrGroupIdList.add(ra.hospitalLeaderSP__c); 
                    }
                    //判断
                    if (ra.Strategic_userFSESP__c != null && (IsActiveNoList.size() ==0 || !IsActiveNoList.contains(ra.Strategic_userFSESP__c)) && !ra.OwnerId.equals(ra.Strategic_userFSESP__c)) {
                        //加入共享
                        Rental_Apply__Share ras = makeData(ra.Id,ra.Strategic_userFSESP__c);
                        addStrategList.add(ras);
                    }
                    //更新字段
                    Rental_Apply__c rac = new Rental_Apply__c();
                    rac.Id = ra.Id;
                    rac.hospitalLeaderSP__c = ra.Strategic_userFSESP__c;
                    raoList.add(rac);

                    //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      start
                    //战略科室FSESP担当 发生变化，记录一下修改内容
                    if(RentalApplyMapData.containsKey(ra.Id)){
                        Rental_Apply__c raa = RentalApplyMapData.get(ra.Id);
                        raa.hospitalLeaderSP__c = ra.Strategic_userFSESP__c;
                        RentalApplyMapData.put(raa.id,raa);
                    }
                    //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      end
                }

                //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      start
                if(('完毕未报告'.equals(ra.OPDPlan__r.Status__c) || '待提交报告'.equals(ra.OPDPlan__r.Status__c)) && ra.Shippment_ng_num__c == 0){
                    //当前备品的产品担当中文名，可能是多个或一个
                    List<String> getProductLeaderNameList = getProductLeaderName(ra);
                    //判断当前备品是否有产品担当人
                    if(getProductLeaderNameList != null && getProductLeaderNameList.size() > 0){
                        String productLeaderUserIdStr = '';
                        //获取最新的备品信息，用于判断当前的产品担当人是否已经有权限查看这条备品信息
                        Rental_Apply__c newRA = RentalApplyMapData.get(ra.Id);
                        //判断当前产品担当人是否已经在共享表里面存在（去除产品担当人共享、手动共享的人、规则和所有人）
                        //去掉手动共享原因：因为此类中会重新更新共享人，并且以上代码已经对新的共享人做了逻辑判断，不需要重新循环判断
                        boolean shareFalg = raShareMap.containsKey(newRA.Id);
                        //循环当前产品担当人，判断他是否需要新添加共享
                        for(String productLeaderName : getProductLeaderNameList){
                            if(userList != null && userList.size() > 0){
                                //循环已经查找到的的用户信息
                                for(User u : userList){
                                    //判断循环的人和当前备品的产品担当人是否中文名相同
                                    //可能出现同名民，如果出现那么这几个同名民的都加到这个备品中
                                    if(u.Alias__c == productLeaderName){
                                        String userId = u.Id;
                                        userId = userId.substring(0,15);
                                        //由于可能出现产品担当人和战略科室所有人、战略科室FSEGI担当人、战略科室FSESP担当人、服务部审批人相同，所以需要判断，如果相同，那么不用加
                                        //备品所有人还有服务部审批人相同不用加
                                        String ownerIdStr = newRA.OwnerId;
                                        ownerIdStr = ownerIdStr.substring(0,15);
                                        if(ownerIdStr.equals(userId)){
                                            //由于系统可能出现同名民的人，所以我们只是跳出本次循环
                                            continue;
                                        }else if(String.isNotBlank(newRA.Approver_of_Service_Department__c)){
                                            String approver_of_Service_Department = newRA.Approver_of_Service_Department__c;
                                            approver_of_Service_Department = approver_of_Service_Department.substring(0,15);
                                            if(userId == approver_of_Service_Department){
                                                continue;
                                            }
                                        }
                                        //战略科室客户所人
                                        if(String.isNotBlank(newRA.ShareStrategicUser__c)){
                                            if(userId == (newRA.ShareStrategicUser__c.substring(0,15))){
                                                //由于系统可能出现同名民的人，所以我们只是跳出本次循环
                                                continue;
                                            }
                                        }
                                        //战略科室FSEGI担当
                                        if(String.isNotBlank(newRA.hospitalLeaderGI__c)){
                                            if(userId == (newRA.hospitalLeaderGI__c.substring(0,15))){
                                                //由于系统可能出现同名民的人，所以我们只是跳出本次循环
                                                continue;
                                            }
                                        }
                                        //战略科室FSESP担当
                                        if(String.isNotBlank(newRA.hospitalLeaderSP__c)){
                                            if(userId == (newRA.hospitalLeaderSP__c.substring(0,15))){
                                                //由于系统可能出现同名民的人，所以我们只是跳出本次循环
                                                continue;
                                            }
                                        }

                                        //判断当前产品担当人是否已经在共享表里面存在（去除产品担当人共享和手动共享的人）
                                        //去掉手动共享原因：因为此类中会重新更新共享人，并且以上代码已经对新的共享人做了逻辑判断，不需要重新循环判断
                                        if(shareFalg){
                                            List<Rental_Apply__Share> rasList = raShareMap.get(newRA.Id);
                                            if(rasList != null && rasList.size() > 0){
                                                //为了更方便的跳出循环，如果在共享表里面找到当前人，证明此人已经共享不需要重新添加共享，那么就需要跳出这次循环
                                                boolean flag = false;
                                                for(Rental_Apply__Share rasO : rasList){
                                                    String rasOId1 = rasO.UserOrGroupId;
                                                    rasOId1 = rasOId1.substring(0,15);
                                                    String userId1 = u.id;
                                                    userId1 = userId1.substring(0,15);
                                                    if(rasOId1 == userId1){
                                                        flag = true;
                                                        break;
                                                    }
                                                }
                                                if(flag){
                                                    continue;
                                                }
                                            }
                                        }
                                        
                                        //如果以上条件都没满足，那么需要把这些人员信息收集，用于后期处理
                                        productLeaderUserIdStr += ','+userId;
                                    }
                                }
                            }
                        }

                        //判断 ProducLeader_Share__c 是否为空
                        if(String.isNotBlank(newRA.ProducLeader_Share__c)){
                            //当前备品是否有需要共享的担当人不
                            if(String.isNotBlank(productLeaderUserIdStr)){
                                productLeaderUserIdStr = productLeaderUserIdStr.substring(1,productLeaderUserIdStr.length());
                                //如果相同，那么什么也不做
                                if(!newRA.ProducLeader_Share__c.equals(productLeaderUserIdStr)){
                                    //备品表记录担当人共享的字段不为空，现在也有需要共享的担当人，并且原来备品记录的担当人和当前需要共享的担当人不是一个人，那么需要删除原来的担当人共享，重新添加共享，并且把备品记录担当人共享的字段重新更新一下
                                    delRentalApplyShare.add(newRA.id);//删除全部的产品担当共享，重新添加共享
                                    List<String> userListId = productLeaderUserIdStr.split(',');
                                    if(userListId.size() > 0){
                                        for(String userId : userListId){
                                            if(userId != ''){
                                                //重新添加共享
                                                insRentalApplyShare.add(makeData3(newRA.id,userId));
                                            }
                                        }
                                        //修改备品的产品担当人字段值
                                        updateRac.add(new Rental_Apply__c(id=newRA.id,ProducLeader_Share__c=productLeaderUserIdStr));
                                    }
                                }
                            }else{
                                //如果 ProducLeader_Share__c 字段不为空，并且没有找到当前备品需要共享的产品担当人
                                //证明以前共享了产品担当人，但是现在产品担当人做了修改（系统中没找到或此人已经通过其它共享原因共享了）或制空了，所以直接把以前共享的人删除掉就行
                                delRentalApplyShare.add(newRA.id);
                                //修改备品的产品担当人字段值
                                updateRac.add(new Rental_Apply__c(id=newRA.id,ProducLeader_Share__c=''));
                            }
                        }else{
                            //如果ProducLeader_Share__c字段为空，并且当前备品的产品担当人需要共享，那么就需要我们新增共享，并把共享人id，记录到当前备品上
                            if(String.isNotBlank(productLeaderUserIdStr)){
                                productLeaderUserIdStr = productLeaderUserIdStr.substring(1,productLeaderUserIdStr.length());
                                List<String> userListId = productLeaderUserIdStr.split(',');
                                if(userListId.size() > 0){
                                    for(String userId : userListId){
                                        if(userId != ''){
                                            //重新添加共享
                                            insRentalApplyShare.add(makeData3(newRA.id,userId));
                                        }
                                    }
                                    //修改备品的产品担当人字段值
                                    updateRac.add(new Rental_Apply__c(id=newRA.id,ProducLeader_Share__c=productLeaderUserIdStr));
                                }
                            }
                        }
                    }else{
                        //如果没有产品当但人，但是字段不为空，那么证明，当前备品的产品担当人有变动值设置为空了，那么我们需要处理以前已经共享的产品担当人
                        if(String.isNotBlank(ra.ProducLeader_Share__c)){
                            delRentalApplyShare.add(ra.id);
                            //修改备品的产品担当人字段值
                            updateRac.add(new Rental_Apply__c(id=ra.id,ProducLeader_Share__c=''));
                        }
                    }
                }
                //add   wangweipeng   新增备品的产品担当人共享     2021/10/15      end
            }
            //删除原来的共享
            delStrategList  = [SELECT Id,ParentId,UserOrGroupId FROM Rental_Apply__Share WHERE  RowCause ='Manual' AND ParentId in :ParentIdList AND UserOrGroupId in :UserOrGroupIdList];
            for(Integer m=0; m<delStrategList.size(); m++){
                if(String.isBlank(PUMap.get(delStrategList[m].ParentId))){
                    delStrategList.remove(m);
                }
            }
            Savepoint sp = Database.setSavepoint();
            try{
                if(delStrategList.size()>0){
                    delete delStrategList;
                }
                //增加
                if (addStrategList.size() > 0) {
                    insert addStrategList;
                }
                //更新备品借出
                if(raList.size()>0){
                    update raList;
                }
                //更新备品借出GI
                if (ratList.size() > 0) {
                    update ratList;
                }
                //更新备品借出SP
                if (raoList.size() > 0) {
                    update raoList;
                }
                //add by rentx 2021-01-04 SFDC-BWQ3MX start
                
                //add   wangweipeng   新增备品的产品担当人共享     2021/10/18      start
                //以下是备品借出申请的产品担当人共享
                //删除原来的产品担当共享人
                if(delRentalApplyShare != null && delRentalApplyShare.size() > 0){
                    List<Rental_Apply__Share> delentalApplyShareList = [SELECT Id,ParentId,UserOrGroupId FROM Rental_Apply__Share WHERE RowCause ='RentalApplyProducLeaderShare__c' AND ParentId in :delRentalApplyShare];
                    if(delentalApplyShareList != null && delentalApplyShareList.size() > 0){
                        delete delentalApplyShareList;
                    }
                }
                //新增产品担当共享人
                if(insRentalApplyShare != null && insRentalApplyShare.size() > 0){
                    insert insRentalApplyShare;
                }
                //修改产品担当共享人
                if(updateRac != null && updateRac.size() > 0){
                    update updateRac;
                }
                //add   wangweipeng   新增备品的产品担当人共享     2021/10/18      end
                
            }catch(Exception e){
                errStr = e.getMessage()+'\n';
                errStr += e.getLineNumber()+'\n';
                Database.rollback(sp);
            }
                //add by rentx 2021-01-04 SFDC-BWQ3MX end
        }  
    }

    //add  wangweipeng   新增备品的产品担当人共享     2021/10/15   start
    //获取对应的产品担当人中文名
    public List<String> getProductLeaderName(Rental_Apply__c rentalApplyOneData){
        List<String> productLeaderNameList = new List<String>();//产品担当中文名
        if(rentalApplyOneData != null){
            String productLeader = '';
            String departmentType = rentalApplyOneData.OCM_dept_category__c;//战略科室分类
            if(departmentType != ''){
                if('消化科'.equals(departmentType)){productLeader = rentalApplyOneData.Hospital__r.GI_Product_Leader__c;}
                if('呼吸科'.equals(departmentType)){productLeader = rentalApplyOneData.Hospital__r.BF_Product_Leader__c;}
                if('普外科'.equals(departmentType)){productLeader = rentalApplyOneData.Hospital__r.GS_Product_Leader__c;}
                if('泌尿科'.equals(departmentType)){productLeader = rentalApplyOneData.Hospital__r.URO_Produc_Leader__c;}
                if('妇科'.equals(departmentType)){productLeader = rentalApplyOneData.Hospital__r.GYN_Product_Leader__c;}
                if('耳鼻喉科'.equals(departmentType)){productLeader = rentalApplyOneData.Hospital__r.ENT_Product_Leader__c;}
                if('ET'.equals(departmentType)){productLeader = rentalApplyOneData.Hospital__r.ET_Product_Leader__c;}
                //由于担当人可能是多个人所以需要循环一下
                if(productLeader != '' && productLeader != null){
                    if(productLeader.indexOf('，') != -1){
                        productLeader = productLeader.replace('，',',');
                    }
                    if(productLeader.indexOf(' ') != -1){
                        productLeader = productLeader.replace(' ','');
                    }
                    if(productLeader.indexOf(',') != -1){
                        for (String usrName1 : productLeader.split(',')) {
                            if(!(''.equals(usrName1))){
                                productLeaderNameList.add(usrName1);
                            }
                        }
                    }else{
                        productLeaderNameList.add(productLeader);
                    }
                }
            }
        }
        return productLeaderNameList;
    }

    //add  wangweipeng   新增备品的产品担当人共享     2021/10/15   end


    global void finish(Database.BatchableContext BC) {
        String tmp = '';
        if (String.isNotBlank(errStr)) {
            tmp = errStr;
        }
        iflog.Log__c += 'ConsumablesApplyOrLendBatch finish()\n';
        iflog.Log__c += '\nConsumablesApplyOrLendBatch 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;
        }
        if (System.Label.Log_IO_Flag == 'Keep') {
          update iflog;
        } else if (System.Label.Log_IO_Flag == 'Auto') {
          if (iflog.Is_Error__c > 0) {
            update iflog;
          }
        }
        //wangweipeng   20210707   start
        if(strategicDept == null || strategicDept == ''){
            //opd计划模块共享
            //如果战略科室所有人和opd计划所有人不是一个人，那么给这个战略科室所有人加一个共享
            Id execBTId = Database.executeBatch(new OPDStrategyPersonShareBatch(),50);  
        } 
        //wangweipeng   20210707   end  
    }
}