package com.wmyun.module.shipping.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wmyun.module.shipping.exception.ShippingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @Description: 获取云当网访问token
 * @Date: 2025/3/10 15:04
 * @Created: by ZZSLL
 */

@Service
@Slf4j
public class YunDangAuthServiceImpl implements YunDangAuthService{

    @Value("${yundang.baseUrl}")
    private String baseUrl;

    @Value("${yundang.companyId}")
    private String companyId;

    @Value("${yundang.appSecret}")
    private String secret;

    @Override
    @Cacheable(value = "shipping", key = "'access_token#3000#'")
    public String getAccessToken() {
        JSONObject data = new JSONObject();
        data.put("companyid", companyId);
        data.put("secret", secret);
        JSONObject body = new JSONObject();
        body.put("data", JSONObject.toJSONString(data));
        // response
        String url = baseUrl + "/authorization";
        log.info("[请求云当网] METHOD: {}, PATH: {}, Body: {}", "POST", url, body.toJSONString());
        String response = HttpUtil.post(url, body);
        log.info("[请求云当网] Response: {}", response);
        JSONObject resp = JSON.parseObject(response);
        if (resp.containsKey("status")) {
            if (resp.getInteger("status") == 0) {
                if (resp.containsKey("token")) {
                    return resp.getString("token");
                }
            }
        }
        throw new ShippingException(String.format("[云当网访问异常]：执行方法 {%s}, 返回结果 {%s}", this.getClass().getName(), response));
    }
}
