package com.tzy.common.utils.http.forest.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.reflection.ForestMethod;
import com.tzy.common.exception.ServiceException;
import com.tzy.common.utils.http.forest.param.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.TreeMap;

/**
 * @author by po'yi
 * @Description saas服务调用
 * @Date 2023/12/28 16:47
 */
@Component
@Slf4j
public class SaasInterceptor implements Interceptor<ResultDTO> {

	@Value("${tenant.appid:1658744039}")
	private String appid;
	@Value("${tenant.secretKey:f58b968b920aa0dbff34fbc0abb7f2a0}")
	private String secretKey;

	@Override
	public void onInvokeMethod(ForestRequest request, ForestMethod method, Object[] args) {
		JSONObject arg = (JSONObject) args[2];
		arg.put("appid",appid);
		arg.put("timestamp",System.currentTimeMillis());
		arg.put("sign",buildSign(arg));
		log.debug("请求参数:{}",arg);
		request.addBody(arg.toJSONString());
	}

	private String buildSign(JSONObject param){
		TreeMap<String, Object> signData = new TreeMap<>(param);
		StringBuilder buf = new StringBuilder();
		signData.forEach((k, v) -> buf.append(k).append("=").append(v == null ? "" : v).append("&"));
		buf.append("secret=").append(secretKey);
		return DigestUtils.md5Hex(buf.toString());
	}


	@Override
	public void onSuccess(ResultDTO data, ForestRequest request, ForestResponse response) {
		if(data.getCode()!=1){
			throw new ServiceException(500,data.getMsg());
		}
		Interceptor.super.onSuccess(data, request, response);
	}
}
