@RestResource(urlMapping='/NFM113/*')
global with sharing class NFM113Rest {
    private static final String LOG_TYPE = 'NFM113';
    global class GeDatasRest {
        public GeDatas GeDatas;
    }
    
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public ReceiveInfo[] ReceiveInfo;
    }

    global class ReceiveInfo{
        public String ReceiveNo;    //认款编号
        public String ItemNO;       //认款行项目
        public String CompanyCode;  //公司代码,根据此查找经销商
        public String ContractNo;    //维修合同号
        public String Amount;       //认款金额
        public String ReceiveDate;  //认款日期
        public String DeleteFlag;   //删除标识          删除状态打‘X’ 正常状态为空
        public String DeleteDate;   //认款删除日期      删除状态填写日期 正常状态为空
        public String Operator;     //认款人员
    }
    
    @HttpPost
    global static void execute() {

        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        // GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
        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.ReceiveInfo);
        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 = '{"status": "Success", "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){
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        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 = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'NFM113';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<ReceiveInfo> GeDataList = (List<ReceiveInfo>) JSON.deserialize(rowDataStr, List<ReceiveInfo>.class);
        if (GeDataList == null || GeDataList.size() == 0) {
            return;
        }

        Savepoint sp = Database.setSavepoint();
        List<String> ReceiveNoList = new List<String>();//认款编号List
        List<String> CompanyCodeList = new List<String>();//公司编码List
        List<string> ContractNoList = new List<String>();//维修合同List
        //List<String> OperatorList = new List<String>();//认款人员List
        for(ReceiveInfo gedata : GeDataList){//判空    
            // //必填的验证
            // if(gedata.ReceiveNo = ''){
            //     iflog += '认款编号未填写无法保存该条数据';
            // }
            string key = gedata.ReceiveNo + gedata.ContractNo + gedata.ItemNO;
            ReceiveNoList.add(key);
            CompanyCodeList.add(gedata.CompanyCode);
            ContractNoList.add(gedata.ContractNo);
            //OperatorList.add(gedata.Operator);
        }
        Map<string,Id> ContractMap = new Map<string,Id>();
        Map<String,Payment_Maintenance_Contract__c> allMap = new Map<String,Payment_Maintenance_Contract__c>();
        List< Payment_Maintenance_Contract__c > allList =[select Id,ReceiveNoKey__c,ContractNo__c,ReceiveNo__c,ItemNO__c,Find_Dealers__c,Amount__c,Find_Contact__c,ReceiveDate__c,DeleteFlag__c,DeleteDate__c,Operator__c from Payment_Maintenance_Contract__c where ReceiveNoKey__c IN:ReceiveNoList];
        system.debug('allList'+allList);
        //增加一个用公司代码查找经销商SQL
        List<Account> dealersList = [select Id,Management_Code__c from account where Management_Code__c IN:CompanyCodeList AND RecordTypeId = '01210000000Qem1'];//
        List<Maintenance_Contract__c> ContractList = [select Id,Management_Code__c from Maintenance_Contract__c where Management_Code__c IN:ContractNoList];//查找维修合同
        //List<contact> conList = [select Id,Employee_No_manual__c from Contact where Employee_No_manual__c IN:OperatorList]; //联系人
        Map<string,Id> dealersMap = new Map<String,Id>();
        //Map<string,Id> ContractMap = new Map<String,Id>();
        //Map<string,Id> ConMap = new Map<String,Id>();
        for(Account temp : dealersList){//经销商Map
            dealersMap.put(temp.Management_Code__c,temp.Id);
        } 
        for(Maintenance_Contract__c temp : ContractList){//维修合同Map
            ContractMap.put(temp.Management_Code__c,temp.Id);
        }
        for(Payment_Maintenance_Contract__c temp : allList){//维修合同RC主数据Map，接收数据Map
            allMap.put(temp.ReceiveNoKey__c,temp);
        }
        // for(contact temp : conList){//联系人Map
        //     ConMap.put(temp.Employee_No_manual__c.repleace('o','O'),temp.Id);
        // }
        
        try{
            List<Payment_Maintenance_Contract__c> RMCList = new List<Payment_Maintenance_Contract__c>();//存放用于更新的数据
            // Map<String,Payment_Maintenance_Contract__c> RMCMap = new Map<String,Payment_Maintenance_Contract__c>();
            for(ReceiveInfo gedata : GeDataList){//遍历所有接口获取到的数据，判断该数据是否存在，因而进行更新或新增
                Payment_Maintenance_Contract__c RMC = new Payment_Maintenance_Contract__c();
                string key = gedata.ReceiveNo + gedata.ContractNo + gedata.ItemNO;
                system.debug('key2021/12/13              '+key);
                system.debug('key2021/12/13__2              '+allMap.get(key));
                system.debug('allMap.containsKey(key)       '+allMap.containsKey(key));
                if(allMap.containsKey(key)){//判断数据是否存在
                    RMC = allMap.get(key);
                }
                RMC.ContractNo__c = gedata.ContractNo;//维修合同号
                RMC.ReceiveNo__c = gedata.ReceiveNo;//认款编码
                RMC.ReceiveNoKey__c = key;    
                RMC.ItemNO__c = gedata.ItemNO;//认款行项目
                RMC.CompanyCode__c = gedata.CompanyCode;//公司代码 5111
                RMC.Operator__c = gedata.Operator;//认款人员
                RMC.Amount__c = Decimal.valueof(String.valueOf(gedata.Amount).trim());//认款金额
                RMC.ReceiveDate__c = NFMUtil.parseStr2Date(gedata.ReceiveDate);//认款日期
                RMC.DeleteFlag__c = gedata.DeleteFlag;//删除标识
                RMC.DeleteDate__c = NFMUtil.parseStr2Date(gedata.DeleteDate);//删除日期
                if(ContractMap.containsKey(gedata.ContractNo)){//维修合同
                    if(string.isBlank(RMC.Id)){
                        RMC.Find_Contact__c = ContractMap.get(gedata.ContractNo);
                    }
                }else{
                    iflog.ErrorLog__c += '输入的维修合同ID不存在';
                    continue;
                }
               
                // if(ConMap.containskey(gedata.Operator)){//认款人员
                //     RMC.Employees__c = ConMap.get(gedata.Operator);
                // }else{
                //     iflog.ErrorLog__c += '输入的认款人员不存在';
                //     continue;
                // }
                // RMCList.add(RMC);
                allMap.put(key,RMC);
            }
            system.debug('RMCList                 '+RMCList);
            // if(RMCList.size()>0){
            //     upsert RMCList; 
            // }
            if (allMap.size() >0) {
                upsert allMap.values();
            }
            rowData.retry_cnt__c = 0;
            logstr += '\nend';

            if (System.Test.isRunningTest()) {
                throw new ControllerUtil.myException('aaa');
            }
        }catch (Exception ex){
            // エラーが発生した場合1
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, LOG_TYPE+'_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, LOG_TYPE+'_' + 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 + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            // }
            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) + ' ...';
        }
        update iflog;
       
    }
}