@RestResource(urlMapping = '/NFM206/*')
global with sharing class NFM206Rest {

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

    global class GeData {
        public String NotesApprovedNo;                    // 合同申请决裁编码
        public String Assistant_Applied_Date;             // 助理：合同DB申请日（SPO的起草日期）
        public String Opportunity_No;                     // 询价编码
        public String OCM_Agent1_Price_DB;                // OCM-Agent1(合同DB)_元（SPO的合同金额）
        public String Contract_DB_SalesDept_complite_day; // 销售部:合同DB审批结束日
        public String Contract_DB_complite_day;           // 合同DB审批结束日
        public String Contract_DB_request_reason;         // 合同DB特价申请原因（SPO的合同特殊申请时的备注）
        public String ApprovedType;                       // User操作类型  3：撤回申请
        public String ContractType;                       // 业务申请类型 1：新建合同   2.更改合同   3.撤销合同
        public String Closing_Bid_Date;                   // 中标日期
        public String SPOApprovedQuote;                   //合同审批完成的报价
        //songxiaoqi ----------start
        public String IsTermination;                     //true代表合同终止

        //songxiaoqi-----------end
    }

    @HttpPost
    global static void execute() {
        // 取得接口传输内容
        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, 'NFM206', 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 = '{"status": "Success", "Message":'  + gedata + '}';
        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               = 'NFM206';
        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<GeData> accordList = new List<GeData>();
            List<String> opportunity_NoList = new List<String>();
            //合同必填字段验证
            for (GeData gda : geDataList) {
                if (String.isBlank(gda.Opportunity_No)) {
                    iflog.ErrorLog__c += 'Error! 询价编码不能为空。\n';
                    continue;
                }

                if (String.isBlank(gda.ApprovedType)) {
                    iflog.ErrorLog__c += 'Error! 合同申请类型不能为空 [ ' + gda.Opportunity_No + ' ]\n';
                    continue;
                }
                opportunity_NoList.add(gda.Opportunity_No);
                accordList.add(gda);
            }

            List<Opportunity> opportunityUpsertList = new List<Opportunity>();
            List<Opportunity> oppList = [Select Id ,
                                         Opportunity_No__c,
                                         Contract_DB_complite_day__c,
                                         SAP_Send_OK__c,
                                         //Decided_Estimation__c
                                         Estimation_Decision__c,
                                         Estimation_No__c,
                                         Competitor__c,
                                         StageName
                                         from Opportunity
                                         where Opportunity_No__c in : opportunity_NoList];

            Map<String, Opportunity> oppMap = new Map<String, Opportunity>();

            for (Opportunity opp : oppList) {
                oppMap.put(opp.Opportunity_No__c, opp);
            }

            for (GeData gda : accordList) {
                Opportunity opportunityInfo = new Opportunity();
                if (oppMap.containsKey(gda.Opportunity_No)) {
                    opportunityInfo = oppMap.get(gda.Opportunity_No);
                } else {
                    iflog.ErrorLog__c += '询价编码不存在[ ' + gda.Opportunity_No + ' ]\n';
                    continue;
                }
                logstr += '询价编码：' + gda.Opportunity_No + ' 用户操作类型：' + gda.ApprovedType + ' 合同申请类型：' + gda.ContractType ;

                if (gda.ApprovedType == '3' && (gda.ContractType == '3' || gda.ContractType == '2')) {
                    continue;
                }
                opportunityInfo.IF_Submit__c = false;
                opportunityInfo.if_Interface_Lock__c = false;
                opportunityInfo.Contract_Authorize_Lock__c = false;

                if (((gda.ContractType == '3' && gda.ApprovedType != '3') ||
                        (gda.ApprovedType == '3' && gda.ContractType == '1'))
                        && opportunityInfo.StageName == '引合') {

                    //新申请合同的撤销 或者最终取消合同时，清空合同信息
                    opportunityInfo.NotesApprovedNo__c                    = null;
                    opportunityInfo.Contract_DB_request_reason__c         = null;
                    opportunityInfo.Contract_DB_complite_day__c           = null;
                    opportunityInfo.Assistant_Applied_Date__c             = null;
                    opportunityInfo.Contract_DB_SalesDept_complite_day__c = null;
                    opportunityInfo.Contract_DB_Finalcomplite_day__c      = null;
                    opportunityInfo.SPOApprovedQuote__c                   = null;//add

                    // 20211206 SWAG-C7P4XB 撤销合同时，如果当前询价等级为A1，退回到A start
                    if ('A1'.equals(opportunityInfo.Competitor__c)) {
                        opportunityInfo.Opportunity_stage__c = '确定了OLY参数';
                        opportunityInfo.Competitor__c = 'A';
                    }
                    // 20211206 SWAG-C7P4XB 撤销合同时，如果当前询价等级为A1，退回到A end

                    if (gda.ContractType == '3') {
                        opportunityInfo.Contract_Invalid_Date__c = NFMUtil.parseStr2Date(gda.Contract_DB_complite_day);
                    }

                } else if (gda.ContractType == '2' && gda.ApprovedType != '3') {
                    // 变更合同（未撤销）
                    opportunityInfo.Contract_DB_Finalcomplite_day__c = NFMUtil.parseStr2Date(gda.Contract_DB_complite_day);
                    opportunityInfo.Contract_Authorize_Lock__c = true;

                } else if (gda.ContractType == '1' && gda.ApprovedType != '3') {
                    // 新建合同（未撤销）
                    opportunityInfo.NotesApprovedNo__c = gda.NotesApprovedNo;
                    opportunityInfo.Contract_DB_request_reason__c = gda.Contract_DB_request_reason;
                    opportunityInfo.Contract_DB_complite_day__c = NFMUtil.parseStr2Date(gda.Contract_DB_complite_day);
                    opportunityInfo.Assistant_Applied_Date__c = NFMUtil.parseStr2Date(gda.Assistant_Applied_Date);
                    opportunityInfo.Closing_Bid_Date__c  = NFMUtil.parseStr2Date(gda.Closing_Bid_Date);
                    opportunityInfo.Contract_DB_SalesDept_complite_day__c = NFMUtil.parseStr2Date(gda.Contract_DB_SalesDept_complite_day);
                    opportunityInfo.Contract_Invalid_Date__c = null;
                    opportunityInfo.Contract_Authorize_Lock__c = true;
                    if (gda.Contract_DB_complite_day == null) {
                        opportunityInfo.if_Interface_Lock__c = true;
                    }
                    opportunityInfo.SPOApprovedQuote__c = gda.SPOApprovedQuote;//add
                }
                //songxiaoqi ------start 2020/11/4 update 状态1是询价
                //传入true代表合同终止  StageName__c

                if (gda.IsTermination == 'true' && opportunityInfo.Estimation_Decision__c == true && gda.SPOApprovedQuote == opportunityInfo.Estimation_No__c && opportunityInfo.StageName == '引合') {

                    //决定报价deide
                    opportunityInfo.Estimation_Decision__c = false;
                    //清空确定备货确认日
                    opportunityInfo.Stock_Confrim_Date__c = null;
                    //取消win
                    opportunityInfo.SAP_Send_OK__c = false;

                    //撤销操作清空相关内容
                    opportunityInfo.NotesApprovedNo__c                    = null;
                    opportunityInfo.Contract_DB_request_reason__c         = null;
                    opportunityInfo.Contract_DB_complite_day__c           = null;
                    opportunityInfo.Assistant_Applied_Date__c             = null;
                    opportunityInfo.Contract_DB_SalesDept_complite_day__c = null;
                    opportunityInfo.Contract_DB_Finalcomplite_day__c      = null;
                    opportunityInfo.SPOApprovedQuote__c                   = null;
                }
                //songxiaoqi -------end
                opportunityUpsertList.add(opportunityInfo);
            }
            if (opportunityUpsertList.size() > 0) {
                upsert opportunityUpsertList;
            }
            logstr += '\nend';
            rowData.retry_cnt__c = 0;
        } catch (Exception ex) {
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM206_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM206_' + 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;
    }
}