package com.zehong.system.task.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.constant.Constants;
import com.zehong.common.core.redis.RedisCache;
import com.zehong.common.utils.http.HttpUtils;
import com.zehong.system.service.ISysConfigService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @date 2026/8/4
 * @description tokenUtil
 */
@Component
public class IotDataAndTokenUtil {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ISysConfigService sysConfigService;

    /**
     * 获取MES token
     */
    public String getIOTToken() {
        // 1. 先从Redis中获取token
        Object tokenObj = redisCache.getCacheObject(Constants.IOT_LOGIN_TOKEN);
        if (tokenObj != null) {
            String token = tokenObj.toString();
            // 检查token是否即将过期（提前5分钟刷新）
            long expireTime = redisCache.getExpire(Constants.IOT_LOGIN_TOKEN, TimeUnit.MINUTES);
            if (expireTime > 10) { // 大于10分钟，直接返回
                return token;
            }
        }

        // 2. 如果Redis中没有或即将过期，重新获取token
        return refreshIOTToken();
    }

    /**
     * 刷新MES token
     */
    private String refreshIOTToken() {
        try {
            // 1. 获取登录配置信息
            String loginUrl = sysConfigService.directSelectConfigByKey(Constants.IOT_LOGIN_ADDRESS);
            String username = sysConfigService.directSelectConfigByKey(Constants.IOT_LOGIN_USERNAME);
            String password = sysConfigService.directSelectConfigByKey(Constants.IOT_LOGIN_PASSWORD);

            if (org.apache.commons.lang3.StringUtils.isAnyBlank(loginUrl, username, password)) {
                throw new RuntimeException("MES登录配置信息不完整");
            }

            // 2. 构造登录参数
            Map<String, String> loginParams = new HashMap<>();
            loginParams.put("username", username);
            loginParams.put("password", password);

            // 3. 添加请求头
            Map<String, String> headers = new HashMap<>();

            // 3. 调用登录接口
            String response = HttpUtils.postJson(loginUrl, headers ,loginParams);

            // 5. 解析响应
            if (org.apache.commons.lang3.StringUtils.isNotBlank(response)) {
                // 尝试解析为JSON
                try {
                    Map<String, Object> responseMap = JSON.parseObject(response, Map.class);

                    // 检查是否有错误
                    if (responseMap.containsKey("code") && !"200".equals(String.valueOf(responseMap.get("code")))) {
                        String errorMsg = responseMap.containsKey("msg") ?
                                String.valueOf(responseMap.get("msg")) : "登录失败";
                        System.err.println("登录失败: " + errorMsg);
                        return null;
                    }

                    // 根据实际响应结构提取token
                    String token = extractTokenFromResponse(responseMap);

                    if (org.apache.commons.lang3.StringUtils.isNotBlank(token)) {
                        // 存储token到Redis
                        redisCache.setCacheObject(Constants.IOT_LOGIN_TOKEN, token, 1, TimeUnit.HOURS);
                        System.out.println("登录成功，token: " + token);
                        return token;
                    }
                } catch (Exception e) {
                    System.err.println("解析响应失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }

            return null;

        } catch (Exception e) {
            throw new RuntimeException("获取MES token失败");
        }
    }


    /**
     * 从响应中提取token（根据实际响应格式调整）
     */
    private String extractTokenFromResponse(Map<String, Object> responseMap) {
        // 根据实际响应结构提取token
        // 例如：responseMap.get("data").get("token")

        // 示例1：如果token在顶层
        if (responseMap.containsKey("token")) {
            return String.valueOf(responseMap.get("token"));
        }

        // 示例2：如果token在data对象中
        if (responseMap.containsKey("data")) {
            Object data = responseMap.get("data");
            if (data instanceof Map) {
                Map<?, ?> dataMap = (Map<?, ?>) data;
                if (dataMap.containsKey("access_token")) {
                    return String.valueOf(dataMap.get("access_token"));
                }
            }
        }

        // 示例3：如果token在其他字段中
        String[] possibleTokenKeys = {"access_token", "accessToken", "Authorization", "authToken"};
        for (String key : possibleTokenKeys) {
            if (responseMap.containsKey(key)) {
                return String.valueOf(responseMap.get(key));
            }
        }

        // 如果都找不到，打印整个响应用于调试
        System.out.println("无法找到token，完整响应: " + JSON.toJSONString(responseMap));
        return null;
    }



    /**
     * 处理MES返回的数据
     */
    public Map<String,String > processIotData(String data ) {
        Map<String,String > deviceStatus = new HashMap<>();


        // 根据实际业务需求处理数据
        // 这里只是示例，具体实现根据您的业务逻辑
        try {
            JSONObject jsonObject = JSON.parseObject(data);

            Object data1 = jsonObject.get("data");
            if(data1 == null) {
                return deviceStatus;
            }

            JSONObject jsonData = JSON.parseObject(data1.toString());

            deviceStatus.put("number", jsonData.getString("number") == null ? "" : jsonData.getString("number"));
            deviceStatus.put("title", jsonData.getString("title") == null ? "" : jsonData.getString("title"));
            deviceStatus.put("deviceType", jsonData.getString("devices_type") == null ? "" : jsonData.getString("devices_type"));
            deviceStatus.put("modelTitle", jsonData.getString("model_title") == null ? "" : jsonData.getString("model_title"));
            deviceStatus.put("batchNum", jsonData.getString("batchNum") == null ? "" : jsonData.getString("batchNum"));
            deviceStatus.put("gas", jsonData.getString("gas") == null ? "" : jsonData.getString("gas"));
            deviceStatus.put("unit", jsonData.getString("unit") == null ? "" : jsonData.getString("unit"));
            deviceStatus.put("status", jsonData.getString("report_status") == null ? "" : jsonData.getString("report_status"));
            deviceStatus.put("concentration", jsonData.getString("report_nd") == null ? "" : jsonData.getString("report_nd"));
            deviceStatus.put("reportTime", jsonData.getString("report_time") == null ? "" : jsonData.getString("report_time"));

            // 处理数据逻辑...
            return deviceStatus;

        } catch (Exception e) {
            return new HashMap<>();
        }
    }
}
