package com.rrtx.services.common.http;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rrtx.services.common.hostenv.HostCipherEnvelope;
import com.rrtx.services.common.utils.DateUtil;
import com.rrtx.services.common.utils.TranslateUtil;

import java.util.HashMap;
import java.util.Map;

public class HostSendMsg {
    // true :测试环境 false : 生产环境
    static boolean isDebug = false;
    /**
     * 向核心发送数据
     * @param apiAction 访问的路径
     * @param jsonStr 发送参数
     * @param pageNum 页数
     * @param pageSize 每页记录数
     * @return
     */
    public static String sendMsg(String apiAction, String jsonStr, String pageNum, String pageSize) {
        // 读取本地报文
        if(isDebug) {
            String baowenDizhi = "hostmessage/";
            ClassPathResource classPathResource = new ClassPathResource(baowenDizhi + apiAction.replaceAll("/", "") + ".txt");
            FileReader fileReader = new FileReader(classPathResource.getPath());
            String result = fileReader.readString();
            return result;
        }
        JSONObject maps = (JSONObject)JSON.parse(jsonStr);
        // TODO 参数化
        maps.put("orgNo", "101");// 机构编码
        maps.put("tellerId", "666666");// 柜员号
        maps.put("channelCode", "20");// 管道号
        maps.put("reqJournalNo", RandomUtil.randomString(32));// 请求流水号
        maps.put("reqTransDate", DateUtil.getCurrentDateFormt());// 交易日期
        maps.put("reqTransTime", DateUtil.getCurrentTimeFormt());// 交易时间
        maps.put("txnType", "N");//
        if(pageNum != null) {
            maps.put("pageNum", pageNum);// 页数
            maps.put("pageSize", pageSize);// 每页记录数
        }
        String publicKeyPath = TranslateUtil.val4Sys("HOST_PUBLIC_CERT_PATH");
        String miwen = HostCipherEnvelope.enCode(publicKeyPath, maps.toString());
        Map<String, String> map = new HashMap<String, String>();
        map.put("param", miwen);
        String resMsg = null;
        try {
            String hostUrl = TranslateUtil.val4Sys("HOST_URL");
            resMsg = HttpUtils.sendHttpPost(hostUrl + apiAction, maps.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMsg;
    }

    /**
     * 向核心发送数据
     * @param apiAction 访问的路径
     * @param jsonStr 发送参数
     * @return
     */
    public static String sendMsg(String apiAction, String jsonStr) {
        return sendMsg(apiAction, jsonStr, null,null);
    }
}
