package com.hys.app.service.shoptnt;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hys.app.model.shoptnt.ApiParams;
import com.hys.app.model.shoptnt.ShopTntApiEnum;
import com.hys.app.model.shoptnt.ThirdApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ShopTnt HTTP客户端
 *
 * @author 张崧
 * @since 2024-04-02
 */
@Component
public class ShopTntHttpClint {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ShopTntConfig shopTntConfig;

    public ThirdApiResponse execute(ShopTntApiEnum apiEnum, ApiParams apiParams) {
        String paramsJson = apiParams.toJson();
        logger.debug("【请求】ShopTnt接口：{}，参数：{}", apiEnum.getUrl(), paramsJson);

        long timestamp = System.currentTimeMillis();
        HttpResponse httpResponse = HttpUtil.createPost(shopTntConfig.getHttpAddress() + apiEnum.getUrl())
                .header("timestamp", String.valueOf(timestamp))
                .header("sign", createSign(paramsJson, timestamp))
                .body(paramsJson)
                .execute();
        String body = httpResponse.body();

        logger.debug("【响应】ShopTnt接口返回：{}", body);

        ThirdApiResponse thirdApiResponse = new ThirdApiResponse();
        if (httpResponse.isOk()) {
            thirdApiResponse.setSuccess(true);
            thirdApiResponse.setData(body);
        } else {
            JSONObject jsonObject = JSON.parseObject(body);
            thirdApiResponse.setSuccess(false);
            thirdApiResponse.setCode(jsonObject.getString("code"));
            thirdApiResponse.setMsg(jsonObject.getString("message"));
        }

        return thirdApiResponse;
    }

    private String createSign(String paramsJson, long timestamp) {
        HMac mac = new HMac(HmacAlgorithm.HmacSHA256, shopTntConfig.getSignSecret().getBytes());
        return Base64.encode(mac.digest(paramsJson + timestamp));
    }

}
