public without sharing class NFM613Controller {

    private static final String LOG_TYPE = 'NFM613';
    // private static final String API = '/admin/api/scd/save';
    private static final String API = '/admin/api/repair/save1111111';
    public class NFM613 {
    	public Gedatas Gedatas;
    }
    public class Gedatas {
    	// public applyRepairInfo[] applyRepairInfo;
    	// public problem[] problem;
    	public applyRepairInfo applyRepairInfo;
    	public problem problem;
    }
    public class applyRepairInfo {
    	public String ReportRepairNo;
		public String ReportRepairNo2;
		public String ReportRepairStatus;
		public String returnWayType;
    }
    public class problem {
		public String dateReceiptQuestions; //投诉知悉日（Complaint Aware Date）
		public String ifDeadHurt; //是否有死亡、伤害、感染
		public String problemOccurred; //问题发生时间情况
		public String problemOccurredSelect; //问题发生时间情况 其他
		public String reportAdverseEvents; //医院有没有向政府机关报告不良事件或疑似不良事件
		public String whatProject; //做的是哪个项目
		public String operationOrExaminationName; //手术/检查名称
		public String breakORFallOff; //是否有发生断裂或脱落
		public String useFailProductFinish; //是否用该产品完成了手术/检查
		public String supportingProducts; //配套使用产品
		public String afterFailureInformation; //发现故障后，医院对患者的处理情况
		public String delay15Min; //发现故障现象后，有延误15分钟以上的手术实施的情况发生吗
		public String informationFrom; //信息是从医院的谁那里得到的
		public String failureQInHospital; //在医院，故障发生的频率是多少
		public String delayReportReason; //超时报告的理由
		public String isProductFaultRelated; //是否与这次产品故障相关
    }
    @future(callout = true)
    public static void callout(String iflog_Id, List < String > repairOrderIdList) {
        List < BatchIF_Log__c > iflog = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog_Id];
        String sql = 'Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = \'' + iflog_Id + '\'';
        // List < BatchIF_Log__c > iflog = DataBase.query(sql);
        System.debug(iflog + 'NFM613======');
        if (iflog == null || iflog.size() == 0) {
        	System.debug(iflog + 'NFM613======null');
            executefuture(null, repairOrderIdList);
        } else {
        	System.debug(iflog + 'NFM613======null1');
            executefuture(iflog.get(0), repairOrderIdList);
        }

    }

    public static void executefuture(BatchIF_Log__c iflog, List < String > repairOrderIdList) {
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmmss');
        if (iflog != null) {
            iflog.ErrorLog__c = '';
        } else {
            iflog = new BatchIF_Log__c();
            iflog.Type__c = LOG_TYPE;
            iflog.ErrorLog__c = '';
            iflog.Log__c = 'callout start \n';
            iflog.MessageGroupNumber__c = nowStr;
        }
        BatchIF_Log__c rowData = null;
        List<RepairSubOrder__c> repSoList = new List<RepairSubOrder__c>();
        repSoList = [SELECT Id,
        					Name,
        					Status__c,
        					ReturnWayType__c,
        					RepairOrderNo__c,
        					DateReceiptQuestions__c,
        					IfDeadHurt__c,
        					ProblemOccurred__c,
        					ProblemOccurredSelect__c,
        					ReportAdverseEvents__c,
        					WhatProject__c,
        					OperationOrExaminationName__c,
        					BreakORFallOff__c,
        					UseFailProductFinish__c,
        					SupportingProducts__c,
        					AfterFailureInformation__c,
        					Delay15Min__c,
        					InformationFrom__c,
        					FailureQInHospital__c,
        					DelayReportReason__c,
        					IsProductFaultRelated__c
        					FROM RepairSubOrder__c WHERE Id IN :repairOrderIdList];
        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + repSoList.size() + '\n';
        try{
        	Gedatas geds = new Gedatas();
        	// geds.applyRepairInfo = new List<applyRepairInfo>();
        	// geds.problem = new List<problem>();
        	List < Id > repSoIdList = new List < Id > ();
            for (RepairSubOrder__c repSo: repSoList) {
                repSoIdList.add(repSo.Id);
            }
            for (RepairSubOrder__c repSo : repSoList) {
            	applyRepairInfo info = new applyRepairInfo();
            	problem pro = new problem();
            	info.ReportRepairNo = repSo.RepairOrderNo__c;
            	info.ReportRepairNo2 = repSo.Name;
            	info.ReportRepairStatus = repSo.Status__c;
            	info.returnWayType = repSo.ReturnWayType__c;
            	pro.dateReceiptQuestions = NFMUtil.formatDate2Str(repSo.DateReceiptQuestions__c);
            	pro.ifDeadHurt = repSo.IfDeadHurt__c;
				pro.problemOccurred = repSo.ProblemOccurred__c;
				pro.problemOccurredSelect = repSo.ProblemOccurredSelect__c;
				pro.reportAdverseEvents = repSo.ReportAdverseEvents__c;
				pro.whatProject = repSo.WhatProject__c;
				pro.operationOrExaminationName = repSo.OperationOrExaminationName__c;
				pro.breakORFallOff = repSo.BreakORFallOff__c;
				pro.useFailProductFinish = repSo.UseFailProductFinish__c;
				pro.supportingProducts = repSo.SupportingProducts__c;
				pro.afterFailureInformation = repSo.AfterFailureInformation__c;
				pro.delay15Min = repSo.Delay15Min__c;
				pro.informationFrom = repSo.InformationFrom__c;
				pro.failureQInHospital = repSo.FailureQInHospital__c;
				pro.delayReportReason = repSo.DelayReportReason__c;
				pro.isProductFaultRelated = repSo.IsProductFaultRelated__c;
				// geds.applyRepairInfo.add(info);
				// geds.problem.add(pro);
				geds.applyRepairInfo = info;
				geds.problem = pro;
            }
            System.debug(geds);
            logstr+= 'end';
            // if (geds.applyRepairInfo.size() > 0 || geds.problem.size() > 0) {
            if (geds.applyRepairInfo != null || geds.problem != null) {
            	NFM613 nfm613 = new NFM613();
            	nfm613.Gedatas = geds;
                rowData = NFMUtil.makeRowData(iflog, LOG_TYPE, nfm613);
                execute(rowData,iflog);
            }
        } catch (Exception e) {
            // 发生错误时
            System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + e.getMessage());
            System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + e.getStackTraceString());
            logstr += e.getMessage();
            iflog.ErrorLog__c += e.getMessage() + '\n';
            iflog.ErrorLog__c += e.getStackTraceString() + '\n';
            iflog.Log__c = iflog.Log__c + logstr;
            upsert iflog;
        }
    }

    /**
     * 接口发送失败 根据BatchLogId进行手动发送
     * @Author   XHL
     * @DateTime 2021-07-22
     * @param    rowDataId  [BatchLogId]
     */
    public static void ManualExecute(String rowDataId) {
        List < BatchIF_Log__c > row = [select id, name, MessageGroupNumber__c, retry_cnt__c,
            RowDataFlg__c, ErrorLog__c, Type__c,
            Log__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
            Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c
            from BatchIF_Log__c
            where id =: rowDataId
        ];
        if (row.size() > 0) execute(row[0], null);
    }
    /**
     * 逻辑正常执行发送
     * @Author   XHL
     * @DateTime 2021-07-22
     * @param    rowDataSFDC [BatchLogId]
     * @param    iflog       [执行情况记录]
     */
    public static void execute(BatchIF_Log__c rowDataSFDC, BatchIF_Log__c iflog) {
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);

        String logstr = rowDataSFDC.Name + ' start\n';
        if (iflog == null) {
            iflog = new BatchIF_Log__c();
            iflog.Type__c = LOG_TYPE;
            iflog.MessageGroupNumber__c = rowDataSFDC.MessageGroupNumber__c;
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';

        } else {
            iflog.Type__c = LOG_TYPE;
            iflog.MessageGroupNumber__c = rowDataSFDC.MessageGroupNumber__c;
            logstr = iflog.Log__c;
        }

        try {
            String data = NFMUtil.getRowDataStr(rowDataSFDC);
            String status = NFMUtil.sendToAWS612(data, NFMUtil.NFM613_ENDPOINT);
            System.debug('NFM613Log--status->' + status);

            if ('OK'.equals(status)) {
                logstr += status + '\n';
                rowDataSFDC.retry_cnt__c = 0;
            } else {
                logstr += 'status:' + status + '\n';
                if (rowDataSFDC.retry_cnt__c == null) rowDataSFDC.retry_cnt__c = 0;
                if (rowDataSFDC.retry_cnt__c < batch_retry_max_cnt) {
                    rowDataSFDC.retry_cnt__c++;
                    // LogAutoSendSchedule.logId = rowDataSFDC.Id;
                    LogAutoSendSchedule.assignOneMinute();
                }
                if (rowDataSFDC.retry_cnt__c >= batch_retry_max_cnt) {
                    rowDataSFDC.ErrorLog__c = 'status:' + status +
                                          '\n错误次数已经超过自动送信设定的最大次数，请手动送信';
                }
            }

        } catch (Exception ex) {
            // TODO IOException
            // 错误发生时
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
            if(!Test.isRunningTest()){
                // rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, ex, null);    //2022-06-24   zyh   注释：重发逻辑修改
                //2022-06-24   zyh   update   start
                if (rowDataSFDC.retry_cnt__c == null) rowDataSFDC.retry_cnt__c = 0;
                if (rowDataSFDC.retry_cnt__c < batch_retry_max_cnt){
                    rowDataSFDC.retry_cnt__c++;
                    // LogAutoSendSchedule.logId = rowDataSFDC.Id;
                    LogAutoSendSchedule.assignOneMinute();
                }
                if (rowDataSFDC.retry_cnt__c >= batch_retry_max_cnt){
                    rowDataSFDC.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowDataSFDC.ErrorLog__c+'错误次数已经超过自动送信设定的最大次数，请手动送信';
                }
                //2022-06-24   zyh   update   end
            }
        }
        iflog.Log__c = logstr;
        upsert iflog;
        upsert rowDataSFDC;
    }
}