public without sharing class TransferApplyHandler extends Oly_TriggerHandler {
    private Map<Id, TransferApply__c> newMap;
    private Map<Id, TransferApply__c> oldMap;
    private List<TransferApply__c> newList;
    private List<TransferApply__c> oldList;
    //记录类型 备品中心保有设备Id
    private static final Map<String,Schema.RecordTypeInfo>  DEVELOPERNAMEMAP  = Schema.SObjectType.TransferApply__c.getRecordTypeInfosByDeveloperName();
    private static final Map<String, Schema.FieldSet> FSMAP = Schema.SObjectType.TransferApplyDetail__c.fieldSets.getMap();
    private static final Map<String, Schema.SObjectField> ASSETFSMAP = Schema.SObjectType.Asset.fields.getMap();

    private static Map<String, String> ocm_ManagementMap;
    private static Map<String, String> ocmProvToAgencyMap;

    public TransferApplyHandler() {
        this.newMap = (Map<Id, TransferApply__c>) Trigger.newMap;
        this.oldMap = (Map<Id, TransferApply__c>) Trigger.oldMap;
        this.newList = (List<TransferApply__c>) Trigger.new;
        this.oldList = (List<TransferApply__c>) Trigger.old;
    }
    protected override void beforeInsert() {
        setFromLocation();
        setManager();
        setOffice_Assistant();
    }
    protected override void beforeUpdate() {
        setManager();
        setOffice_Assistant();
    }
    protected override void afterInsert() {
        // 动态更新办事处助理共享
        dynamicUpdateOfficeAssistantShare();
    }
    protected override void afterUpdate() {
        updateRequestTime();
        reApprovalStatus();
        formulaToTextCheck();
        updateAsset();//20201027 ljh OCSM_BP5-26 审批同意后更新保有设备 add

        // 动态更新办事处助理共享
        dynamicUpdateOfficeAssistantShare();
        // 共享给审批人
        dynamicUpdateApprovalShare();
        cancelTa();//20201208 ljh add
    }
    private void setFromLocation() {
        User user1 = [SELECT OCM_man_province_Rental__c
                           , ProfileId
                           , UserRole.DeveloperName
                        FROM User WHERE Id=:UserInfo.getUserId()];
        for(TransferApply__c nObj:newList) {
            if(String.isBlank(nObj.From_Location__c)) {
                if(user1.ProfileId == System.Label.ProfileId_EquipmentCenter) {
                    switch on user1.UserRole.DeveloperName {
                        when 'Loaner_nanfang_staff' {
                            nObj.From_Location__c = '广州 备品中心';
                        }
                        when 'beipin_huadong_staff' {
                            nObj.From_Location__c = '上海 备品中心';
                        }
                        when else {
                            nObj.From_Location__c = '北京 备品中心';
                        }
                    }
                }
                else {
                    if (ocmProvToAgencyMap == null) {
                        ocmProvToAgencyMap = new Map<String, String>();
                        if(ocm_ManagementMap == null) {
                            ocm_ManagementMap = AssetWebService.getOcmMgtProvMap();
                        }
                        // 省->办事处
                        for(String agency: ocm_ManagementMap.keySet()) {
                            ocmProvToAgencyMap.put(ocm_ManagementMap.get(agency),agency);
                        }
                    }
                    if(ocmProvToAgencyMap.containsKey(user1.OCM_man_province_Rental__c)) {
                        nObj.From_Location__c = ocmProvToAgencyMap.get(user1.OCM_man_province_Rental__c);
                    }
                    else {
                        nObj.From_Location__c.addError(user1.OCM_man_province_Rental__c + '没有对应的办事处，请检查！');
                    }
                }
            }
        }
    }

    private void setOffice_Assistant() {

        if (ocm_ManagementMap == null) {
            ocm_ManagementMap = AssetWebService.getOcmMgtProvMap();
        }

        Set<String> locSet = new Set<String>();
        List<TransferApply__c> nObjList = new List<TransferApply__c>();
        Id centerToAgency = DEVELOPERNAMEMAP.get('CenterToAgency').getRecordTypeId();
        Id agencyToCenter = DEVELOPERNAMEMAP.get('AgencyToCenter').getRecordTypeId();
        for (TransferApply__c nObj : newList) {
            Boolean have = false;
            if (System.Trigger.isInsert) {
                if (nObj.RecordTypeId == centerToAgency
                    && String.isNotBlank(nObj.Destination_location__c)
                    && ocm_ManagementMap.containsKey(nObj.Destination_location__c)
                ) {
                    locSet.add(ocm_ManagementMap.get(nObj.Destination_location__c));
                    have = true;
                }
                else if (nObj.RecordTypeId == agencyToCenter
                    && String.isNotBlank(nObj.From_Location__c)
                    && ocm_ManagementMap.containsKey(nObj.From_Location__c)
                ) {
                    locSet.add(ocm_ManagementMap.get(nObj.From_Location__c));
                    have = true;
                }
                if (have) {
                    nObjList.add(nObj);
                }
            }
            else if (System.Trigger.isUpdate) {
                TransferApply__c oObj = oldMap.get(nObj.id);
                if (nObj.RecordTypeId == centerToAgency
                    && oObj.Destination_location__c != nObj.Destination_location__c
                    && String.isNotBlank(nObj.Destination_location__c)
                    && ocm_ManagementMap.containsKey(nObj.Destination_location__c)
                ) {
                    have = true;
                    nObj.After_Office_Assistant1__c = null;
                    nObj.After_Office_Assistant2__c = null;
                    locSet.add(ocm_ManagementMap.get(nObj.Destination_location__c));
                }
                else if (nObj.RecordTypeId == agencyToCenter
                    && oObj.From_Location__c != nObj.From_Location__c
                    && String.isNotBlank(nObj.From_Location__c)
                    && ocm_ManagementMap.containsKey(nObj.From_Location__c)
                ) {
                    have = true;
                    nObj.Before_Office_Assistant1__c = null;
                    nObj.Before_Office_Assistant2__c = null;
                    locSet.add(ocm_ManagementMap.get(nObj.From_Location__c));
                }
                if (have) {
                    nObjList.add(nObj);
                }
            }
        }

        if (locSet.size() > 0) {
            Map<String, OCM_Management_Province__c> ocpMap = new Map<String, OCM_Management_Province__c>();
            for (OCM_Management_Province__c ocp : [SELECT Id
                                                        , Name
                                                        , Agency_assistant1__c
                                                        , Agency_assistant2__c
                                                        , OBA3_Email_Group2__c // 20220520 ljh SWAG-CDTEFS add
                                                     FROM OCM_Management_Province__c
                                                    WHERE Name = :locSet]
            ) {
                ocpMap.put(ocp.Name, ocp);
            }
            for (TransferApply__c nObj : nObjList) {
                String de = ocm_ManagementMap.get(nObj.Destination_location__c);
                String fl = ocm_ManagementMap.get(nObj.From_Location__c);
                if (ocpMap.containsKey(de)) {
                    nObj.After_Office_Assistant1__c = ocpMap.get(de).Agency_assistant1__c;
                    nObj.After_Office_Assistant2__c = ocpMap.get(de).Agency_assistant2__c;
                    nObj.OBA3_Email_Group__c = ocpMap.get(de).OBA3_Email_Group2__c; // 20220520 ljh SWAG-CDTEFS add
                }
                if (ocpMap.containsKey(fl)) {
                    nObj.Before_Office_Assistant1__c = ocpMap.get(fl).Agency_assistant1__c;
                    nObj.Before_Office_Assistant2__c = ocpMap.get(fl).Agency_assistant2__c;
                    nObj.OBA3_Email_Group__c = ocpMap.get(fl).OBA3_Email_Group2__c;// 20220520 ljh SWAG-CDTEFS add
                }
            }
        }
    }

    private void updateRequestTime(){
        Map<Id, TransferApply__c> taIdMap = new Map<Id, TransferApply__c>();
        for (TransferApply__c nObj : newList) {
            TransferApply__c oObj = oldMap.get(nObj.Id);
            if (oObj.Request_time__c != nObj.Request_time__c) {
                taIdMap.put(nObj.Id, nObj);
            }
        }
        if(taIdMap.isEmpty()) {
            return;
        }
        List <TransferApplyDetail__c> tadList = [SELECT Id, TransferApply__c FROM TransferApplyDetail__c WHERE TransferApply__c IN:taIdMap.keySet()];
        for(TransferApplyDetail__c tad:tadList) {
            tad.Request_time__c = taIdMap.get(tad.TransferApply__c).Request_time__c;
        }
        update tadList;
    }

    private void setManager() {
        // 申請中かどうかのチェック
        List<Id> copyUserIds = new List<Id>();                       // 件数は Trigger.New と同じ
        List<TransferApply__c> newList1 = new List<TransferApply__c>(); // 件数は Trigger.New と同じ
        Id agencyToCenter = DEVELOPERNAMEMAP.get('AgencyToCenter').getRecordTypeId();
        for (TransferApply__c nObj : newList) {
            TransferApply__c oObj;
            if (Trigger.isUpdate) {
                oObj = oldMap.get(nObj.Id); 
               
                // 20210429 1831 you start
                if(nObj.Add_Approval_Status__c=='已批准' && oObj.Add_Approval_Status__c != nObj.Add_Approval_Status__c && String.isNotEmpty(nObj.Add_Reason__c)){
                   if(String.isBlank(nObj.Add_Reason_All__c)){
                      nObj.Add_Reason_All__c =nObj.Add_Request_demo_time__c.format()+':'+nObj.Add_Reason__c+';';
                   }else{
                      nObj.Add_Reason_All__c +='\n'+nObj.Add_Request_demo_time__c.format()+':'+nObj.Add_Reason__c+';';
                   }
                   nObj.Add_Reason__c ='';
                }
                // 20210429 1831 you end
            }
            //20201217 ljh add start
            //公式拷贝文本
            nObj.AfterOCMAssetEmail__c = nObj.AfterOCMAssetEmail_F__c;
            nObj.BeforeOCMAssetEmail__c = nObj.BeforeOCMAssetEmail_F__c;
            nObj.AfterCheckEmail__c = nObj.AfterCheckEmail_F__c;
            nObj.BeforeCheckEmail__c = nObj.BeforeCheckEmail_F__c;
            //20201217 ljh add end
            //20201209 ljh add start
            if (Trigger.isUpdate && oObj.Status__c != '取消' && nObj.Status__c == '取消') {
                nObj.Cancel_Time__c = Datetime.now();
            }
            //20201209 ljh add end
            if (nObj.applyUser__c != null) nObj.OwnerId = nObj.applyUser__c;
            System.debug(nObj.applyUser__c);
            System.debug(nObj.OwnerId);
            if (Trigger.isInsert
                        || (Trigger.isUpdate && oObj.Status__c != nObj.Status__c && nObj.Status__c == '填写完毕')
                        || (Trigger.isUpdate && oObj.Add_Approval_Status__c != nObj.Add_Approval_Status__c && nObj.Add_Approval_Status__c == '填写完毕')
                        || (Trigger.isUpdate && oObj.OwnerId != nObj.OwnerId)
                ) {
                    newList1.add(nObj);
                    //20210428 ljh update start
                    //copyUserIds.add(nObj.OwnerId);
                    if(nObj.RecordTypeId == agencyToCenter){
                        copyUserIds.add(nObj.Contact_Person__c);
                    }else{
                        copyUserIds.add(nObj.OwnerId);
                    }
                    //20210428 ljh update end
                }
        }
        System.debug(copyUserIds);
        if (copyUserIds.size() > 0) {
            Map<Id, User> copyUserMap = new Map<Id, User>([
                SELECT Id, Name, Buzhang_Equipment_Manager__c, JingliEquipmentManager__c, SalesManager__c, BuchangApprovalManagerSales__c, JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, TongkuoZongjian__c FROM User WHERE Id IN :copyUserIds
            ]);
            bp3_Setting__c conf = bp3_Setting__c.getOrgDefaults();//20201128 ljh  OCSM_BP5-66 add start
            for (Integer i = 0; i < copyUserIds.size(); i++) {
                TransferApply__c nObj = newList1[i];
                User loginUser = copyUserMap.get(copyUserIds[i]);
                //精琢 wql 测试batch报错 跳过 20210518 start 
                if(loginUser!=null){
                    nObj.SalesManager__c = loginUser.JingliEquipmentManager__c;
                    nObj.JingliApprovalManager__c = loginUser.JingliApprovalManager__c;
                    //nObj.BuchangApprovalManagerSales__c = loginUser.Buzhang_Equipment_Manager__c;
                }
                if(conf!=null){
                    nObj.BuchangApprovalManagerSales__c = conf.YunYingBuZhang__c;
                    
                    //20201128 ljh OCSM_BP5-66 update 审批运营部长 start
                    //nObj.BuchangApprovalManager__c = loginUser.BuchangApprovalManager__c;
                    nObj.BuchangApprovalManager__c = conf.YunYingBuZhang__c;
                    //20201128 ljh OCSM_BP5-66 update 审批运营部长 end
                    //nObj.ZongJian__c = loginUser.ZongjianApprovalManager__c;//20201127 ljh OCSM_BP5-66 add 审批总监赋值
                    nObj.ZongJian__c = conf.BeiPin_ZhongJian__c;
                    nObj.HuaDongAccept__c = conf.HDAccept__c;//20201127 ljh OCSM_BP5-66 add 审批华东受理赋值
                }
                //精琢 wql 测试batch报错 跳过 20210518 end 
                    nObj.BeiPinWindow__c = nObj.beipinWindow_F__c;//20201202 ljh OCSM_BP5-76 备品总窗口
                    //nObj.ZongjianApprovalManager__c = loginUser.ZongjianApprovalManager__c;
                    //nObj.TongkuoZongjian__c = loginUser.TongkuoZongjian__c;
                    System.debug(loginUser);
                
                
                
            }
        }
    }

    // 追加审批相关操作 20210723 ljh add SFDC-C56D3K  此处修改 新加批准时间也复制
    private void reApprovalStatus() {
        Map<Id, TransferApply__c> taIdMap = new Map<Id, TransferApply__c>();
        for (TransferApply__c nObj : newList) {
            TransferApply__c oObj = oldMap.get(nObj.Id);
            // if (oObj.Add_Approval_Status__c != nObj.Add_Approval_Status__c
            //     && nObj.Request_approval_time__c != null
            //     && oObj.Request_approval_time__c == nObj.Request_approval_time__c
            //     && nObj.Add_Approval_Status__c != '填写完毕') {
            //     taIdMap.put(nObj.Id, nObj);
            // }
            if ((oObj.Add_Approval_Status__c != nObj.Add_Approval_Status__c
                && nObj.Request_approval_time__c != null
                && oObj.Request_approval_time__c == nObj.Request_approval_time__c
                && nObj.Add_Approval_Status__c != '填写完毕')
                || (nObj.Request_approval_time__c != null
                && oObj.Request_approval_time__c != nObj.Request_approval_time__c)) {
                taIdMap.put(nObj.Id, nObj);
            }
        }
        if (taIdMap.isEmpty()) {
            return;
        }
        List<TransferApplyDetail__c> tadList = [
            Select Id
                , TransferApply__c
                , Add_Request_demo_time__c
                , Add_Request_approval_time__c
                , Transfer_Apply_Request_approval_time__c //20210723 ljh add SFDC-C56D3K add
                From TransferApplyDetail__c
                Where TransferApply__c = :taIdMap.keySet()
                AND ((ApplyPersonAppended_F__c = true
                AND Add_Request_approval_time__c = null) OR Transfer_Apply_Request_approval_time__c = null)];
                // 20210723 ljh add SFDC-C56D3K 增加 OR Transfer_Apply_Request_approval_time__c = null
        for (TransferApplyDetail__c tad : tadList) {
            TransferApply__c ta = taIdMap.get(tad.TransferApply__c);
            if (ta.Add_Approval_Status__c == '申请中') {
                tad.Add_Request_demo_time__c = ta.Add_Request_demo_time__c;
            } else if (ta.Add_Approval_Status__c == '已批准') {
                tad.Add_Request_approval_time__c = ta.Add_Request_approval_time__c;
                tad.Transfer_Apply_Request_approval_time__c = ta.Add_Request_approval_time__c;//20210723 ljh add SFDC-C56D3K
            } else if (ta.Add_Approval_Status__c == '草案中') {
                tad.Add_Request_demo_time__c = null;
                tad.Add_Request_approval_time__c = null;
                tad.Transfer_Apply_Request_approval_time__c = null;//20210723 ljh add SFDC-C56D3K
            }
            // System.debug('zheli:'+ta.Status__c+'~'+ta.Add_Approval_Status__c+ta.Id);
            //20210723 ljh add SFDC-C56D3K start
            if(ta.Status__c == '已批准' && ta.Add_Approval_Status__c == null){
               tad.Transfer_Apply_Request_approval_time__c = ta.Request_approval_time__c;
            }
            //20210723 ljh add SFDC-C56D3K end
        }
        update tadList;
    }

    private void cancelTa() {
        Set<Id> raIdSet = new Set<Id>();
        for (TransferApply__c nObj : newList) {
            TransferApply__c oObj = oldMap.get(nObj.Id);

            if (oObj.Status__c != '取消' && nObj.Status__c == '取消') {
                raIdSet.add(nObj.Id);
            }
        }
        if (raIdSet.isEmpty()) {
            return;
        }
        List<TransferApplySummary__c> tasList = [Select id,TransferApply__r.Cancel_Reason__c,TAS_Status__c
                FROM TransferApplySummary__c
                WHERE TransferApply__c = :raIdSet
                  AND Cancel_Select__c = false // 已经取消的备品借出一览不再修改取消理由等字段
                ];
        if (tasList.size() > 0) {
            for (TransferApplySummary__c raes : tasList) {
                raes.Cancel_Select__c = true;
                raes.Cancel_Reason__c = raes.TransferApply__r.Cancel_Reason__c;
                //raes.Loaner_cancel_Remarks__c = raes.Rental_Apply__r.Loaner_cancel_request__c;
                raes.Cancel_Mem__c = UserInfo.getUserId();
                //raes.Cancel_Date__c = Date.today();
                raes.Cancel_Time__c = System.now();
            }
            update tasList;
        }
    }
    private void formulaToTextCheck() {
        List<TransferApply__c> ras = new List<TransferApply__c>();
        for (TransferApply__c nObj : newList) {
            if (nObj.TA_Status_Text__c != nObj.TA_Status__c
                || nObj.Status_Text__c != nObj.Status__c
                || nObj.NotWatch_TA_Status__c != nObj.NotWatch_TA_Status_F__c
                //2021027  ljh  add  strat
                || nObj.TA_Status__c != nObj.TransferApply_Status__c) {
                //2021027  ljh  add  end
                TransferApply__c ra = new TransferApply__c(Id = nObj.Id);
                //2021027  ljh  add  strat
                ra.TA_Status_Text__c = nObj.TA_Status__c;
                //2021027  ljh  add  end
                ra.TransferApply_Status__c = nObj.TA_Status__c;
                ra.Status_Text__c = nObj.Status__c;
                ra.NotWatch_TA_Status__c = nObj.NotWatch_TA_Status_F__c;
                ras.add(ra);
            }
        }
        if (!ras.isEmpty()) {
            update ras;
        }
    }
    //20201027 ljh OCSM_BP5-26 审批同意后更新保有设备 add
    private void updateAsset(){
        Set<Id> raIdSet = new Set<Id>();
        for ( TransferApply__c nObj : newList) {
            //记录类型是备品中心保有设备 且是审批同意 更新保有设备
            TransferApply__c oObj = oldMap.get(nObj.Id);
            if ( nObj.RecordTypeId == DEVELOPERNAMEMAP.get('InsideCenter').getRecordTypeId() && nObj.Status__c == '已批准'&& oObj.Status__c != '已批准') {
                raIdSet.add(nObj.Id);
            }
        }
        if (raIdSet.isEmpty()) {
            return;
        }
        Schema.FieldSet fs = FSMAP.get('updateAsset');
        List<FieldSetMember> fsmList = fs.getFields();
        // 获得字段集中的字段名
        List<String> column = new List<String>();
        for (FieldSetMember fsm : fsmList) {
            column.add(fsm.getFieldPath());
        }
        String soql = 'Select Id,Asset__c,Asset__r.Name,Asset__r.ProductCode,TransferApply__c  ';
        for (Integer i=0;i<column.size();i++) {
            soql += ',' + column[i];
        }
        soql += ' FROM TransferApplyDetail__c  Where TransferApply__c = :raIdSet';
        List<TransferApplyDetail__c> tadList = Database.query(soql);
        Map<Id,Asset> AssetMap = new  Map<Id,Asset>();
        for(TransferApplyDetail__c tad:tadList){
            if(!AssetMap.containsKey(tad.Asset__c)){
                Asset at = new Asset();
                at.Id = tad.Asset__c;
                at.TransferFrozenQuantity__c = 0;
                for (Integer i=0;i<column.size();i++) {
                    String tempS = column[i];
                    String tempSNew = tempS.replace('_After', '');
                    if(ASSETFSMAP.containsKey(tempSNew)){
                        String TadAfter = (String)tad.get(tempS);
                        if(!String.isBlank(TadAfter)){
                            at.put(tempSNew,TadAfter);
                        }
                    }else{
                        newMap.get(tad.TransferApply__c).addError('保有设备字段'+tempSNew+'不存在,无法更新');
                    }
                }
                if(at != null){
                    AssetMap.put(tad.Asset__c,at);
                }
            }else{
                newMap.get(tad.TransferApply__c).addError('有重复更新保有设备:'+tad.Asset__r.Name+',机身号码:'+tad.Asset__r.ProductCode+',请确认');
            }
        }
        if(AssetMap.size()>0){
            update AssetMap.values();
        }
    }


    // after insert, after update
    private void dynamicUpdateOfficeAssistantShare() {
        List<TransferApply__Share> insertShareList = new List<TransferApply__Share>();
        List<Id> deleteOfficeAssistantShare_nObjId_List = new List<Id>();       // 共享删除用
        for (TransferApply__c nObj : newList) {
            TransferApply__c oObj = (null == this.oldMap) ? null : this.oldMap.get(nObj.Id);
            if (Trigger.isInsert
                || (oObj.Before_Office_Assistant1__c != nObj.Before_Office_Assistant1__c
                    || oObj.Before_Office_Assistant2__c != nObj.Before_Office_Assistant2__c
                    || oObj.After_Office_Assistant1__c != nObj.After_Office_Assistant1__c
                    || oObj.After_Office_Assistant2__c != nObj.After_Office_Assistant2__c
                )
            ) {
                deleteOfficeAssistantShare_nObjId_List.add(nObj.Id);
                if (nObj.Before_Office_Assistant1__c != null) {
                    insertShareList.add(new TransferApply__Share(
                        RowCause = 'Office_Assistant__c',
                        ParentId = nObj.Id,
                        UserOrGroupId = nObj.Before_Office_Assistant1__c,
                        AccessLevel = 'Edit'
                    ));
                }
                if (nObj.Before_Office_Assistant2__c != null) {
                    insertShareList.add(new TransferApply__Share(
                        RowCause = 'Office_Assistant__c',
                        ParentId = nObj.Id,
                        UserOrGroupId = nObj.Before_Office_Assistant2__c,
                        AccessLevel = 'Edit'
                    ));
                }
                if (nObj.After_Office_Assistant1__c != null) {
                    insertShareList.add(new TransferApply__Share(
                        RowCause = 'Office_Assistant__c',
                        ParentId = nObj.Id,
                        UserOrGroupId = nObj.After_Office_Assistant1__c,
                        AccessLevel = 'Edit'
                    ));
                }
                if (nObj.After_Office_Assistant2__c != null) {
                    insertShareList.add(new TransferApply__Share(
                        RowCause = 'Office_Assistant__c',
                        ParentId = nObj.Id,
                        UserOrGroupId = nObj.After_Office_Assistant2__c,
                        AccessLevel = 'Edit'
                    ));
                }
            }
        }

        // 先 Delete, 后 Insert
        List<TransferApply__Share> deleteShareList = [SELECT Id, UserOrGroupId, ParentId, UserOrGroup.Name
                 FROM TransferApply__Share
                WHERE RowCause = 'Office_Assistant__c'
                  AND ParentId =: deleteOfficeAssistantShare_nObjId_List];
        if (deleteShareList.size() > 0) { delete deleteShareList; }
        if (insertShareList.size() > 0) { insert insertShareList; }
    }
    // 共享给审批人
    private void dynamicUpdateApprovalShare() {
        List<TransferApply__Share> insertShareList = new List<TransferApply__Share>();
        List<Id> deleteApproveShare_nObjId_List = new List<Id>();       // 共享删除用
        Set<Id> userIdSet = new Set<Id>();
        for (TransferApply__c nObj : newList) {
            TransferApply__c oObj = (null == this.oldMap) ? null : this.oldMap.get(nObj.Id);
            if (oObj != null && oObj.Request_time__c != nObj.Request_time__c && nObj.Request_time__c != null) {
                deleteApproveShare_nObjId_List.add(nObj.Id);
                userIdSet.clear();
                if(nObj.RecordTypeId == DEVELOPERNAMEMAP.get('AgencyToCenter').getRecordTypeId()) {
                    if(nObj.BeiPinWindow__c != null) {
                        userIdSet.add(nObj.BeiPinWindow__c);
                    }
                }
                else if(nObj.RecordTypeId == DEVELOPERNAMEMAP.get('CenterToAgency').getRecordTypeId()) {
                    if(nObj.SalesManager__c != null) {
                        userIdSet.add(nObj.SalesManager__c);
                    }
                    if(nObj.BuchangApprovalManagerSales__c != null) {
                        userIdSet.add(nObj.BuchangApprovalManagerSales__c);
                    }
                }
                else if(nObj.RecordTypeId == DEVELOPERNAMEMAP.get('InsideCenter').getRecordTypeId()
                        || nObj.RecordTypeId == DEVELOPERNAMEMAP.get('CenterToCenter').getRecordTypeId()) {
                    if(nObj.SalesManager__c != null) {
                        userIdSet.add(nObj.SalesManager__c);
                    }
                    if(nObj.HuaDongAccept__c != null) {
                        userIdSet.add(nObj.HuaDongAccept__c);
                    }
                    if(nObj.BuchangApprovalManagerSales__c != null) {
                        userIdSet.add(nObj.BuchangApprovalManagerSales__c);
                    }
                }
                else if(nObj.RecordTypeId == DEVELOPERNAMEMAP.get('CenterToOther').getRecordTypeId()) {
                    if(nObj.SalesManager__c != null) {
                        userIdSet.add(nObj.SalesManager__c);
                    }
                    if(nObj.HuaDongAccept__c != null) {
                        userIdSet.add(nObj.HuaDongAccept__c);
                    }
                    if(nObj.BuchangApprovalManagerSales__c != null) {
                        userIdSet.add(nObj.BuchangApprovalManagerSales__c);
                    }
                    if(nObj.ZongJian__c != null) {
                        userIdSet.add(nObj.ZongJian__c);
                    }
                }
            }
            for(Id userId:userIdSet) {
                insertShareList.add(new TransferApply__Share(
                    RowCause = 'Approval__c',
                    ParentId = nObj.Id,
                    UserOrGroupId = userId,
                    AccessLevel = 'Edit'
                ));
            }
        }
        // 先 Delete, 后 Insert
        List<TransferApply__Share> deleteShareList = [SELECT Id, UserOrGroupId, ParentId, UserOrGroup.Name
                 FROM TransferApply__Share
                WHERE RowCause = 'Approval__c'
                  AND ParentId =: deleteApproveShare_nObjId_List];
        if (deleteShareList.size() > 0) { delete deleteShareList; }
        if (insertShareList.size() > 0) { insert insertShareList; }
    }
}