package com.hfkj.channel.tianque.utils;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.tianque.config.TianQueConfig;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.IdentifyUtil;

import java.io.File;
import java.util.*;

/**
 * @className: RequestUtil
 * @author: HuRui
 * @date: 2023/8/23
 **/
public class RequestUtil {

    /**
     * 请求
     * @param reqData
     * @return
     */
    public static JSONObject request(String url,Map<String,Object> reqData) {
        Map<String,Object> header = new HashMap<>();
        header.put("Content-Type", "application/json");

        TreeMap<String,Object> treeMap = new TreeMap();
        treeMap.putAll(reqData);

        Map<String,Object> param = new LinkedHashMap<>();
        param.put("orgId", TianQueConfig.orgId);
        param.put("reqData", JSONObject.toJSON(reqData));
        param.put("reqId", IdentifyUtil.getGuid());
        param.put("signType", "RSA");
        param.put("timestamp", DateUtil.date2String(new Date(), "yyyyMMddHHmmss"));
        param.put("version", "1.0");
        param.put("sign", RSASignature.encryptBASE64(RSASignature.sign(RSASignature.getContent(param), TianQueConfig.priKey)));

        JSONObject response = HttpsUtils.doPost(url, param, header);
        System.out.println("请求参数：" + JSONObject.toJSONString(param));
        System.out.println("响应参数：" + response);
        if (response != null && !"0000".equals(response.getString("code"))) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("msg"));
        }
        // 验证签名
        String resSign = response.getString("sign");
        response.remove("sign");
        if (!RSASignature.doCheck(RSASignature.getContent(JSONObject.toJavaObject(response, Map.class)), resSign, TianQueConfig.pubKey)) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "响应参数签名失败");
        }
        return response.getJSONObject("respData");
    }

    /**
     * 文件上传请求
     * @param file
     * @return
     */
    public static JSONObject requestUpload(String pictureType,File file) {
        Map<String,Object> param = new HashMap<>();
        param.put("orgId", TianQueConfig.orgId);
        param.put("reqId", IdentifyUtil.Guid);
        param.put("pictureType", pictureType);
        JSONObject response = HttpsUtils.doPostUpload(TianQueConfig.requestUrl + "/merchant/uploadPicture", file, param);
        if (response != null && !"0000".equals(response.getString("code"))) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("msg"));
        }
        return response.getJSONObject("respData");
    }
}
