package com.fastbee.deviceData.api.renke.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import com.fastbee.deviceData.api.renke.domin.ModWormAutoMode;
import com.fastbee.deviceData.api.renke.domin.UpdateDevice;
import com.fastbee.deviceData.api.renke.domin.WormMode;
import com.fastbee.deviceData.api.renke.domin.WormOper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 建大仁科虫情设备服务
 */
@Service
public class RenkeWormSituationDeviceService {

    @Autowired
    private RenKeAuthorizationService authorizationService;
    /**
     * 批量获取设备详情
     * @param deviceAddr
     * @return
     */
    public  JSONObject getAllInsectEquipmentInformation(String deviceAddr){

        //获取设备实时数据
        //请求参数
        HttpResponse response = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/worm/device/getBtchDeviceDO?deviceAddr="+deviceAddr)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取设备实时数据失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 修改虫情设备信息
     * @param updateDevice
     * @return
     */
    public JSONObject updateDevice(UpdateDevice updateDevice){
        //获取设备实时数据
        HttpResponse response = HttpRequest.post("http://api.farm.0531yun.cn/api/v2.0/worm/device/updateDevice")
                .header("token", authorizationService.getToken()).body(JSONUtil.toJsonStr(updateDevice))
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("修改设备自动模式时间失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }

    /**
     * 获取设备自动模式时间
     * @param deviceAddr
     * @return
     */
    public JSONObject getWormAutoMode(String deviceAddr){
        HttpResponse response = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/worm/device/getWormAutoMode?deviceAddr="+deviceAddr)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取设备实时数据失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }

    /**
     * 修改设备自动模式时间
     * @param modWormAutoMode
     * @return
     */
    public JSONObject updateWormAutoMode(ModWormAutoMode modWormAutoMode){
        //获取设备实时数据
        //请求参数
        Map<String,Object> reqBody =getObjectProperties(modWormAutoMode);
        HttpResponse response = HttpRequest.post("http://api.farm.0531yun.cn/api/v2.0/worm/device/modWormAutoMode")
                .header("token", authorizationService.getToken()).body(JSONUtil.toJsonStr(reqBody))
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("修改设备自动模式时间失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 手自动模式切换
     * @param wormMode
     * @return
     */
    public JSONObject updateWormMode(WormMode wormMode){
        //获取设备实时数据
        //请求参数
        Map<String,Object> reqBody =getObjectProperties(wormMode);
        HttpResponse response = HttpRequest.post("http://api.farm.0531yun.cn/api/v2.0/worm/device/modWormAutoMode")
                .header("token", authorizationService.getToken()).body(JSONUtil.toJsonStr(reqBody))
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("虫情设备下发命令失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 虫情设备下发命令
     * @param wormOper
     * @return
     */
    public JSONObject updateWormOper(WormOper wormOper){
        //获取设备实时数据
        //请求参数
        Map<String,Object> reqBody =getObjectProperties(wormOper);
        HttpResponse response = HttpRequest.post("http://api.farm.0531yun.cn/api/v2.0/worm/device/deviceOper/wormOper")
                .header("token", authorizationService.getToken()).body(JSONUtil.toJsonStr(reqBody))
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取设备实时数据失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 虫情设备历史记录
     * @return
     */
    public JSONObject getWormHistoryData(String deviceAddr,String beginTime,String endTime,Integer pages,Integer limit){
        // 请求基础URL
        String baseUrl = "http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormHistoryData";

        StringBuilder queryParams = new StringBuilder();
        if (deviceAddr != null && !deviceAddr.isEmpty()) {
            queryParams.append("deviceAddr=").append(URLEncoder.encode(deviceAddr));
        }
        if (beginTime != null && !beginTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("beginTime=").append(URLEncoder.encode(beginTime));
        }
        if (endTime != null && !endTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("endTime=").append(URLEncoder.encode(endTime));
        }
        if (pages != null) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("pages=").append(pages);
        }
        if (limit != null) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("limit=").append(limit);
        }
        String fullUrl = baseUrl + "?" + queryParams.toString();
        HttpResponse response = HttpRequest.get(fullUrl)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取虫情设备历史记录失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 虫情区域统计
     * @return
     */
    public JSONObject getWormStatisticsByGroup(String groupId,String beginTime,String endTime){
        // 请求基础URL
        String baseUrl = "http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormStatisticsByGroup";

        StringBuilder queryParams = new StringBuilder();
        if (groupId != null && !groupId.isEmpty()) {
            queryParams.append("deviceAddr=").append(URLEncoder.encode(groupId));
        }
        if (beginTime != null && !beginTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("beginTime=").append(URLEncoder.encode(beginTime));
        }
        if (endTime != null && !endTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("endTime=").append(URLEncoder.encode(endTime));
        }

        String fullUrl = baseUrl + "?" + queryParams.toString();
        HttpResponse response = HttpRequest.get(fullUrl)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取虫情区域统计失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 虫情设备分析报表
     * @return
     */
    public JSONObject getWormDataList(String deviceAddr,String beginTime,String endTime,Integer pages,Integer limit){
        // 请求基础URL
        String baseUrl = "http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormDataList";

        StringBuilder queryParams = new StringBuilder();
        if (deviceAddr != null && !deviceAddr.isEmpty()) {
            queryParams.append("deviceAddr=").append(URLEncoder.encode(deviceAddr));
        }
        if (beginTime != null && !beginTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("beginTime=").append(URLEncoder.encode(beginTime));
        }
        if (endTime != null && !endTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("endTime=").append(URLEncoder.encode(endTime));
        }
        if (pages != null) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("pages=").append(pages);
        }
        if (limit != null) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("limit=").append(limit);
        }
        String fullUrl = baseUrl + "?" + queryParams.toString();
        HttpResponse response = HttpRequest.get(fullUrl)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取虫情设备历史记录失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }

    /**
     * 虫情设备分析报表记录（最新一条记录）
     * @param deviceAddr
     * @return
     */
    public  JSONObject getWormDataAndWormDataAIBy(String deviceAddr){

        //获取设备实时数据
        //请求参数
        HttpResponse response = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormDataAndWormDataAIBy?deviceAddr="+deviceAddr)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取虫情设备分析报表记录（最新一条记录）失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 害虫自动识别
     * @param recordId
     * @return
     */
    public  JSONObject analysistWorm(String recordId){

        //获取设备实时数据
        //请求参数
        HttpResponse response = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/analysistWorm?recordId="+recordId)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取虫情设备分析报表记录（最新一条记录）失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 根据ID获取虫情设备分析报表记录
     * @return
     */
    public JSONObject getDeviceAnalysisReportRecordAccordingIdList(String deviceAddr,String recordIds){
        // 请求基础URL
        String baseUrl = "http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getDeviceAnalysisReportRecordAccordingIdList";

        StringBuilder queryParams = new StringBuilder();
        if (deviceAddr != null && !deviceAddr.isEmpty()) {
            queryParams.append("deviceAddr=").append(URLEncoder.encode(deviceAddr));
        }

        if (recordIds != null) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("recordIds=").append(recordIds);
        }
        String fullUrl = baseUrl + "?" + queryParams.toString();
        HttpResponse response = HttpRequest.get(fullUrl)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取虫情设备历史记录失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
    /**
     * 虫情设备操作记录
     * @return
     */
    public JSONObject getWormOperationLog(String deviceAddr,String beginTime,String endTime){
        // 请求基础URL
        String baseUrl = "http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormOperationLog";

        StringBuilder queryParams = new StringBuilder();
        if (deviceAddr != null && !deviceAddr.isEmpty()) {
            queryParams.append("deviceAddr=").append(URLEncoder.encode(deviceAddr));
        }
        if (beginTime != null && !beginTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("beginTime=").append(URLEncoder.encode(beginTime));
        }
        if (endTime != null && !endTime.isEmpty()) {
            if (queryParams.length() > 0) queryParams.append("&");
            queryParams.append("endTime=").append(URLEncoder.encode(endTime));
        }
        String fullUrl = baseUrl + "?" + queryParams.toString();
        HttpResponse response = HttpRequest.get(fullUrl)
                .header("token", authorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取虫情设备历史记录失败!");
        }
        JSONObject jsonObject = JSONUtil.parseObj(respBodyStr);
        return jsonObject;
    }
        /**
         * 通过反射获取对象的所有属性和值，并存储到Map中
         *
         * @param obj 目标对象
         * @return 包含属性和值的Map
         */
        public static Map<String, Object> getObjectProperties(Object obj) {
            Map<String, Object> propertiesMap = new HashMap<>();

            // 获取对象的类类型
            Class<?> clazz = obj.getClass();

            // 获取类的所有字段（包括私有字段）
            Field[] fields = clazz.getDeclaredFields();

            // 遍历字段
            for (Field field : fields) {
                // 设置字段为可访问（即使它是私有的）
                field.setAccessible(true);

                try {
                    // 获取字段的名称
                    String fieldName = field.getName();

                    // 获取字段的值（从目标对象中）
                    Object fieldValue = field.get(obj);

                    // 将字段名称和值存入Map中
                    propertiesMap.put(fieldName, fieldValue);

                } catch (IllegalAccessException e) {
                    // 理论上不应该发生，因为我们已经设置了setAccessible(true)
                    e.printStackTrace();
                }
            }
            return propertiesMap;
        }

}
