package com.haha.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.haha.service.HahaCallbackService;
import com.haha.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class HahaCallbackServiceImpl implements HahaCallbackService {

    @Autowired
    private OrderService orderService;

    @Value("${haha.api.app-secret}")
    private String appSecret;

    @Override
    public void handleMessage(Map<String, Object> params) {
        String notifyType = (String) params.get("notify_type");
        if (notifyType == null || notifyType.isEmpty()) {
            log.warn("消息回调缺少 notify_type 参数");
            return;
        }

        switch (notifyType) {
            case "DEVICE_STATUS":
                handleDeviceStatus(params);
                break;
            case "ONLINE_STATUS":
                handleOnlineStatus(params);
                break;
            case "VOICE_RESULT":
                handleVoiceResult(params);
                break;
            case "CLIENT_NEW_PRODUCT":
                handleNewProductAudit(params);
                break;
            case "MERGE_PRODUCT":
                handleMergeProduct(params);
                break;
            case "ORC_RESULT":
                handleOrcResult(params);
                break;
            default:
                log.warn("未知的消息通知类型: {}", notifyType);
        }
    }

    @Override
    public void handleDeviceStatus(Map<String, Object> params) {
        try {
            String deviceId = (String) params.get("device_id");
            String status = (String) params.get("status");
            String openType = (String) params.get("open_type");
            
            log.info("开关门状态通知 - 设备: {}, 状态: {}, 类型: {}", deviceId, status, openType);
            
            switch (status) {
                case "2": // OPENED
                    log.info("设备 {} 开门成功", deviceId);
                    break;
                case "3": // CLOSED
                    log.info("设备 {} 关门成功，等待AI识别", deviceId);
                    break;
                case "1": // ERROR
                    log.error("设备 {} 开门失败", deviceId);
                    break;
                case "4": // ANOTHER
                    log.warn("设备 {} 繁忙", deviceId);
                    break;
            }
        } catch (Exception e) {
            log.error("处理开关门状态通知逻辑失败", e);
        }
    }

    @Override
    public void handleOnlineStatus(Map<String, Object> params) {
        try {
            String deviceId = (String) params.get("device_id");
            Object onlineObj = params.get("is_online");
            Integer isOnline = onlineObj instanceof Integer ? (Integer) onlineObj : Integer.valueOf(onlineObj.toString());
            
            log.info("设备在线状态通知 - 设备: {}, 在线状态: {}", deviceId, isOnline == 1 ? "在线" : "离线");
        } catch (Exception e) {
            log.error("处理设备在线状态通知逻辑失败", e);
        }
    }

    @Override
    public void handleVoiceResult(Map<String, Object> params) {
        try {
            String deviceId = (String) params.get("device_id");
            Object voiceObj = params.get("voice");
            Integer voice = voiceObj instanceof Integer ? (Integer) voiceObj : Integer.valueOf(voiceObj.toString());
            
            log.info("音量调节结果通知 - 设备: {}, 音量值: {}", deviceId, voice);
        } catch (Exception e) {
            log.error("处理音量调节结果通知逻辑失败", e);
        }
    }

    @Override
    public void handleNewProductAudit(Map<String, Object> params) {
        try {
            String id = (String) params.get("id");
            Object statusObj = params.get("status");
            Integer status = statusObj instanceof Integer ? (Integer) statusObj : Integer.valueOf(statusObj.toString());
            String name = (String) params.get("name");
            
            log.info("新品审核结果 - ID: {}, 商品名: {}, 状态: {}", id, name, status);
        } catch (Exception e) {
            log.error("处理新品审核结果通知逻辑失败", e);
        }
    }

    @Override
    public void handleMergeProduct(Map<String, Object> params) {
        try {
            Object listObj = params.get("list");
            if (listObj instanceof JSONArray) {
                JSONArray list = (JSONArray) listObj;
                log.info("商品合并结果通知 - 合并数量: {}", list.size());
            }
        } catch (Exception e) {
            log.error("处理商品合并结果通知逻辑失败", e);
        }
    }

    @Override
    public void handleOrcResult(Map<String, Object> params) {
        try {
            String activityId = (String) params.get("activity_id");
            String deviceId = (String) params.get("device_id");
            Object nobuyObj = params.get("nobuy");
            Integer nobuy = nobuyObj instanceof Integer ? (Integer) nobuyObj : Integer.valueOf(nobuyObj.toString());
            
            if (nobuy == 1) {
                log.info("AI识别结果: 用户未消费 (activityId: {})", activityId);
                return;
            }

            // 解析识别结果
            String resultStr = (String) params.get("result");
            JSONObject result = JSON.parseObject(resultStr);
            JSONArray excepts = result.getJSONArray("excepts");
            
            if (excepts != null && !excepts.isEmpty()) {
                log.warn("识别结果包含异常 (activityId: {}): {}", activityId, excepts.toJSONString());
            }

            log.info("AI识别结果通知处理完成 - 设备: {}, 活动: {}", deviceId, activityId);
            
            // TODO: 调用 orderService 计算金额并生成订单
            
        } catch (Exception e) {
            log.error("处理AI识别结果逻辑失败", e);
        }
    }

    @Override
    public boolean validateSign(Map<String, Object> params) {
        // TODO: 实现具体的签名验证逻辑
        return true;
    }
}
