package com.jjt.utils;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import com.jjt.common.constant.CacheConstants;
import com.jjt.common.core.redis.RedisCache;
import com.jjt.common.core.text.Convert;
import com.jjt.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * IotServiceImpl$
 *
 * @author wukai
 * @date 2024/5/4 20:35
 */
@Component
@Slf4j
public class IotService {
    @Resource
    private RedisCache redisCache;
    @Value("${iot.uri}")
    private String uri;
    @Value("${iot.tenantId}")
    private String tenantId;
    @Value("${iot.username}")
    private String username;
    @Value("${iot.password}")
    private String password;
    @Value("${iot.authorization}")
    private String authorization;

    /**
     * 查询数据
     *
     * @param sql sql语句
     * @return JSON数据
     */
    public JSONObject query(String sql) {
        String uri = this.uri + "/api/cnv-device/data-point/timeseries/query";
        JSONObject object = new JSONObject();
        object.set("sql", sql);
        HttpRequest request = HttpUtil.createPost(uri);
        request.setMethod(Method.POST);
        request.header("Blade-Auth", "bearer " + getToken());
        request.body(object.toString());
        return IotTools.getData(request);
    }

    /**
     * 获取token
     *
     * @return token
     */
    public void setToken() {
        redisCache.setCacheObject(CacheConstants.IOT_TOKEN, queryToken());
    }

    /**
     * 获取token
     *
     * @return token
     */
    public String getToken() {
        String token = Convert.toStr(redisCache.getCacheObject(CacheConstants.IOT_TOKEN));
        if (StringUtils.isNotEmpty(token)) {
            return token;
        }
        token = queryToken();
        redisCache.setCacheObject(CacheConstants.IOT_TOKEN, token);
        return token;
    }

    private String queryToken() {
        String uri = this.uri + "/api/blade-auth/oauth/token";
        Map<String, Object> map = new HashMap<>(16);
        map.put("tenantId", tenantId);
        map.put("username", username);
        map.put("password", MD5.create().digestHex(password));
        HttpRequest request = HttpUtil.createPost(uri);
        request.setMethod(Method.POST);
        request.header("Authorization", authorization);
        request.form(map);
        JSONObject jsonObject = IotTools.getData(request);
        return jsonObject.getStr("access_token");
    }
}
