package com.limap.common.utils.ali.iot;

import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.limap.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class ClientUtil {
    final static String appKey ="334224397";
//    final static String appKey ="LTAI5tKv3CygUJwCd8W9p6aR";
    final static String appSecret = "70de3018ec39423e9ca1e1b6a6a84ad6";
//    final static String appSecret = "KjOSdAMh4Tgdyj0he1mM5xk6JBYiY5";

    public static ApiResponse postRequestDemo(IoTApiRequest request,String path) throws UnsupportedEncodingException {
        IoTApiClientBuilderParams builderParams = new IoTApiClientBuilderParams();
        builderParams.setAppKey(appKey);
        builderParams.setAppSecret(appSecret);
        SyncApiClient syncClient = new SyncApiClient(builderParams);


        //请求参数域名、path、request
        String host = "api.link.aliyun.com";
        ApiResponse response = syncClient.postBody(host, path, request);

        log.info(
                "response code = " + response.getCode() + " response content = " + new String(response.getBody(),
                        "utf-8"));
        return response;
    }

    public  String getCloudToken() {
        String s = HttpUtils.sendGet("http://120.46.184.148:6232/assistant/weatherHourData");
        return s.substring(1,s.length()-1);
    }

    public Boolean propertiesSet(String iotId,String items) {
        IoTApiRequest request = new IoTApiRequest();
        request.setApiVer("1.0.2");
        //设置参数
        request.putParam("iotId", iotId);
        request.putParam("items",items);
        try {
            ApiResponse apiResponse = ClientUtil.postRequestDemo(request, "/cloud/thing/properties/set");
            System.out.println(JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8)));
            JSONObject jsonObject = JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8));
            Integer code = jsonObject.getInteger("code");
            return code.equals(200);
        }catch (Exception e) {
            log.error("设备属性设置失败,设备id:{},设置参数{}，失败原因{}",iotId,items,e.getMessage());
            return false;
        }
    }

    /**
     *
     * @param iotId
     * @param items
     * @return
     */
    public Boolean propertiesSet(String iotId,Object items) {
        IoTApiRequest request = new IoTApiRequest();
        request.setApiVer("1.0.2");
        //设置参数
        request.putParam("iotId", iotId);
        request.putParam("items",items);
        try {
            ApiResponse apiResponse = ClientUtil.postRequestDemo(request, "/cloud/thing/properties/set");
            System.out.println(JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8)));
            JSONObject jsonObject = JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8));
            Integer code = jsonObject.getInteger("code");
            return code.equals(200);
        }catch (Exception e) {
            log.error("设备属性设置失败,设备id:{},设置参数{}，失败原因{}",iotId,items.toString(),e.getMessage());
            return false;
        }
    }

    public JSONArray propertiesGet(String iotId) {
        IoTApiRequest request = new IoTApiRequest();
        request.setApiVer("1.0.2");
        //设置参数
        request.putParam("iotId", iotId);
        try {
            ApiResponse apiResponse = ClientUtil.postRequestDemo(request, "/cloud/thing/properties/get");
            JSONObject jsonObject = JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8));
            return jsonObject.getJSONArray("data");
        }catch (Exception e) {

            return null;
        }
    }

    public JSONObject thingInfoGet(String cloudToken,String iotId) {
        IoTApiRequest request = new IoTApiRequest();
        request.setApiVer("1.0.2");
        request.setCloudToken(cloudToken);
        //设置参数
        request.putParam("iotId", iotId);
        try {
            ApiResponse apiResponse = ClientUtil.postRequestDemo(request, "/cloud/thing/info/get");
            JSONObject jsonObject = JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8));
            return jsonObject.getJSONObject("data");
        }catch (Exception e) {
            return null;
        }
    }

    public JSONObject thingStatusGet(String iotId) {
        IoTApiRequest request = new IoTApiRequest();
        request.setApiVer("1.0.2");
        //设置参数
        request.putParam("iotId", iotId);
        try {
            ApiResponse apiResponse = ClientUtil.postRequestDemo(request, "/cloud/thing/status/get");
            JSONObject jsonObject = JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8));
            return jsonObject.getJSONObject("data");
        }catch (Exception e) {
            try{
                HttpUtils.sendGet("http://localhost:6223/assistant/weatherHourData/refresh");
                return thingStatusGet(iotId);
            }catch (Exception ec){

            }
            return null;
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        IoTApiRequest request = new IoTApiRequest();
        request.setApiVer("1.0.2");
        request.setCloudToken("f5bef20cc3b24cb18a069a0d3a0009e6");
        JSONObject object = JSONObject.parseObject("{\"rated_voltage\":{\"phase\":\"A\",\"voltage\":220}}");
        //设置参数
        request.putParam("deviceName", "866145063650952");
        request.putParam("productKey", "a1g8Z6yzWqv");
        request.putParam("items",object);

        ApiResponse apiResponse = ClientUtil.postRequestDemo(request, "/cloud/thing/properties/set");
        JSONObject jsonObject = JSONObject.parseObject(new String(apiResponse.getBody(), StandardCharsets.UTF_8));
        System.out.println(jsonObject);
    }
}
