public with sharing class NFM512Controller {
    public static String status1;
    public static String status;
    public static Integer MaxLogColumnLength = 131072;

    // public class OnlineSigns {
    //     public NFMUtil.Monitoring Monitoring;
    //     public OnlineSign[] OnlineSign;
    // }
    public class OnlineSign {
        public String sfdcCode;        //SFDC 编码(必填)
        public String projectStage;    //项目阶段
        public String projectName;     //项目名称
        public String tenderNum;       //招标编号
        public String tenderOrg;       //招标单位
        public String winBidOrg;       //中标单位
        public String dataCreateTime;  //创建日期
        public String dataRecordTime;  //结果记录日
        public String pubdate;         //发布时间
        public String relatedIf;         //是否相关  //20231226
    }

     /**
     * NFM512の送信処理
     * 
     * @param iflog_Id          //日志表的ID
     * @param tenderList  //要发送的招标项目的ID
     */
    @future (callout=true)
    public static void callout(String iflog_Id, List<String> tenderList) {
        executeNotFuture(iflog_Id, tenderList);
    }

    public static void executeNotFuture(String iflog_Id, List<String> tenderList) {

        if (tenderList == null || tenderList.size() == 0) {
            return;
        }
        //MessageGroupNumber的获取
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        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];
        } else{
            iflog.MessageGroupNumber__c = nowStr;
        }
        iflog.Log__c = 'callout start\n';
        iflog.Type__c = 'NFM512';
        iflog.ErrorLog__c = '';
        String logstr = iflog.Log__c + '\nNumberOfRecord=' + tenderList.size();

        //Monitoring的设定
        // OnlineSigns onlineSigns = new OnlineSigns();
        // onlineSigns.Monitoring = new NFMUtil.Monitoring();
        // onlineSigns.Monitoring.TransmissionDateTime = nowStr;
        // onlineSigns.Monitoring.Text                 = ''; 
        // onlineSigns.Monitoring.Tag                  = 'MSGH';
        // onlineSigns.Monitoring.Sender               = 'SFDC';
        // onlineSigns.Monitoring.Receiver             = 'QLM';
        // onlineSigns.Monitoring.NumberOfRecord       = '' + tenderList.size();
        // onlineSigns.Monitoring.MessageType          = 'NFM512';
        // onlineSigns.Monitoring.MessageGroupNumber   = iflog.Name;

        BatchIF_Log__c rowData = new BatchIF_Log__c();
        try {
            List<Tender_information__c> tenList = [
                Select id,name,TenderManageCode__c,InfoType__c,InfoTitle__c,XmNumber__c,
                       ZhaoBiaoUnit1__c,ZhongBiaoUnit1__c,CreatedDate,ResultDate__c,
                       InfoPublishTime__c,IsRelateProject__c 
                From Tender_information__c 
                Where Id IN :tenderList];
            System.debug('lt789---tenList:' + tenList);

            List<OnlineSign> onsList = new List<OnlineSign>();
            // onlineSigns.OnlineSign = new List<OnlineSign>();
            for(Tender_information__c ten : tenList){
                OnlineSign onlineSign = new OnlineSign();

                onlineSign.sfdcCode = ten.TenderManageCode__c;
                onlineSign.projectStage = ten.InfoType__c;
                onlineSign.projectName = ten.InfoTitle__c;  //Name?
                onlineSign.tenderNum = ten.XmNumber__c;
                onlineSign.tenderOrg = ten.ZhaoBiaoUnit1__c;
                onlineSign.winBidOrg = ten.ZhongBiaoUnit1__c;
                onlineSign.dataCreateTime = String.valueOf(ten.CreatedDate);
                onlineSign.dataRecordTime = String.valueOf(ten.ResultDate__c);
                onlineSign.pubdate = String.valueOf(ten.InfoPublishTime__c);
                onlineSign.relatedIf = ten.IsRelateProject__c; //20231226

                onsList.add(onlineSign);
            }
            System.debug('lt789---onsList.size:' + onsList.size());
            System.debug('lt789---onsList:' + onsList);

            if(onsList.size() > 0){
                // NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
                // Monitoring.Tag                  = onlineSigns.Monitoring.Tag;
                // Monitoring.Sender               = onlineSigns.Monitoring.Sender;
                // Monitoring.Receiver             = onlineSigns.Monitoring.Receiver;
                // Monitoring.MessageType          = onlineSigns.Monitoring.MessageType;
                // Monitoring.MessageGroupNumber   = onlineSigns.Monitoring.MessageGroupNumber;
                // Monitoring.NumberOfRecord       = onlineSigns.Monitoring.NumberOfRecord;
                // Monitoring.TransmissionDateTime = onlineSigns.Monitoring.TransmissionDateTime;
                // Monitoring.Text                 = '';
                rowData = makeRowData(rowData, 'NFM512', onsList);
                execute(rowData, iflog);
            }
            logstr += '\nend';
        } catch(Exception ex) {
            System.debug(Logginglevel.ERROR, 'NFM512_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM512_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
        }
        System.debug('lt789---rowData:' + rowData);
        if (rowData != null) {
            rowData.Type__c = 'NFM512';
            upsert rowData;
            System.debug('哈哈哈---rowData:' + rowData);
        }

        iflog.Log__c = logstr;
        upsert iflog;
    }

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

        //511token
        BatchIF_Transfer__c tokeninfo = null;
        BatchIF_Transfer__c indexinfo = null;
        Boolean updateToken = false; // 是否更新token

        Datetime nowDT = Datetime.now();
        Long nowM = Long.valueOf(nowDT.format('yyyyMMddHHmm'));
        Long nowD = Long.valueOf(nowDT.format('yyyyMMdd'));
        String yestoday = system.now().addDays(-1).format('yyyy-MM-dd') + ' 00:00:00';
        //511token

        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        // OnlineSigns onlineSigns = (OnlineSigns) JSON.deserialize(rowDataStr, OnlineSigns.class);
        String logstr = ' start\n';
        Boolean needUpdateIflog = false;
        if (iflog == null || Test.isRunningTest()) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();      
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
        } else {
            logstr = iflog.Log__c;
        }
        iflog.Type__c = 'NFM512';
        // iflog.MessageGroupNumber__c = onlineSigns.Monitoring.MessageGroupNumber;

        try{

            //511token
            //1 获得token  //和当前任务页数数据
            String token;
            String loginNo;
            String systemId;
            tokeninfo = [Select ID, NFM501_Token__c,LastModifiedDate FROM BatchIF_Transfer__c
                                        Where Table__c = 'NFM511Token512' limit 1];
            // indexinfo = [Select ID, Internal_Value__c,LastModifiedDate FROM BatchIF_Transfer__c
            //                             Where Table__c = 'NFM511GainEndTime' limit 1];

            Long lastModM = tokeninfo == null ? 0 : Long.valueOf(tokeninfo.LastModifiedDate.format('yyyyMMddHHmm'));
            Long lastModD = tokeninfo == null ? 0 : Long.valueOf(tokeninfo.LastModifiedDate.format('yyyyMMdd'));
            String[] tokeninfos = null;

            //2 判断是否要取新token
            if (nowM - lastModM > 15) {
                String tokennew = getZCToken();
                System.debug('token: ' + tokennew);
                Map<String, Object> tr = (Map<String, Object>) JSON.deserializeUntyped(tokennew);
                System.debug('tr: ' + tr);
                Map<String, Object> retdata = (Map<String, Object>) tr.get('data');
                System.debug('retdata: ' + retdata);
                String strtokeninfo = (String) retdata.get('access_token') + ';' + retdata.get('loginNo') + ';' + retdata.get('systemId');
                System.debug('strtokeninfo: ' + strtokeninfo);
                if (tokeninfo == null) {
                    tokeninfo = new BatchIF_Transfer__c();
                    tokeninfo.Table__c = 'NFM511Token512';
                }
                tokeninfo.NFM501_Token__c = strtokeninfo;
                updateToken = true;
                tokeninfos = strtokeninfo.split(';');
            } else {
                tokeninfos = tokeninfo.NFM501_Token__c.split(';');
            }
            token = tokeninfos[0];
            loginNo = tokeninfos[1];
            systemId = tokeninfos[2];
            // token写入执行日志
            iflog.Log__c = 'token: ' + token + '\n';
            //511token

            //发送接口
            status = sendToZCRet(token,loginNo,systemId,rowDataStr, NFMUtil.NFM512_ENDPOINT);
            System.debug('lt789---NFM512Log--status:' + status);
            
            //if ('Accepted'.equals(status)) {
            if ('OK'.equals(status1)) {
                logstr += 'status:' + status + '\n';
                rowData.retry_cnt__c = 0;
            }
        } catch (Exception ex) {
            System.debug(Logginglevel.ERROR, 'NFM512_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM512_' + 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++;
                // LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'错误次数已经超过自动送信设定的最大次数，请手动送信';
            }
        } finally {
            iflog.Log__c = logstr;
    
            if(rowData != null){
                upsert rowData;
            }
            // if(iflog != null){
            //     upsert iflog;
            // }
            if (needUpdateIflog) {
                upsert iflog;
                // upsert rowData;
            }
    
            if (updateToken) {
                upsert tokeninfo;
            }
        }
    }

    // 获得众成数据
    public static String sendToZCRet(String token,String loginNo, String systemId,String rowDataStr, String endpoint) {

        System.debug('嘿哈呼---rowDataStr:' + rowDataStr);
        // 发送接口
        Http http2 = new Http();
        HttpRequest req2 = new HttpRequest();
        HTTPResponse res2;
        String resb2;

        String url = NFMUtil.NFM512_ENDPOINT;
        // url += '?loginNo=' + loginNo;
        // url += '&systemId=' + systemId;

        //NFMUtil.NFM512_ENDPOINT
        req2.setTimeout(110000);
        req2.setMethod('POST');
        req2.setEndpoint(url);
        req2.setBody(rowDataStr);
        req2.setHeader('Authorization', 'Bearer ' + token); //511token
        req2.SetHeader('Content-Type', 'application/json');
        req2.setHeader('loginNo', loginNo);
        req2.setHeader('systemId', systemId);
        System.debug('嘿哈---req2:' + req2);

        res2 = http2.send(req2);
        resb2 = res2.getBody();
        // resb2 = res2.getStatus();
        status1 = res2.getStatus();
        System.debug('lt789---res2.getStatus():' + res2.getStatus());
        System.debug('lt789---resb2:' + resb2);
        return resb2;
    }

    // 获得众成token
    public static String getZCToken() {
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        HTTPResponse res;
        String resb;

        String url = NFMUtil.NFM511_TOKEN_ENDPOINT;
        url += '?username=' + NFMUtil.NFM511_USERNAME;
        url += '&password=' + NFMUtil.NFM511_PASSWORD;
        System.debug('token url: ' + url);
        req.setMethod('GET');
        req.setEndpoint(url);
        if (Test.isRunningTest()) {
            return 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzeXN0ZW1JZCI6IjEwMDEiLCJ1c2VyX25hbWUiOiIxMzY5MDAwMDAxMiIsInVzZXJOYW1lIjoiMTM2OTAwMDAwMTIiLCJsb2dpbk5vIjoiMWZiYzZjZDlkZTIxNGYwZWI3NzUzMTQ5ZDI5MTExM2IiLCJhdXRob3JpdGllcyI6WyIxMDAxNzMiXSwiY2xpZW50X2lkIjoiZUNsb3VkIiwicmVhbE5hbWUiOiLlpaXliKnlt7Tmlq8iLCJncmFudF90eXBlIjoicGFzc3dvcmQiLCJ0b2tlblZlcnNpb24iOm51bGwsInNjb3BlIjpbIjEwMDEiXSwidGVsIjoiMTM2OTAwMDAwMTIiLCJpZCI6IjE2ODkxNzM5NDQ3Mzg4MTE5MDYiLCJleHAiOjE2OTY5MzM1MDAsImp0aSI6Ijg3NjUzMWQ2LTcxMjctNDdiMC1iYzgxLTg4NmMzMDhiZWZiMCJ9.89M_1q6vrIOf1xQYD_omjx9qr49xrY31Hx_rVR5Blv8;1fbc6cd9de214f0eb7753149d291113b;1001';
        }
        // req.setBody('');
        res = http.send(req);
        resb = res.getBody();
        System.debug('511 get token:' + resb);

        return resb;
    }

    public static BatchIF_Log__c makeRowData(BatchIF_Log__c rowData, String NFMType, List<OnlineSign> NFMData) {
        String rowDataStr = JSON.serialize(NFMData);
        System.debug('rowDataStr：'+rowDataStr);
        if (rowDataStr.length() > 0) {
            Integer splitIdx = 1;
            while (rowDataStr.length() > 0) {
                if (splitIdx == 1) {
                    rowData.put('Log__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
                } else if (splitIdx == 13) {
                    if(rowDataStr.length() > MaxLogColumnLength){
                        rowData.ErrorLog__c = '数据量太大。';
                    }else{
                        rowData.ErrorLog__c = rowDataStr;
                    }
                    break;
                } else {
                    rowData.put('Log' + splitIdx + '__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
                }
                splitIdx++;
                rowDataStr = rowDataStr.substring((rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length()));
            }
        }
        return rowData;
    }

    
}