package com.dsk.common.utils;

import com.dsk.acc.openapi.api.AccClient;
import com.dsk.acc.openapi.client.Config;
import com.dsk.acc.openapi.client.util.CommonUtils;
import com.dsk.common.config.DskOpenApiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class DskOpenApiUtil {
	@Autowired
	private DskOpenApiConfig dskOpenApiConfig;

	/**
	 * <b>application/json请求</b>
	 * @param path 请求路径
	 * @param bodyMap 参数体
	 * @return
	 */
	public Map<String,Object> requestBody(String path, Map<String, Object> bodyMap){
		return request(path, bodyMap, "json");
	}

	public Map<String,Object> requestBodyWithHeader(String path, Map<String, Object> bodyMap, Map<String, String> headerMap){
		return requestWithHeader(path, bodyMap, "json", headerMap);
	}

	/**
	 * <b>application/x-www-form-urlencoded请求</b>
	 * @param path 请求路径
	 * @param bodyMap 参数体
	 * @return
	 */
	public Map<String,Object> requestForm(String path, Map<String, Object> bodyMap){
		return request(path, bodyMap, "form");
	}
	
	/**
	 * <b>开放平台统一请求</b>
	 * @param path 请求路径
	 * @param bodyMap 参数体
	 * @param reqBodyType 请求格式
	 * @return
	 */
	public Map<String,Object> request(String path, Map<String, Object> bodyMap, String reqBodyType){
		try {
			AccClient.init(new Config(dskOpenApiConfig.accessKeyId, dskOpenApiConfig.accessKeySecret)
					.setEndpoint(dskOpenApiConfig.endPoint));
			Map<String, ?> res = AccClient.request(reqBodyType, path, bodyMap);
			if(!res.containsKey("headers") || !res.containsKey("body")) {
				throw new RuntimeException(String.format("请求无返回:path=%s",path));
			}
			Object resBody = res.get("body");
			if(resBody == null) {
				return null;
			}
			return CommonUtils.assertAsMap(resBody);
		} catch (Exception e) {
			throw new RuntimeException(String.format("请求异常:path=%s,err=%s",path,e.getMessage()));
		}
	}

	/**
	 * <b>开放平台统一请求</b>
	 * @param path 请求路径
	 * @param bodyMap 参数体
	 * @param reqBodyType 请求格式
	 * @return
	 */
	public Map<String,Object> requestWithHeader(String path, Map<String, Object> bodyMap, String reqBodyType, Map<String, String> headerMap){
		try {
			AccClient.init(new Config(dskOpenApiConfig.accessKeyId, dskOpenApiConfig.accessKeySecret)
					.setEndpoint(dskOpenApiConfig.endPoint));
			Map<String, ?> res = AccClient.request(reqBodyType, path, bodyMap, headerMap);
			if(!res.containsKey("headers") || !res.containsKey("body")) {
				throw new RuntimeException(String.format("请求无返回:path=%s",path));
			}
			Object resBody = res.get("body");
			if(resBody == null) {
				return null;
			}
			return CommonUtils.assertAsMap(resBody);
		} catch (Exception e) {
			throw new RuntimeException(String.format("请求异常:path=%s,err=%s",path,e.getMessage()));
		}
	}

}