/**********************************************************************
 * 
 *
 * @url: /services/apexrest/NFM209/execute
 * 
 * 
*************************************************************************/
@RestResource(urlMapping='/NFM209/*')
global with sharing class NFM209Rest {
    //新增NFM209Rest 合规状态  you start
  
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }

    global class GeData {
        public String custCode;                    // 客户管理编码
        public String complStatus;                 // 零合规状态
        public String orgSysId;                    // 发起系统
        public String glbBusiNo;                   // 报文流水号
        public String custTp;                      // 对象类型
        public String entityTp;                    // 实体类型
        public String custName;                    // 客户名称
       
    }

    @HttpPost
    global static void execute() {

        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
        system.debug('rquest----'+strData);
        if (ges == null ) {
            return;
        }

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

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM209', ges.GeData);
        if (String.isBlank(rowData.Log__c) == false) {
            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
    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 = 'Account')
                                          ];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }


        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, retry_cnt__c, 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 from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'NFM209';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);

        if (geDataList == null || geDataList.size() == 0) {
            return;
        }

        Savepoint sp = Database.setSavepoint();

        try {
            List<Account> accInsList = new List<Account>();

            //将客户管理编码、合规状态存入List
            List<String> custCodeList = new List<String>();
            List<String> complStatusList = new List<String>();
            
            for (GeData geData : geDataList) {
                if (String.isBlank(geData.custCode)) {
                    iflog.ErrorLog__c += '管理编码不能为空。\n';
                    continue;
                } else {
                    custCodeList.add(geData.custCode);
                }

                if (String.isBlank(geData.complStatus)) {
                    iflog.ErrorLog__c += geData.custCode+':合规状态为空。\n';
                    continue;
                } 
                
            }
            
            //客户管理编码和合规状态日期存入Map
            Map<String, Account> accInfoMap = new Map<String, Account>();
            if (custCodeList.size() > 0) {
                List<Account> accList = [select ID,Parent_Management_CodeClean__c,TradeComplianceStatus__c  from Account where Parent_Management_CodeClean__c in :custCodeList and (RecordType.DeveloperName = 'HP' or RecordType.DeveloperName = 'Agency')];
                if (accList.size() > 0) {
                    for (Account accInfo : accList) {
                        accInfoMap.put(accInfo.Parent_Management_CodeClean__c, accInfo);
                    }
                }
            }
            
            // 将XML的合规状态存入客户对象中
            for (GeData geData : geDataList) {
                    
                Account acc = new Account();
                if (!accInfoMap.containsKey(geData.custCode)){
                	iflog.ErrorLog__c += '客户管理编码:' +geData.custCode +'：未找到。\n';
                	continue;
                }
                acc.Id = (accInfoMap.get(geData.custCode)).ID;            
                acc.TradeComplianceStatus__c = NFMUtil.getMapValue(transferMap, 'TradeComplianceStatus__c', string.valueof(geData.complStatus), iflog);             //合规状态
                
                accInsList.add(acc);
                logstr += '客户管理编码:' +geData.custCode +'：获取成功。\n';

            }

            if (accInsList.size() > 0) {
                upsert accInsList;
                logstr += '更新成功。\n';
            }

            logstr += '\nend';
            rowData.retry_cnt__c = 0;

        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM209_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM209_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c++;
                LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }

        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) + ' ...';
        }
        update iflog;
    }
    //新增NFM209Rest 合规状态 you end
}