/**********************************************************************
 * 
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
        
    }
 * @msg:
 *   1.接收到的决裁信息全键更新到学会上，保持学会和决裁一直（空的项目不更新）
 *   2.赞助会不做自动创建和自动更新
 *   3.补充决裁额外创建新的决裁数据，但不自动创建学会
 *   4.补充决裁更新时只更新决裁信息，不更新学会
*************************************************************************/
@RestResource(urlMapping='/NFM705/*')
global with sharing class NFM705Rest {
    public static final String LOG_TYPE = 'NFM705';
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }
    global class GeData {
        public String MeetingApprovedNo; //会议决裁编码==MeetingApprovedNo__c
        public String Name; //会议名称 == Name
        public String Num; //会议编码 == Num__c
        public String StartDate; //开始日期 == StartDate
        public String EndDate; //结束日期 == EndDate
        public String BudgetType; //预算类型 == Budget_Type__c
        public String OfficeCategory; //科室分类 == OfficeCategory__c
        public String MeetingType; //会议类型 == Meeting_Type__c   
        public String StateMaster; //省 == State_Master__c
        public String CityMaster; //市 == City_Master__c
        public String WorkshopPlace; //会场地点 == WorkshopPlace__c
        public String HostName; //会议主办方 == HostName__c
        public String CooperatorCompany; //会议承办方 == cooperatorCompany__c
        public String SponsorshipCategory;//赞助款项是否支付给主办方
        public String IsPaidToSponsor;//赞助类别
        public Decimal ConveningParticipantsNum; //参加人数（召开） == Convening_Participants_Num__c
        public Integer ProcessState;//OBPM审批状态
        public Decimal ExpectedOlympusAttendance;//预计参会Olympus人数
        public String ActivityTypeName;//活动形式
        public Decimal ExpectedHcpAttendance;//预计参会HCP人数
        public String IsCoOrganizingActivities;//传Y/N，转是/否
        public String Applicant; // 申请人的员工编码  == Applicant__c
        public String SharedEditing; // 共享人的员工编码 == Shared_Editing__c
    }

    private static Map<String, String> states;

    private static Map<String, String> cities;
    
    @HttpPost
    global static void doPost() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);


        if (ges == null) {
            return;
        }

        NFMUtil.Monitoring Monitoring = ges.Monitoring;
        if (Monitoring == null) {
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, LOG_TYPE, ges.GeData);
        system.debug('String.isBlank(rowData.Log__c) == false?');
        if (String.isBlank(rowData.Log__c) == false) {
            System.debug('进入if方法，成功调用executefuture');
            executefuture(rowData.Id);
        }

        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = '{"Result": {"Result": "00", "Message":""}}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }
    @future(callout = true)
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }
    global static void main(String rowData_Id) {
        
        Map<String, String> transferMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferList = [select Table__c,
                                  Column__c,
                                  External_value__c,
                                  Internal_value__c
                                  from BatchIF_Transfer__c
                                  where Dropped_Flag__c = false
                                          and (Table__c = 'Application_for_Conference_Adjudication__c')
                                          ];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }
        
        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id =: rowData_Id];

        String logstr = 'start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = LOG_TYPE;
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);

        List < GeData > itemMasterList = (List < GeData > ) JSON.deserialize(rowDataStr, List < GeData > .class);
        logstr += '数据总数为：' + itemMasterList.size() + '\n';
        if (itemMasterList == null || itemMasterList.size() == 0) {
            return;
        }
        Savepoint sp = Database.setSavepoint();
        try {
            List <Application_for_Conference_Adjudication__c> acaList = new List <Application_for_Conference_Adjudication__c>();
            //Map<string,GeData> meetingApprovedNoMap = new Map<string,GeData>();
            List<String> meetingApprovedNoList = new List<String>();
            List<String> NumList = new List<String>();
            List<User> users = new List<User>();
            for(GeData ged : itemMasterList){
                //验证数据完整性
                // String dataComplete = verify(ged);
                // if (!String.isBlank(dataComplete)) {
                //     logstr += dataComplete;
                //     continue;
                // }
                meetingApprovedNoList.add(ged.MeetingApprovedNo);
                // if (String.isNotBlank(ged.Num)) {
                //     NumList.add(ged.Num);
                // }
            }
            
            //Map<String,String> campaignMap = new Map<String,String>();
            // for(Campaign temp : campaignList){
            //     campaignMap.put(temp.Num__c,temp.Id);
            // }

            //查询会议决裁表
            Map<String,Application_for_Conference_Adjudication__c> oldacfcMap = new Map<String,Application_for_Conference_Adjudication__c>();
            List<Application_for_Conference_Adjudication__c> oldafcaList = [select Id, MeetingApprovedNo__c, Num__c, ProcessState__c
                                                                from Application_for_Conference_Adjudication__c
                                                                where MeetingApprovedNo__c IN :meetingApprovedNoList 
                                                                and ProcessState__c != '审批成功'];
            for(Application_for_Conference_Adjudication__c oldafca  : oldafcaList){
                oldacfcMap.put(oldafca.MeetingApprovedNo__c,oldafca);
            }

            // 所有人信息
            List<String> user_nos = new List<String>();

            for (GeData ged : itemMasterList) {
                //新建会议裁决申请
                Application_for_Conference_Adjudication__c aca = new Application_for_Conference_Adjudication__c();
                aca.MeetingApprovedNo__c            = ged.MeetingApprovedNo;
                aca.Name                            = ged.MeetingApprovedNo; // 用决裁编号替代名称
                aca.CampaignTheme__c                = ged.Name;
                aca.Num__c                          = ged.Num;
                aca.StartDate__c                    = NFMUtil.parseDateTimeStr2Date(ged.StartDate);
                aca.EndDate__c                      = NFMUtil.parseDateTimeStr2Date(ged.EndDate);
                aca.BudgetType__c                   = ged.BudgetType;
                aca.OfficeCategory__c               = GetOfficeCategory(ged.OfficeCategory, transferMap, iflog);
                //aca.MeetingType__c                  = ged.MeetingType;
                aca.MeetingType__c                  = DividingTypes(ged.IsCoOrganizingActivities,ged.ActivityTypeName);
                aca.StateMaster__c                  = ged.StateMaster;
                aca.CityMaster__c                   = ged.CityMaster;
                aca.WorkshopPlace__c                = ged.WorkshopPlace;
                aca.HostName__c                     = String.isBlank(ged.HostName) ? '无' : ged.HostName;
                aca.CooperatorCompany__c            = String.isBlank(ged.CooperatorCompany) ? '无' : ged.CooperatorCompany;
                aca.ConveningParticipantsNum__c     = ged.ConveningParticipantsNum;
                aca.IsPaidToSponsor__c              = NFMUtil.getMapValue(transferMap, 'IsPaidToSponsor__c', string.valueof(ged.IsPaidToSponsor), iflog);
                aca.SponsorshipCategory__c          = ged.SponsorshipCategory;
                aca.ExpectedOlympusAttendance__c    = ged.ExpectedOlympusAttendance;
                aca.ActivityTypeName__c             = ged.ActivityTypeName;
                aca.ExpectedHcpAttendance__c        = ged.ExpectedHcpAttendance;
                aca.ProcessState__c                 = NFMUtil.getMapValue(transferMap, 'ProcessState__c', string.valueof(ged.ProcessState), iflog);
                aca.Type_of_adjudication_meeting__c = ged.MeetingType;
                aca.Activities_of_a_share__c        = NFMUtil.getMapValue(transferMap, 'Activities_of_a_share__c', string.valueof(ged.IsCoOrganizingActivities), iflog);

                if(oldacfcMap.containsKey(ged.MeetingApprovedNo) && 
                    (aca.ProcessState__c != '补充决裁' || 
                    aca.ProcessState__c == oldacfcMap.get(ged.MeetingApprovedNo).ProcessState__c)){
                    aca.Id = oldacfcMap.get(ged.MeetingApprovedNo).Id;
                    aca.Num__c = String.isBlank(aca.Num__c) ? oldacfcMap.get(ged.MeetingApprovedNo).Num__c : aca.Num__c; 
                } 
                if (String.isNotBlank(aca.Num__c)) {
                    NumList.add(aca.Num__c);
                }
                system.debug('NumList------------->'+NumList);
                // 确认申请人
                System.debug('aca.Id: ' + aca.Id);
                if (String.isBlank(aca.Id)) {
                    user_nos.add(ged.Applicant);
                }

                aca.IsSupplemental__c = aca.ProcessState__c != '补充决裁' ? false : true;
                aca.Applicant__c = ged.Applicant;
                aca.Shared_Editing__c = ged.SharedEditing;
                if (String.isNotBlank(ged.SharedEditing)) {
                    user_nos.addAll(ged.SharedEditing.split(','));
                }
                System.debug(user_nos);

                acaList.add(aca);
            }
            List<Campaign> campaignList = NumList.size() > 0 ? [select Id, 
                                            Num__c, 
                                            MeetingApprovedNo__c 
                                        from Campaign 
                                        where Num__c IN: NumList 
                                        ] : new List<Campaign>();
            // 查找所有人
            if (user_nos != null && user_nos.size() > 0) {
                // 2022-03-23 紧急修复 未启用的用户无法设置共享
                users = [select Id, Employee_No__c from User where Employee_No__c in :user_nos and IsActive = true];
                if (users != null && users.size() > 0) {
                    String owner = '';
                    for (Application_for_Conference_Adjudication__c app : acaList) {
                        System.debug('owner from 705: ' + app.Applicant__c);
                        for (User u : users) {
                            System.debug('user no: ' + u.Employee_No__c);
                            if (String.isNotBlank(u.Employee_No__c) && u.Employee_No__c.equals(app.Applicant__c)) {
                                app.OwnerId = u.Id;
                                owner = u.Id;
                                break;
                            }
                        }
                    }
                }
            }
            
            if (acaList.size() > 0) {
                // 写入决裁信息
                upsert acaList;
                // 共享权限
                SetSharing(users, acaList);
                // 自动创建学会
                // 2022-02-22 会议确认 无法确认记录类型，不做自动创建
                // List<Application_for_Conference_Adjudication__c> wait_to_create_cams = new List<Application_for_Conference_Adjudication__c>();
                // List<Campaign> new_campaigns = new List<Campaign>();
                // for (Application_for_Conference_Adjudication__c app : acaList) {
                //     if (String.isBlank(app.Id) && String.isBlank(app.Num__c) && app.MeetingType__c != '赞助会' && app.ProcessState__c != '补充决裁') {
                //         wait_to_create_cams.add(app);
                //     }
                // }
                // if (wait_to_create_cams != null && wait_to_create_cams.size() > 0) {
                //     for (Application_for_Conference_Adjudication__c app : wait_to_create_cams) {
                //         Campaign cam = createNewCampaignFromApplication(app);
                //         new_campaigns.add(cam);
                //     }
                //     if (new_campaigns.size() > 0) {
                //         insert new_campaigns;
                //     }
                // }
                // 更新已存在的决裁信息
                System.debug('查找到的会议: ' + campaignList.size());
                if (campaignList != null && campaignList.size() > 0) {
                    List<Campaign> updatelist = new List<Campaign>();
                    for (Campaign cam : campaignList) {
                        for (Application_for_Conference_Adjudication__c app : acaList) {
                            if (cam.Num__c == app.Num__c && !app.IsSupplemental__c) {
                                cam.MeetingApprovedNo__c             = app.MeetingApprovedNo__c;
                                cam.Meeting_Approved_No__c           = app.Id;
                                if (app.MeetingType__c != '赞助会') {
                                    cam.StartDate                        = app.StartDate__c;
                                    cam.EndDate                          = app.EndDate__c;
                                    cam.Budget_Type__c                   = app.BudgetType__c;
                                    cam.OfficeCategory__c                = app.OfficeCategory__c;
                                    cam.Meeting_Type__c                  = app.MeetingType__c;
    
                                    cam.WorkshopPlace__c                 = app.WorkshopPlace__c;
                                    cam.HostName__c                      = app.HostName__c;
                                    cam.cooperatorCompany__c             = app.CooperatorCompany__c;
                                    cam.Convening_Participants_Num__c    = app.ConveningParticipantsNum__c;
    
                                    // OBPM对接 新增字段
                                    cam.Expected_Olympus_Attendance__c   = app.ExpectedOlympusAttendance__c;
                                    cam.Expected_Hcp_Attendance__c       = app.ExpectedHcpAttendance__c;
                                    cam.SponsorshipCategory__c           = app.SponsorshipCategory__c;
                                    cam.IsPaidToSponsor__c               = app.IsPaidToSponsor__c;
                                    // cam.Activity_Type_Name__c            = app.ActivityTypeName__c;
                                    cam.Activity_Type_Name__c            = app.Type_of_adjudication_meeting__c;
                                    // 这里需要额外加操作
                                    cam.State_Master__c                  = StateCityUtil.get_state(app.StateMaster__c);                 
                                    cam.City_Master__c                   = StateCityUtil.get_city(app.CityMaster__c);
                                }
                                

                                updatelist.add(cam);
                                break;
                            }
                        }
                    }
                    if (updateList.size() > 0) {
                        update updatelist;
                    }
                }
            }
            rowData.retry_cnt__c = 0;
            logstr += '\nend';
        } catch (Exception ex) {
            Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
            // エラーが発生した場合
            Database.rollback(sp);
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            // 异常重发
            rowData = NFMUtil.LogAutoSend(rowData, ex, null);
        }
        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        upsert iflog;

        
    }
    // 必填字段验证
    // private static String verify(GeData ged) {
    //     String result = '';

    //     // Map<String , String> BudgetTypeMap = new Map<String,String>();
    //     // BudgetTypeMap.put(ged.BudgetType, '新产品上市');
    //     // BudgetTypeMap.put(ged.BudgetType, '产品推广');
    //     // BudgetTypeMap.put(ged.BudgetType, '主题活动（NBI早癌，EUS大赛等）');
    //     // BudgetTypeMap.put(ged.BudgetType, '产品售后使用培训');
    //     // BudgetTypeMap.put(ged.BudgetType, 'NTC等故障预防活动');
    //     // BudgetTypeMap.put(ged.BudgetType, '经销商相关会议');
    //     // BudgetTypeMap.put(ged.BudgetType, '其他');

    //     // Map<String , String> OfficeCategoryMap = new Map<String,String>();
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '1.消化科');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '2.呼吸科');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '3.普外科');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '4.泌尿科');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '5.妇科');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '6.耳鼻喉科');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '其他');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '肝胆外科');
    //     // OfficeCategoryMap.put(ged.OfficeCategory, '胃肠外科');

    //     // Map<String , String> MeetingTypeMap = new Map<String,String>();
    //     // MeetingTypeMap.put(ged.MeetingType, '自办会');
    //     // MeetingTypeMap.put(ged.MeetingType, '赞助会');
    //     // MeetingTypeMap.put(ged.MeetingType, '共同主办会');

    //     // if (ged.MeetingApprovedNo == null) {
    //     //     result += 'DataError: 会议决裁编码 [ MeetingApprovedNo ] is null!\n';
    //     // }
    //     if (String.isBlank(ged.Name)) {
    //         result += 'DataError: 会议名称 [ Name ] 不能为空!\n';
    //     }
    //     if(String.isBlank(ged.MeetingApprovedNo)){
    //         result += 'DataError:会议决裁编码[MeetingApprovedNo] 不能为空!\n';
    //     }
    //     if(ged.ProcessState == null){
    //         result += 'DataError:OBPM审批状态[ProcessState] 不能为空!\n';
    //     }
    //     if(String.isBlank(ged.HostName)){
    //         result += 'DataError:会议主办方[HostName] 不能为空!\n';
    //     }
    //     if(String.isBlank(ged.CooperatorCompany)){
    //         result += 'DataError:会议承办方[CooperatorCompany] 不能为空!\n';
    //     }
    //     /*if (!BudgetTypeMap.containsKey(ged.BudgetType)) {
    //         result += 'DataError: 预算类型 [ BudgetType ] 传值有误!\n';
    //     } else if (!ged.BudgetType.equals('产品推广')) {
    //         result += 'DataError: 预算类型 [ BudgetType ] 传值有误!\n';
    //     } else if (!ged.BudgetType.equals('主题活动（NBI早癌，EUS大赛等）')) {
    //         result += 'DataError: 预算类型 [ BudgetType ] 传值有误!\n';
    //     } else if (!ged.BudgetType.equals('产品售后使用培训')) {
    //         result += 'DataError: 预算类型 [ BudgetType ] 传值有误!\n';
    //     } else if (!ged.BudgetType.equals('NTC等故障预防活动')) {
    //         result += 'DataError: 预算类型 [ BudgetType ] 传值有误!\n';
    //     } else if (!ged.BudgetType.equals('经销商相关会议')) {
    //         result += 'DataError: 预算类型 [ BudgetType ] 传值有误!\n';
    //     } else if (!ged.BudgetType.equals('其他')) {
    //         result += 'DataError: 预算类型 [ BudgetType ] 传值有误!\n';
    //     }
    //     if (!OfficeCategoryMap.containsKey(ged.OfficeCategory)) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('2.呼吸科')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('3.普外科')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('4.泌尿科')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('5.妇科')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('6.耳鼻喉科')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('其他')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('肝胆外科')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     } else if (!ged.OfficeCategory.equals('胃肠外科')) {
    //         result += 'DataError: 科室分类 [ OfficeCategory ] 传值有误!\n';
    //     }
    //     if (!MeetingTypeMap.containsKey(ged.MeetingType)) {
    //         result += 'DataError: 会议类型 [ MeetingType ] 传值有误!\n';
    //     } else if (!ged.MeetingType.equals('赞助会')) {
    //         result += 'DataError: 会议类型 [ MeetingType ] 传值有误!\n';
    //     } else if (!ged.MeetingType.equals('共同主办会')) {
    //         result += 'DataError: 会议类型 [ MeetingType ] 传值有误!\n';
    //     } */
    //     return result;
    // }

    // 创建会议 绑定决裁相关信息
    // public static Campaign createNewCampaignFromApplication(Application_for_Conference_Adjudication__c app) {
    //     Campaign cam = new Campaign();
    //     //定义变量保存记录类型
    //     Id RtId = Schema.SObjectType.Campaign.getRecordTypeInfosByDeveloperName().get('Society').getRecordTypeId();
    //     //List<Id> = [select Id from RecordType where IsActive = true and SobjectType = 'CampaignMember' and Name = '社外参加人'];
    //     Id RtId2 = Schema.SObjectType.CampaignMember.getRecordTypeInfosByDeveloperName().get('WorkShop').getRecordTypeId();
    //     cam.RecordTypeId                     = RtId;
    //     cam.CampaignMemberRecordTypeId       = RtId2;//ID不写死 社外人员

    //     cam.Name                             = app.MeetingApprovedNo__c;
    //     cam.Name2__c                         = app.MeetingApprovedNo__c;
    //     cam.MeetingApprovedNo__c             = app.MeetingApprovedNo__c;
    //     cam.Meeting_Approved_No__c           = app.Id;
    //     cam.StartDate                        = app.StartDate__c;
    //     cam.EndDate                          = app.EndDate__c;
    //     cam.Budget_Type__c                   = app.BudgetType__c;
    //     cam.OfficeCategory__c                = app.OfficeCategory__c;
    //     cam.Meeting_Type__c                  = app.MeetingType__c;
    //     cam.Activity_Type_Name__c            = app.ActivityTypeName__c;
        
    //     cam.WorkshopPlace__c                 = app.WorkshopPlace__c;
    //     cam.HostName__c                      = app.HostName__c;
    //     cam.cooperatorCompany__c             = app.CooperatorCompany__c;
    //     cam.Convening_Participants_Num__c    = app.ConveningParticipantsNum__c;
    //     cam.IF_Approved__c                   = true;

    //     // OBPM对接 新增字段
    //     cam.Expected_Olympus_Attendance__c   = app.ExpectedOlympusAttendance__c;
    //     cam.Expected_Hcp_Attendance__c       = app.ExpectedHcpAttendance__c;
    //     cam.SponsorshipCategory__c           = app.SponsorshipCategory__c;
    //     cam.IsPaidToSponsor__c               = app.IsPaidToSponsor__c;
    //     cam.Activity_Type_Name__c            = app.ActivityTypeName__c;

    //     // 新增所有人信息
    //     List<String> user_nos = new List<String>();
    //     user_nos.add(app.Applicant__c);
    //     user_nos.addAll(app.Shared_Editing__c.split(','));
    //     List<User> users = [select Id, Employee_No__c from User where Employee_No__c in :user_nos];
    //     if (users != null && users.size() > 0) {
    //         for (User u : users) {
    //             if (u.Employee_No__c == app.Applicant__c) {
    //                 cam.OwnerId = u.Id;
    //             }
    //         }
    //     }

    //     return cam;
    // }

    public static string DividingTypes(String IsCoOrganizingActivities,String ActivityTypeName){
        if('N'.equals(IsCoOrganizingActivities)){
            if('赞助'.equals(ActivityTypeName)){
                return '赞助会';
            }
            return '主办会';
        }
        return '共同主办会';
    }

    public static void SetSharing(List<User> users, List<Application_for_Conference_Adjudication__c> apps) {
        if (users == null || users.size() <= 0 || apps == null || apps.size() <= 0) {
            return;
        }
        // 初始化参数
        List<Application_for_Conference_Adjudication__Share> delete_list = new List<Application_for_Conference_Adjudication__Share>();
        List<Application_for_Conference_Adjudication__Share> insert_list = new List<Application_for_Conference_Adjudication__Share>();
        List<String> app_ids = new List<String>();
        // 共享理由
        String rowCauseShare = Schema.Application_for_Conference_Adjudication__Share.RowCause.Shared_Editor__c;
        // 循环设置
        for (Application_for_Conference_Adjudication__c app : apps) {
            app_ids.add(app.Id);
            System.debug('app.Shared_Editing__c: ' + app.Shared_Editing__c);

            for (User u : users) {
                if (String.isBlank(u.Employee_No__c)) {
                    continue;
                }
                System.debug('u.Employee_No__c: ' + u.Employee_No__c);
                if (app.Shared_Editing__c.contains(u.Employee_No__c)) {
                    Application_for_Conference_Adjudication__Share aos = new Application_for_Conference_Adjudication__Share(
                        RowCause = rowCauseShare,
                        ParentId = app.Id,
                        UserOrGroupId = u.Id,
                        AccessLevel = 'Edit');
                    insert_list.add(aos);
                }
            }
        }
        // 先删除
        delete_list = [select Id from Application_for_Conference_Adjudication__Share where ParentId in :app_ids and RowCause =: rowCauseShare];
        if (delete_list != null && delete_list.size() > 0) {
            delete delete_list;
        }
        // 再新增
        if (insert_list != null && insert_list.size() > 0) {
            System.debug('insert_list is: ');
            System.debug(insert_list);
            insert insert_list;
        }
    }

    public static String GetOfficeCategory(String OfficeCategory, Map<String, String> transferMap, BatchIF_Log__c iflog) {
        if (String.isNotBlank(OfficeCategory)) {
            List<String> categories = OfficeCategory.split(',');
            if (categories != null && categories.size() > 0) {
                return NFMUtil.getMapValue(transferMap, 'OfficeCategory__c', categories.get(0), iflog);
            }
        }
        return null;
    }
}