package com.haha.miniapp.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.haha.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 状态查询控制器
 * 供小程序轮询查询设备状态、识别结果和订单信息
 * 
 * 数据流程：
 * 1. 哈哈平台通过回调推送状态到 CallbackController
 * 2. CallbackController 将状态保存到 Redis
 * 3. 小程序通过此控制器轮询 Redis 获取最新状态
 */
@Slf4j
@RestController
@RequestMapping("/status")
@SaIgnore
public class StatusQueryController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String DEVICE_STATUS_KEY = "haha:device:status:";
    private static final String RECOGNIZE_RESULT_KEY = "haha:recognize:result:";
    private static final String ORDER_INFO_KEY = "haha:order:info:";

    /**
     * 查询设备状态
     * 
     * @param deviceId 设备ID
     * @return 设备状态信息
     */
    @PostMapping("/device")
    public Result<Map<String, String>> queryDeviceStatus(@RequestBody Map<String, String> params) {
        String deviceId = params.get("deviceId");
        if (deviceId == null || deviceId.isEmpty()) {
            return Result.error(400, "设备ID不能为空");
        }
        
        String statusKey = DEVICE_STATUS_KEY + deviceId;
        Map<Object, Object> statusData = redisTemplate.opsForHash().entries(statusKey);
        
        if (statusData.isEmpty()) {
            Map<String, String> emptyResult = new HashMap<>();
            emptyResult.put("deviceId", deviceId);
            emptyResult.put("doorStatus", "unknown");
            return Result.success("暂无状态数据", emptyResult);
        }
        
        Map<String, String> result = new HashMap<>();
            statusData.forEach((k, v) -> result.put(k.toString(), v != null ? v.toString() : ""));
        
        return Result.success("查询成功", result);
    }

    /**
     * 查询识别结果
     * 
     * @param activityId 活动ID
     * @return 识别结果
     */
    @PostMapping("/recognize")
    public Result<Map<String, String>> queryRecognizeResult(@RequestBody Map<String, String> params) {
        String activityId = params.get("activityId");
        if (activityId == null || activityId.isEmpty()) {
            return Result.error(400, "活动ID不能为空");
        }
        
        String resultKey = RECOGNIZE_RESULT_KEY + activityId;
        Map<Object, Object> resultData = redisTemplate.opsForHash().entries(resultKey);
        
        if (resultData.isEmpty()) {
            return Result.error(404, "识别结果尚未生成，请稍后重试");
        }
        
        Map<String, String> result = new HashMap<>();
        resultData.forEach((k, v) -> result.put(k.toString(), v != null ? v.toString() : ""));
        
        return Result.success("查询成功", result);
    }

    /**
     * 查询订单信息
     * 
     * @param orderId 订单ID
     * @param activityId 活动ID
     * @return 订单信息
     */
    @PostMapping("/order")
    public Result<Map<String, String>> queryOrderInfo(@RequestBody Map<String, String> params) {
        String orderId = params.get("orderId");
        String activityId = params.get("activityId");
        
        if ((orderId == null || orderId.isEmpty()) && (activityId == null || activityId.isEmpty())) {
            return Result.error(400, "订单ID或活动ID不能同时为空");
        }
        
        String orderKey = ORDER_INFO_KEY + (orderId != null && !orderId.isEmpty() ? orderId : activityId);
        Map<Object, Object> orderData = redisTemplate.opsForHash().entries(orderKey);
        
        if (orderData.isEmpty()) {
            return Result.error(404, "订单信息尚未生成，请稍后重试");
        }
        
        Map<String, String> result = new HashMap<>();
        orderData.forEach((k, v) -> result.put(k.toString(), v != null ? v.toString() : ""));
        
        return Result.success("查询成功", result);
    }

    /**
     * 综合状态查询
     * 根据设备ID查询所有相关状态（设备状态 + 最新的识别结果和订单）
     * 
     * @param deviceId 设备ID
     * @return 综合状态信息
     */
    @PostMapping("/all")
    public Result<Map<String, Object>> queryAllStatus(@RequestBody Map<String, String> params) {
        String deviceId = params.get("deviceId");
        if (deviceId == null || deviceId.isEmpty()) {
            return Result.error(400, "设备ID不能为空");
        }
        
        Map<String, Object> result = new HashMap<>();
        
        // 查询设备状态
        String statusKey = DEVICE_STATUS_KEY + deviceId;
        Map<Object, Object> statusData = redisTemplate.opsForHash().entries(statusKey);
        if (!statusData.isEmpty()) {
            Map<String, String> deviceStatus = new HashMap<>();
            statusData.forEach((k, v) -> deviceStatus.put(k.toString(), v != null ? v.toString() : ""));
            result.put("deviceStatus", deviceStatus);
            
            // 如果有活动ID，查询识别结果和订单
            String activityId = deviceStatus.get("activityId");
            if (activityId != null && !activityId.isEmpty()) {
                // 查询识别结果
                String recognizeKey = RECOGNIZE_RESULT_KEY + activityId;
                Map<Object, Object> recognizeData = redisTemplate.opsForHash().entries(recognizeKey);
                if (!recognizeData.isEmpty()) {
                    Map<String, String> recognizeResult = new HashMap<>();
                    recognizeData.forEach((k, v) -> recognizeResult.put(k.toString(), v != null ? v.toString() : ""));
                    result.put("recognizeResult", recognizeResult);
                }
                
                // 查询订单信息
                String orderKey = ORDER_INFO_KEY + activityId;
                Map<Object, Object> orderData = redisTemplate.opsForHash().entries(orderKey);
                if (!orderData.isEmpty()) {
                    Map<String, String> orderInfo = new HashMap<>();
                    orderData.forEach((k, v) -> orderInfo.put(k.toString(), v != null ? v.toString() : ""));
                    result.put("orderInfo", orderInfo);
                }
            }
        } else {
            Map<String, String> emptyStatus = new HashMap<>();
            emptyStatus.put("deviceId", deviceId);
            emptyStatus.put("doorStatus", "unknown");
            result.put("deviceStatus", emptyStatus);
        }
        
        return Result.success("查询成功", result);
    }
}