public without sharing class NFM701Controller {

    private static final String LOG_TYPE = 'NFM701';
    // private static final String API = '/admin/api/repair/save';
    public static String logstr;
    public static String status;      
    public static String ResponseBody;
    public static String Result;
    public static boolean isRunning = false;
    // public NFM701Controller() {
        
    // }
    public class Response {
        public Result Result;
    }
    public Class Result{
        public String Result;
        public String Message;
    }
    public class NFM701 {
        // public GeDatas GeDatas;
        public NFMUtil.Monitoring Monitoring;
        public GeData[] GeData;
        
    }
    public Class GeData {
    	public String DataType; //数据类型 == RecordType
		public String HospitalMCode; //医院管理编码 == Parent_Management_Code__c +Management_Code__c+
		public String HospitalName; //医院名称 == Name
		public Boolean IsActive; //是否有效 == Is_Active_Formula__c
		public String Address; //地址 == Address__c
		public String StateMaster; //省 == State_Master__c
		public String CityMaster; //市 == City_Master__c
		public String Grade; //政府等级 == Grade__c
		public Boolean IsMerge; //是否合并
		public String LinkedHospitalMCode; //合并指向医院的管理编码
		//select Id,Management_Code__c,Hospital_Name__c,Is_Active__c,Address__c,State_Master__r.Name,City_Master__r.Name,Grade__c from Account limit 100
	}
    @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 = '';
        NFM701 gds = new NFM701();
        gds.GeData = new List < GeData > ();
        BatchIF_Log__c rowData = null;
        List<Account> accList = [SELECT Id,
                                        Name,
    									Address__c,
    									RecordTypeId,
                                        Parent_Management_Code__c,
                                        Ban_On_Use_Reason__c,
    									State_Master__r.Name,
    									City_Master__r.Name,
                                        RecordType.DeveloperName,
                                        Is_Active_Formula__c,
    									Grade__c 
                                    FROM Account 
                                    WHERE  id IN: accIdList 
                                ];
	    String logstr =  ' ' + 'NumberOfRecord=' + accList.size() + '\n';
        NFMUtil.Monitoring mon = new NFMUtil.Monitoring();
        mon.Tag 				 = 'MSGH';
		mon.Sender 				 = 'SFDC';
		mon.Receiver 			 = 'OBPM';
		mon.MessageType 		 = 'NFM701';
		mon.MessageGroupNumber 	 = nowStr;
		mon.NumberOfRecord 		 = '' + accIdList.size();
		mon.TransmissionDateTime = nowStr;
		mon.Text = '';
        try {
        	for (Account acc : accList) {
                GeData ged = new GeData();
                ged.DataType            = acc.RecordType.DeveloperName.equals('HP') ? 'Hospital':'Office';//数据类型
                ged.HospitalMCode       = acc.Parent_Management_Code__c;     //医院管理编码
                ged.HospitalName        = acc.Name;        //医院名称
                ged.IsActive            = '有效'.equals(acc.Is_Active_Formula__c) ? true:false;
				ged.Address             = acc.Address__c;                   //地址
				ged.StateMaster         = acc.State_Master__r.Name;     //省
				ged.CityMaster          = acc.City_Master__r.Name;       //市
				ged.Grade               = acc.Grade__c;
                ged.LinkedHospitalMCode = '';
                ged.IsMerge             = false;
				if (acc.RecordType.DeveloperName.equals('HP') && ged.IsActive == false) {
                    if (String.isNotBlank(acc.Ban_On_Use_Reason__c) && digitalVerification(acc.Ban_On_Use_Reason__c)) {
                        ged.IsMerge = true;                         //是否合并
                        ged.LinkedHospitalMCode = acc.Ban_On_Use_Reason__c;//合并指向医院的管理编码
                    }
                }
                gds.GeData.add(ged);
    		}
            logstr += '\nend';
            if (gds.GeData.size() > 0) {
                mon.NumberOfRecord       = '' + gds.GeData.size();
                gds.Monitoring = mon;
                logstr = '\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.MessageType          = gds.Monitoring.MessageType;
                Monitoring.MessageGroupNumber   = gds.Monitoring.MessageGroupNumber;
                Monitoring.NumberOfRecord       = gds.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = gds.Monitoring.TransmissionDateTime;
                Monitoring.Text                 = '';

                NFM701 nfm701 = new NFM701();
                nfm701.GeData = new List < GeData >();
                nfm701.GeData = gds.GeData;
                nfm701.Monitoring = new NFMUtil.Monitoring();
                nfm701.Monitoring = Monitoring;
                // GeDatas gds = new GeDatas();

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

        System.debug(Logginglevel.DEBUG, 'NFM701_' + iflog.Name + ' end');
        iflog.Log__c = iflog.Log__c + logstr;
        // 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.NFM701_ENDPOINT);
            status = response.status;
            ResponseBody = response.responseBody;
            Response resultList = ( Response ) JSON.deserializeStrict(ResponseBody, Response.class);
            System.debug('NFM701Log--status->'+ ResponseBody);
            // status = '';
            // NFM701Response NFM701Response = new NFM701Response();
            // Response response1 = new Response();
            // system.debug(ResponseBody);
            // if (string.isNotEmpty(ResponseBody)) {
            //     // List < GeData >
            //     // response1 = (Response) JSON.deserializeStrict(ResponseBody, Response.class);
            //      Result resultList = ( Result ) JSON.deserializeStrict(ResponseBody, Result.class);
            //     System.debug('resultList---->'+resultList);
            // }
            // if (response1.Result != null &&
            //         response1.Result.size() > 0 &&
            //         response1.Result[0].Result != null &&
            //         string.isNotEmpty(response1.Result[0].Result)) {
            //     Result = response1.Result[0].Result;

            // }
            Result = resultList.Result.Result;
            // if ('00'.equals(ResponseBody)) {
            // if ('00'.equals(Result)) {
            // if (ResponseBody.contains('00')) {
            if (Result.equals('00')) {
                // logstr += status+'\n';
                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) {
            // TODO IOException
            // エラーが発生した場合
            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 =  logstr;
        upsert iflog;
        upsert rowDataSFDC;

    }
    // 验证医院禁用理由是否是纯数字，是 医院管理编码
    public static Boolean digitalVerification(String ban_On_Use_Reason) {
        Boolean result = false;
        Pattern pattern = Pattern.compile('^[0-9]*$');
        Matcher isNum = pattern.matcher(ban_On_Use_Reason);
        if (isNum.matches()) {
            result = true;
        }

        return result;
    }
}