/**
 * 
 * @url: /services/apexrest/接口编号/execute
 * 
 */
@RestResource(urlMapping='/NFM706/*')
global with sharing class NFM706Rest {

    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }

    public static final String LOG_TYPE = 'NFM706';
    global class GeData {
        public String MeetingApprovedNo; //会议决裁编码==MeetingApprovedNo__c
        public String Num; //会议编码 == Num__c
        public Integer ProcessState;//OBPM审批状态
    }
    @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);

        Map<String,Id> campignMap = new Map<String,Id>();

        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
            List <Application_for_Conference_Adjudication__c> acaList = new List<Application_for_Conference_Adjudication__c>();
            //会议
            List<String> meetingApprovedNoList = new List<String>();
            
            List<String> NumList = new List<String>();

            for( GeData ged : itemMasterList){
                //验证数据完整性
                String dataComplete = verify(ged);
                if (!String.isBlank(dataComplete)) {
                    logstr += dataComplete;
                    continue;
                }
                meetingApprovedNoList.add(ged.MeetingApprovedNo);
                NumList.add(ged.Num);
            }
            
            //查询SFDC的会议决裁表
            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,	ProcessState__c
                                                                from Application_for_Conference_Adjudication__c
                                                                where MeetingApprovedNo__c IN :meetingApprovedNoList];
            for(Application_for_Conference_Adjudication__c oldafca  : oldafcaList){
                oldacfcMap.put(oldafca.MeetingApprovedNo__c,oldafca);
            }

            Map<String,Application_for_Conference_Adjudication__c> updateMap = new Map<String,Application_for_Conference_Adjudication__c>();


            for(GeData ged : itemMasterList){
                if(oldacfcMap.containsKey(ged.MeetingApprovedNo)){
                    //新会议裁决申请
                    Application_for_Conference_Adjudication__c aca = new Application_for_Conference_Adjudication__c();
                    Application_for_Conference_Adjudication__c aca1 = oldacfcMap.get(ged.MeetingApprovedNo);
                    logstr += '已存在会议决裁编码\n';
                    aca.Id                            = aca1.Id;
                    aca.MeetingApprovedNo__c          = ged.MeetingApprovedNo;
                    // aca.Num__c                        = ged.Num;
                    aca.ProcessState__c               = NFMUtil.getMapValue(transferMap, 'ProcessState__c', string.valueof(ged.ProcessState), iflog);
                    updateMap.put(ged.MeetingApprovedNo, aca);
                
                }else {
                    logstr += '不存在的会议编码';
                }

                if( updateMap.size() > 0 ) {
                    logstr += '更新数据\n' + updateMap.values();
                    Update updateMap.values();
                }

                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;
    }


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

        if (ged.MeetingApprovedNo == null) {
            result += 'DataError: 会议决裁编码 [ MeetingApprovedNo ] is null!\n';
        }
        if (ged.Num == null) {
            result += 'DataError: SFDC编码 [ Num ] is null!\n';
        }
        if (ged.ProcessState == null) {
            result += 'DataError: OBPM审批状态 [ ProcessState ] is null!\n';
        }

        return result;
    }

}