package com.example.zxweb.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.zxweb.common.constant.DevConstant;
import com.example.zxweb.common.constant.enums.IotApiEnum;
import com.example.zxweb.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description ios 设备请求工具
 * @Author ZhouWenTao
 * @Date 2023/9/8 11:59
 */
@Component
@Slf4j
public class IotUtils {
    //请求服务地址                              https://10.0.10.153:2443/api/iot/v1
    private static final String API_PREFIX = "https://10.0.10.153:2443/api/iot/v1";
    private static String serial = DevConstant.gateway.gateway_5lqh;
    private static final JSONObject headers=JSONObject.parseObject("{\"x-consumer-username\":\"dwVendor\",\"appCode\":\"42142fd0jkbf4515853b7fcec64748f6\"}");

    public static List<JSONObject> devicesMethodsNews(JSONObject queryData){
        String serial = queryData.getString("serial");
        String[] serials = serial.split(",");
        List<JSONObject> list=new ArrayList<>();
        for (String s : serials) {
            String url = API_PREFIX + IotApiEnum.getPathByText("查询方法历史数据") + "?serial=" + s;
            if (!StringUtils.isEmpty(queryData.getString("methodName"))) {
                url+="&methodName="+queryData.getString("methodName");
            }
            JSONObject jsonObject = RestUtil.get(url, null, null, headers);
            Integer code = jsonObject.getInteger("code");
            if (code==0) {
                if (jsonObject.getJSONObject("data")==null) {
                    continue;
                }
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("methods");
                if (CollectionUtils.isEmpty(jsonArray)) {
                    continue;
                }
                list.add(jsonArray.getJSONObject(0));
            }
        }
        return list;
    }

    /**
     * {"serial":"0cefafd605f7","productId":"",	"methodName":"celueSet","inputData":{"devid":"0cefafd605f7","celueid":"100000000003","name":"策略3","triggereTime":"20 18 * * 1,4,6","action":"e826ecfeff81f68c.light.controlLight.ctrl_ch0_status=\"0\"","startTime":"2023-09-12 10:00:00","endTime":"2023-09-30 11:30:00"	}}
     * @param requestBody
     * @return
     */
    public static boolean celueSet(JSONObject requestBody){
        JSONObject responseBody = postApi(IotApiEnum.getPathByText("向设备发送方法"), requestBody);
        try {
            if (responseBody!=null) {
                JSONObject data = responseBody.getJSONObject("data");
                if (data!=null) {
                    JSONObject outputData = data.getJSONObject("outputData");
                    if (outputData!=null) {
                        Integer code = outputData.getInteger("code");
                        if (code==1) {
                            return true;
                        }
                    }else{
                        throw new BusinessException(outputData.getString("message"));
                    }
                }
            }
        }catch (Exception e){
            throw new BusinessException(e.getMessage());
        }
        return false;
    }

    /**
     * 更改策略状态
     * @param celueId 策略id
     * @param status 1-启动 0-停止
     * @return true/false
     */
    public static boolean editCelueStatus(String celueId,String status){
        String serial = DevConstant.gateway.gateway_5lqh;
        JSONObject requestBody=JSONObject.parseObject(String.format("{\t\"serial\":\"%s\",\t\"productId\":\"\",\t\"methodName\":\"celueCmd\",\t\"inputData\":{\t\t\"devid\":\"%s\",\t\t\"celueid\":\"%s\",\t\t\"startStop\":\"%s\"\t}}",serial,serial,celueId,status));
        System.out.println(requestBody.toJSONString());
        try {
            JSONObject jsonObject = postApi(IotApiEnum.getPathByText("向设备发送方法"), requestBody);
            log.info(jsonObject.toJSONString());
            JSONObject data = jsonObject.getJSONObject("data");
            if (data!=null) {
                JSONObject outputData = data.getJSONObject("outputData");
                if (outputData!=null) {
                    Integer code1 = outputData.getInteger("code");
                    if (code1!=null && 1==code1) {
                        return true;//更改成功
                    }else{
                        throw new BusinessException(outputData.getString("message"));
                    }
                }
            }
        }catch (Exception e){
            throw new BusinessException(e.getMessage());
        }
        return false;
    }

    /**
     * 获取策略的状态
     * @param celueId 策略id
     * @return 1-运行中,0-停止中
     */
    public static String getCelueStatus(String celueId){
        String str=String.format("{\"serial\":\"%s\",\"productId\":\"\",\"methodName\":\"celueStatusQuery\",\"inputData\":{\"devid\":\"%s\",\"celueid\":\"%s\"}}",serial,serial,celueId);
        System.out.println("-----------------");
        System.out.println(str);
        JSONObject requestBody = JSONObject.parseObject(str);
        JSONObject responseBody = IotUtils.postApi(IotApiEnum.getPathByText("向设备发送方法"), requestBody);
        JSONObject data = responseBody.getJSONObject("data");
        try {
            if (data!=null) {
                JSONObject outputData = data.getJSONObject("outputData");
                if (outputData!=null) {
                    return outputData.getString("status");
                }
            }
        }catch (Exception e){
            throw new BusinessException(e.getMessage());
        }
        return "0";
    }

    /**
     * 删除策略
     * @param celueId 策略id
     */
    public static boolean deleteCelue(String celueId) {
        String request=String.format("{\"serial\":\"%s\",\"productId\":\"\",\"methodName\":\"celueDelete\",\"inputData\":{\"devid\":\"%s\",\t\"celueid\":\"%s\"}}",serial,serial,celueId);
        try {
            JSONObject requestBody = JSONObject.parseObject(request);
            JSONObject responseBody = postApi(IotApiEnum.getPathByText("向设备发送方法"), requestBody);
            JSONObject data = responseBody.getJSONObject("data");
            if (data!=null) {
                JSONObject outputData = data.getJSONObject("outputData");
                if (outputData != null) {
                    Integer code = outputData.getInteger("code");
                    return code == 1;
                }else{
                    throw new BusinessException(outputData.getString("message"));
                }
            }
        }catch (Exception e){
            throw new BusinessException(e);
        }
        return false;
    }

    public static JSONObject getApi(String apiUrl,JSONObject queryData) {

        StringBuilder sb=new StringBuilder();
        int i=0;
        for (String field : queryData.keySet()) {
            String value = (String) queryData.get(field);
            if (StringUtils.isEmpty(value)) {
                continue;
            }
            sb.append(i==0?"?":"&");
            sb.append(field).append("=").append(value);
            i++;
        }
        return RestUtil.get(API_PREFIX+apiUrl+sb,null,null,headers);
    }

    public static JSONObject postApi(String apiUrl,JSONObject requestBody){
        return RestUtil.post(API_PREFIX+apiUrl,requestBody,headers);
    }
}
