/**
 * UserToContact.trigger触发
 */
public with sharing class NFM621Controller {

    public static String status;
    private static final String API = '/admin/api/user/saveOlympus';

    public class NFM621 {
        public GeDatas GeDatas;
    }
    public class GeDatas {
        public NFMUtil.MonitoringToComPlat Monitoring;
        public Gedata[] GeData;
    }

    public class GeData {

        public String Name; //姓名
        public String EmployeeNo; //员工编码
        public String Email; //邮件
        public String StayOrNot; //在职状况
        public String JobCategoryPicklist; //职种
        public String StatePlatForm; //省(共通平台）
        public String OnlinePlatformManager; //经理(共通平台)
        public String OnlinePlatformBuchang; //部长(共通平台)
        public String ZongjianApprovalManager; //总监(共通平台)
        public String FederationIdentifier; //联盟ID
        public String BusinessDivision; //本部
        public String Department; //部
        public String GroupDep; //课
        public String State; //省  
        public Date JobStartDate; //入职日期

    }

    /**
     * NFM621の送信処理
     *
     * @param iflog_Id           ログテーブルのId
     * @param userIDs    送信対象取引先
     */
    @future(callout = true)
    public static void callout(String iflog_Id, List < String > userIDs) {
        executefuture(iflog_Id, userIDs);
    }

    public static void executefuture(String iflog_Id, List < String > userIDs) {
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmmss');
        if (userIDs == null || userIDs.size() == 0) {
            return;
        }

        BatchIF_Log__c iflog = null;

        if (string.isNotBlank(iflog_Id)) {
            // MessageGroupNumber の取得
            List < BatchIF_Log__c > iflogList = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id =: iflog_Id];
            if (iflogList.size() > 0) {
                iflog = iflogList.get(0);
                iflog.ErrorLog__c = '';
            } else {
                // データ取れってないとは、rollbackされていることです
                // return;
                iflog = new BatchIF_Log__c();
                iflog.Type__c = 'NFM621';
                iflog.MessageGroupNumber__c = nowStr;
            }
        } else {
            // return;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM621';
            iflog.MessageGroupNumber__c = nowStr;
        }

        //String logstr = iflog.Log__c + '\nNumberOfRecord=' + userIDs.size() + '\n';
        String logstr = 'NumberOfRecord=' + userIDs.size() + '\n';

        // Monitoringの設定
        NFMUtil.MonitoringToComPlat me = new NFMUtil.MonitoringToComPlat();
        me.Tag = 'MSGH';
        me.Sender = 'SFDC';
        me.Receiver = '共通平台/服务新系统';
        me.MessageType = 'NFM621';
        me.MessageGroupNumber = nowStr; //iflog.Name;
        if (String.isNotBlank(iflog.Name)) {
            me.MessageGroupNumber = iflog.Name;
        }
        me.NumberOfRecord = '' + userIDs.size();
        me.TransmissionDateTime = nowStr;
        me.Text = '';
        String randomstr = NFMUtil.randomUUID(16);
        Long timestamp = DateTime.now().getTime();
        String timestampStr = String.valueOf(timestamp);
        String getToken = NFMUtil.getToken(randomstr, timestamp);

        me.API_RANDOM_STR = randomstr;
        me.API_TIME = timestampStr;
        me.API_TOKEN = getToken;

        //OCSM管理省对应自然省
        List < OCM_Management_Province__c > provinceList = [select Id, Name, Real_Province__c, 
                                                            OnlinePlatformWindow1__c, OnlinePlatformWindow2__c, 
                                                            OnlinePlatformWindow3__c from OCM_Management_Province__c];
        Map < String, String > provinceNameMap = new Map < String, String > ();
        for (OCM_Management_Province__c province1: provinceList) {
            if (String.isNotBlank(province1.OnlinePlatformWindow1__c)) {
                provinceNameMap.put(province1.OnlinePlatformWindow1__c, province1.Real_Province__c);
            }
            if (String.isNotBlank(province1.OnlinePlatformWindow2__c)) {
                provinceNameMap.put(province1.OnlinePlatformWindow2__c, province1.Real_Province__c);
            }
            if (String.isNotBlank(province1.OnlinePlatformWindow3__c)) {
                provinceNameMap.put(province1.OnlinePlatformWindow3__c, province1.Real_Province__c);
            }
        }
        BatchIF_Log__c rowData = null;
        GeDatas gds = new GeDatas();
        gds.GeData = new List < GeData > ();
        // endusers.GeData = new List < GeData > ();
        try {
            // 転送データを取得、参照先のデータがあるので、ここで検索必要です。
            List < User > userList = [select Id, Name,
                Employee_No__c,
                Email,
                Stay_or_not__c,
                Job_Category__c,
                OnlinePlatformManager__c,
                OnlinePlatformManager__r.Employee_No__c,
                OnlinePlatformBuchang__c,
                OnlinePlatformBuchang__r.Employee_No__c,
                ZongjianApprovalManager__c,
                ZongjianApprovalManager__r.Employee_No__c,
                FederationIdentifier,
                Salesdepartment__c,
                Category5__c,
                Category6__c,
                Province__c,
                Hire_Date__c,
                QuitDate__c
                from User where Id IN: userIDs All ROWS
            ];
            System.debug(Logginglevel.DEBUG, 'NFM621_ userList.size()=' + userList.size());
            // GeDatasのデータの設定
            for (User user1: userList) {
                GeData info = new GeData();
                info.Name = user1.Name; //名称
                info.EmployeeNo = user1.Employee_No__c; //员工编号
                info.Email = user1.Email; //电子邮件
                info.JobCategoryPicklist = user1.Job_Category__c; //职种 
                info.OnlinePlatformManager = user1.OnlinePlatformManager__r.Employee_No__c; //经理(共通平台)
                info.OnlinePlatformBuchang = user1.OnlinePlatformBuchang__r.Employee_No__c; //部长(共通平台)
                info.ZongjianApprovalManager = user1.ZongjianApprovalManager__r.Employee_No__c; //总监(共通平台) 
                info.FederationIdentifier = user1.FederationIdentifier; //联盟ID
                info.BusinessDivision = user1.Salesdepartment__c; //本部
                info.Department = user1.Category5__c; //部
                info.GroupDep = user1.Category6__c; //课
                info.State = user1.Province__c; //省
                info.JobStartDate = user1.Hire_Date__c; //入职日期

                if (provinceNameMap.containsKey(user1.Id)) {
                    info.StatePlatForm = provinceNameMap.get(user1.Id); //省(共通平台）   
                } else {
                    info.StatePlatForm = '';
                }
                if (user1.QuitDate__c != null && user1.QuitDate__c <= Date.Today()) {
                    info.StayOrNot = '已离职';
                } else {
                    info.StayOrNot = user1.Stay_or_not__c; //在职状况
                }
                logstr += '员工编码:' +info.EmployeeNo+ '\n';
                gds.GeData.add(info);
            }

            if (gds.GeData.size() > 0) {
                me.NumberOfRecord = '' + gds.GeData.size();
                gds.Monitoring = me;

                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 = '';

                NFM621 nfm621 = new NFM621();
                nfm621.GeDatas = new GeDatas();
                nfm621.GeDatas = gds;
                rowData = NFMUtil.makeRowData(Monitoring, 'NFM621', nfm621);
                execute(rowData, iflog);

            }
            logstr += '\nStatus:' + status;
            logstr += '\nend';

        } catch (Exception ex) {
            // エラーが発生した場合
            System.debug(Logginglevel.ERROR, 'NFM621_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM621_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
        }
        if (rowData != null) {
            upsert rowData;
        }

        iflog.Log__c = logstr;
        upsert iflog;
    }

    public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog) {

        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        //String rowDataStr = NFMUtil.getRowDataStr(rowData);
        //GeDatas endusers = (GeDatas) JSON.deserialize(rowDataStr, GeDatas.class);

        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        Boolean needUpdateIflog = false;
        if (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM621';
            iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
        } else {
            logstr = iflog.Log__c;
        }

        try {
            
            // 向共通平台及服务新系统送信
            String data = NFMUtil.getRowDataStr(rowData);
            status = NFMUtil.sendToSapRet(data, NFMUtil.NFM621_ENDPOINT);
            System.debug('NFM621Log--status->' + status);
            if ('Accepted'.equals(status)) {
                logstr += status + '\n';
                rowData.retry_cnt__c = 0;
            } else {
                rowData = NFMUtil.LogAutoSend(rowData, null, status);
            }
            
            // 发送给 AWS 临时 Start
            // status = NFMUtil.sendToAWS(data, API);
            // if ('Created'.equals(status)) {
            //     logstr += status + '\n';
            //     rowData.retry_cnt__c = 0;
            // } else {
            //     // rowData = NFMUtil.LogAutoSend(rowData, null, status);
            // }
            // System.debug('NFM621Log--status->' + status);
            // 发送给 AWS 临时 End

        } catch (Exception ex) {
            // TODO IOException
            // エラーが発生した場合
            System.debug(Logginglevel.ERROR, 'NFM621_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM621_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';

            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c++;
                if(!Test.isRunningTest()){
                    LogAutoSendSchedule.assignOneMinute();
                }
                
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动送信设定的最大次数，请手动送信';
            }
        }
        logstr += '\nStatus:' + status;
        iflog.Log__c = logstr;

        // if (needUpdateIflog) {
        upsert iflog;
        upsert rowData;
        // }
    }

}