package com.jeequan.jeepay.thirdparty.device.speaker.psSpeaker;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.cache.RedisUtil;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.device.PsSpeakerParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author: ZhuXiao
 * @Description:
 * @Date: 18:20 2021/7/6
*/
@Slf4j
public class PsUtil {

    private final static String REQ_URL = "https://open.zergiot.com/api";

    /**
     * 获取token
     */
    public static String getToken(PsSpeakerParams psSpeakerParams) throws BizException {

        String cacheKey = CS.PINSHENG_TOKEN_CACHE_KEY + "_" + psSpeakerParams.getProviderParams().getUsername();
        String accessToken = RedisUtil.getString(cacheKey);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }

        JSONObject params = (JSONObject) JSONObject.toJSON(psSpeakerParams.getProviderParams());

        JSONObject obj = post("/getToken", params, null);
        if (obj == null) {
            throw new BizException("请求异常，获取token失败");
        }

        accessToken = obj.getString("token");
        log.info("品生云喇叭获取token = {}", accessToken);

        //保存token
        RedisUtil.setString(cacheKey, accessToken, CS.PINSHENG_TOKEN_TIME, TimeUnit.SECONDS);

        return accessToken;
    }

    /**
     * 发起post请求
     */
    public static JSONObject post(String reqUrl, JSONObject reqParams, String token) throws BizException {

        log.info("品生云喇叭请求参数 = {}", reqParams.toJSONString());
        HttpRequest httpRequest = HttpUtil.createPost(REQ_URL + reqUrl).header("token", token).contentType("application/json").timeout(60000);
        String responseStr = httpRequest.body(reqParams.toJSONString()).execute().body();
        log.info("品生云喇叭响应response = {}", responseStr);
        if (StringUtils.isBlank(responseStr)) {
            throw new BizException("请求失败，响应结果为空");
        }

        JSONObject obj = JSONObject.parseObject(responseStr);
        if (!"200".equals(obj.getString("code")) || !obj.getBoolean("success")) {
            throw new BizException("请求失败，errCode:【" + obj.getString("code") + "】,errMsg：" + obj.getString("message"));
        }

        return obj.getJSONObject("data");
    }


}
