global with sharing class NFM702Controller {

    private static final String LOG_TYPE = 'NFM702';

    public static String logstr;
    public static String status;   
    public static String ResponseBody;
    public static String Result;

    public NFM702Controller() {

    }

    public class Response {
        public Result Result;
    }

    public Class Result{
        public String Result;
        public String Message;
    }

    public class NFM702 {
        public NFMUtil.Monitoring Monitoring;
        public GeData[] GeData;
    }

    // public Class GeDatas {
    //     public NFMUtil.Monitoring Monitoring;
    //     public GeData[] GeData;
    // }

    public Class GeData {
        public String StaffMCode;   //人员管理编码
        public String HospitalName;     //医院名称
        public String OfficeName;   //科室名称
        public String Name;    //姓名
        public String Mobile;   //电话
        public String HcpNo;    //HPC编码
        public Boolean IsActive;    //是否有效
        public String UpdateStatus;     //操作类型
    }

    @future(callout = true)
    public static void callout( String iflog_Id, List < String > accIdList ){
        executeNotFuture(iflog_Id, accIdList);
    }

    public static void executeNotFuture(String iflog_Id, List < String > accIdList) {
        
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmmss');
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        if (string.isNotBlank(iflog_Id)) {
            iflog = [Select Id, Name, Log__c, ErrorLog__c,MessageGroupNumber__c from BatchIF_Log__c where Id =: iflog_Id];
        }
        iflog.MessageGroupNumber__c = String.isBlank(iflog.Id)?nowStr:iflog.MessageGroupNumber__c;
        iflog.Log__c = 'callout start\n';
        iflog.Type__c = LOG_TYPE;
        iflog.ErrorLog__c = '';

        NFM702 gds = new NFM702();
        gds.GeData = new List < GeData >();

        BatchIF_Log__c rowData = null;

        List<Contact> conList = [select Id,
                                        CManageCode__c,     //人员管理编码
                                        Account.Hospital_Name__c,       //医院名称
                                        Account.Department_Name__c,       //科室名称
                                        Name,       //姓名
                                        Phone,      //电话
                                        HcpNo__c,       //HCP编码
                                        Isactive__c,    //是否有效
                                        UpdateStatus__c            //操作类型
                                        from Contact WHERE Id IN:accIdList order by Id];  //AccountId
        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + conList.size() + '\n';

        NFMUtil.Monitoring mon = new NFMUtil.Monitoring();
        mon.Tag                = 'MSGH';
        mon.Sender 				 = 'SFDC';
		mon.Receiver 			 = 'OBPM';
		mon.MessageType 		 = 'NFM702';
		mon.MessageGroupNumber 	 = nowStr;
		mon.NumberOfRecord 		 = '' + accIdList.size();
		mon.TransmissionDateTime = nowStr;
		mon.Text = '';


        try{
            for( Contact con : conList ){
                GeData ged = new GeData();
                ged.StaffMCode = con.CManageCode__c;
                ged.HospitalName = con.Account.Hospital_Name__c;
                ged.OfficeName = con.Account.Department_Name__c;
                ged.Name = con.Name;
                ged.Mobile = con.Phone;
                ged.HcpNo = con.HcpNo__c;
                ged.IsActive = '有效'.equals(con.Isactive__c)? true:false;
                ged.UpdateStatus = con.UpdateStatus__c;
                gds.GeData.add(ged);
            }

            logstr += '\nend';

            if(gds.GeData.size()>0){

                mon.NumberOfRecord = '' + gds.GeData.size();
                gds.Monitoring = mon;

                logstr = iflog.Log__c + '\nNumberOfRecord=' + gds.GeData.size();
                NFMUtil.Monitoring Monitoring = new NFMUtil.Monitoring();
                Monitoring.Tag                  = gds.Monitoring.Tag;
                Monitoring.Sender               = gds.Monitoring.Sender;
                Monitoring.Receiver             = gds.Monitoring.Receiver;
                Monitoring.MessageGroupNumber   = gds.Monitoring.MessageGroupNumber;
                Monitoring.MessageType          = gds.Monitoring.MessageType;
                Monitoring.NumberOfRecord       = gds.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = gds.Monitoring.TransmissionDateTime;
                Monitoring.Text = '';

                NFM702 nfm702 = new NFM702();
                nfm702.GeData = new List <GeData>();
                nfm702.GeData = gds.GeData;
                nfm702.Monitoring = new NFMUtil.Monitoring();
                nfm702.Monitoring = Monitoring;

                rowData = NFMUtil.makeRowData(iflog, LOG_TYPE, nfm702);
                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;
        }

        if (rowData != null) {
            upsert rowData;
        }

        System.debug(Logginglevel.DEBUG, 'NFM702_' + iflog.Name + ' end');
        iflog.Log__c = iflog.Log__c + logstr;

        upsert iflog;
    }

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

    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 rowDataStr = NFMUtil.getRowDataStr(rowDataSFDC);
        String logstr = rowDataSFDC.MessageGroupNumber__c + ' 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 {

            NFMUtil.response response = NFMUtil.sendToSapStatusAndBody(rowDataStr, NFMUtil.NFM702_ENDPOINT);
            System.debug('NFM702Log--status->'+ status);

            status = response.status;
            ResponseBody = response.responseBody;
            Response resultList = ( Response ) JSON.deserializeStrict(ResponseBody, Response.class);
            System.debug('NFM702Log--status->'+ ResponseBody);

            Result = resultList.Result.Result;

            if ('00'.equals(Result)) {
                logstr += ResponseBody+'\n';
                rowDataSFDC.retry_cnt__c = 0;
                //iflog.Log__c = 'ok';
            } 
            else {
                //iflog.Log__c = 'ok2';
                rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, null, status);
            }

        }catch ( Exception ex ) {
           //打印错误日志
           System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + ex.getMessage());
           System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + ex.getStackTraceString());

           logstr = ex.getMessage();
           iflog.ErrorLog__c += ex.getMessage() + '\n';
           iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
           if(!Test.isRunningTest()){
                //rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, null, status);
           }
        }

        iflog.Log__c = iflog.Log__c + logstr;
        upsert iflog;
        upsert rowDataSFDC;
    }
}