package com.ssyf.task.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.ssyf.module.robot.domain.entity.*;
import com.ssyf.module.robot.domain.query.RRobotConsumptionRecordQuery;
import com.ssyf.module.robot.service.*;
import com.ssyf.task.models.PerformanceMetrics;
import com.ssyf.third.bmiss.model.GiftDetail;
import com.ssyf.third.bmiss.model.LiveRoom;
import com.ssyf.third.bmiss.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 机器人记录管理服务实现类
 *
 * @author system
 * @since 1.0
 */
@Slf4j
@Service
public class RobotRecordServiceImpl implements RobotRecordService {

    @Autowired @Lazy private RRobotRunRecordService robotRunRecordService;
    @Autowired @Lazy private RRobotRunningInfoService robotRunningInfoService;
    @Autowired @Lazy private RRobotConsumptionRecordService robotConsumptionRecordService;
    @Autowired @Lazy private RedisTemplate<String, String> stringRedisTemplate;

    // 性能监控指标缓存
    private final ConcurrentHashMap<String, PerformanceMetrics> performanceMetrics = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Long> taskExecutionTimes = new ConcurrentHashMap<>();

    private static final String ROBOT_EXECUTION_STATUS_PREFIX = "robot:execution:status:";
    private static final String REDIS_CURRENT_ROOM_KEY_PREFIX = "robot:current:room:";

    @Override
    public void recordRobotRunRecord(LiveRoom liveRoom, RRobotAccount robotAccount, RConfigRelation configRelation,
                                     RRunningConfig runningConfig, UserInfo userInfo,
                                     String actionType, String actionDesc, String result, Integer executeStatus) {
        if (robotAccount == null) {
            log.warn("忽略运行日志记录：机器人账号为空");
            return;
        }
        try {
            RRobotRunRecord runRecord = new RRobotRunRecord();
            runRecord.setUuid(IdUtil.fastSimpleUUID());
            runRecord.setRobotUuid(robotAccount.getUuid());
            runRecord.setRobotAccount(robotAccount.getEmail());
            runRecord.setRobotNickName(robotAccount.getNickname());
            runRecord.setRobotGroupUuid(robotAccount.getGroupId());
            runRecord.setRobotGroupName(robotAccount.getGroupName());

            if (configRelation != null) {
                runRecord.setConfigUuid(configRelation.getUuid());
                runRecord.setConfigName(configRelation.getConfigName());
            }

            runRecord.setConfigType(actionType);
            runRecord.setExecuteDesc(actionDesc);
            runRecord.setExecuteStatus(executeStatus);
            runRecord.setExecuteLog(result);
            runRecord.setCreateTime(LocalDateTime.now());
            // 简单处理：开始结束时间暂定相同，精确统计需在业务层传递
            runRecord.setExecuteStartTime(LocalDateTime.now());
            runRecord.setExecuteEndTime(LocalDateTime.now());

            // 填充直播间信息
            if (liveRoom != null) {
                runRecord.setLiveRoomId(String.valueOf(liveRoom.getUser_id()));
                runRecord.setLiveRoomName(liveRoom.getTitle());
                runRecord.setAnchorId(liveRoom.getUser_number());
                runRecord.setAnchorName(liveRoom.getNick_name());
                runRecord.setAnchorAvatar(liveRoom.getHeade_portrait());
            }

            robotRunRecordService.addOne(runRecord);
        } catch (Exception e) {
            log.error("记录运行日志异常，账号：{}，动作：{}", robotAccount.getEmail(), actionType, e);
        }
    }

    @Override
    public void recordRobotConsumption(LiveRoom liveRoom, RRobotAccount robotAccount, RConfigRelation configRelation,
                                       RRunningConfig runningConfig, UserInfo userInfo, GiftDetail giftDetail, int count) {
        if (robotAccount == null || giftDetail == null) {
            log.warn("忽略消费记录：关键参数为空");
            return;
        }
        try {
            double price = Optional.ofNullable(giftDetail.getGift_price()).map(Number::doubleValue).orElse(0.0);
            double totalPrice = price * count;

            RRobotConsumptionRecordQuery record = new RRobotConsumptionRecordQuery();
            record.setUuid(IdUtil.fastSimpleUUID());
            record.setRobotUuid(robotAccount.getUuid());
            record.setRobotAccount(robotAccount.getEmail());
            record.setRobotNickName(robotAccount.getNickname());
            record.setRobotGroupUuid(robotAccount.getGroupId());
            record.setRobotGroupName(robotAccount.getGroupName());
            // 礼物信息
            record.setGiftId(giftDetail.getGift_id() + "");
            record.setGiftName(giftDetail.getGift_name());
            record.setGiftIcon(giftDetail.getGift_image());
            record.setGiftQuantity(count);
            record.setGiftUnitPrice(price);
            record.setGiftTotalPrice(totalPrice);

            // 直播间关联
            if (liveRoom != null) {
                record.setRoomId(String.valueOf(liveRoom.getUser_id()));
                record.setRoomName(liveRoom.getTitle());
                record.setAnchorId(liveRoom.getUser_number());
                record.setAnchorName(liveRoom.getNick_name());
                record.setAnchorAvatar(liveRoom.getHeade_portrait());
                record.setSourceId(String.valueOf(liveRoom.getUser_id()));
            }

            record.setConsumptionAmount(totalPrice);
            record.setConsumptionInfo(StrUtil.format("赠送：{} x {}，总额：{}", giftDetail.getGift_name(), count, totalPrice));
            record.setConsumptionMethod("GIFT");
            record.setNotes("机器人自动化送礼");
            record.setConsumptionTime(LocalDateTime.now());

            robotConsumptionRecordService.addOne(record);
            log.debug("消费记录已保存：账号={}，总价={}", robotAccount.getEmail(), totalPrice);
        } catch (Exception e) {
            log.error("记录消费记录异常，账号：{}", robotAccount.getEmail(), e);
        }
    }

    @Override
    public void recordRobotRunningInfo(LiveRoom liveRoom, RRobotAccount robotAccount, RConfigRelation configRelation,
                                       RRunningConfig runningConfig, UserInfo userInfo) {
        if(robotAccount == null){return;}
        try {
            RRobotRunningInfo runningInfo = robotRunningInfoService.getOrCreated(robotAccount);
            runningInfo.setRunningStatus(1); // 1-在线
            runningInfo.setLastUpdateTime(LocalDateTime.now());
            runningInfo.setRobotAccount(robotAccount.getEmail());
            runningInfo.setRobotNickName(robotAccount.getNickname());
            runningInfo.setRobotUuid(robotAccount.getUuid());
            runningInfo.setRobotGroupUuid(robotAccount.getGroupId());
            runningInfo.setRobotGroupName(robotAccount.getGroupName());

            if (liveRoom != null) {
                // 在直播间
                runningInfo.setLiveRoomId(String.valueOf(liveRoom.getUser_id()));
                runningInfo.setLiveRoomName(liveRoom.getTitle());
                runningInfo.setAnchorId(liveRoom.getUser_number());
                runningInfo.setAnchorName(liveRoom.getNick_name());
                runningInfo.setAnchorAvatar(liveRoom.getHeade_portrait());

                // 只有当行为变化时才更新进入时间
                if (runningInfo.getCurrentBehavior() == null || runningInfo.getCurrentBehavior() != 2) {
                    runningInfo.setCurrentBehavior(2); // 2-观看直播
                    runningInfo.setEnterLiveRoomTime(LocalDateTime.now());
                    runningInfo.setExitLiveRoomTime(null);
                }
                
                // 更新Redis状态供前端或监控查询
                updateRedisStatus(robotAccount.getUuid(), liveRoom);
            } else {
                // 仅登录，未在房间
                runningInfo.setCurrentBehavior(1); // 1-空闲/大厅
                runningInfo.setEnterLiveRoomTime(null);
            }
            robotRunningInfoService.saveOrUpdate(runningInfo);
        } catch (Exception e) {
            log.error("更新运行状态异常，账号：{}", robotAccount.getEmail(), e);
        }
    }

    private void updateRedisStatus(String robotUuid, LiveRoom liveRoom) {
        String key = ROBOT_EXECUTION_STATUS_PREFIX + robotUuid;
        JSONObject status = new JSONObject();
        status.set("status", "WATCHING");
        status.set("roomId", liveRoom.getUser_id());
        status.set("anchorId", liveRoom.getUser_number());
        status.set("updateTime", LocalDateTime.now().toString());
        stringRedisTemplate.opsForValue().set(key, status.toString(), Duration.ofHours(1));
    }

    @Override
    public void recordTaskExecutionTime(String taskName, long executionTime) {
        taskExecutionTimes.put(taskName, executionTime);
        performanceMetrics.computeIfAbsent(taskName, PerformanceMetrics::new)
                .recordExecution(true, executionTime);
    }

    @Override
    public void recordTaskExecutionFailure(String taskName, long executionTime) {
        performanceMetrics.computeIfAbsent(taskName, PerformanceMetrics::new)
                .recordExecution(false, executionTime);
    }

    @Override
    public void updateRobotRunningInfoAfterQuit(RRobotAccount robotAccount, Integer roomId, LocalDateTime enterLiveRoomTime) {
        if(robotAccount == null){return;}
        try {
            RRobotRunningInfo runningInfo = robotRunningInfoService.getOrCreated(robotAccount);
            runningInfo.setRobotAccount(robotAccount.getEmail());
            runningInfo.setRobotNickName(robotAccount.getNickname());
            runningInfo.setRobotUuid(robotAccount.getUuid());
            runningInfo.setRobotGroupUuid(robotAccount.getGroupId());
            runningInfo.setRobotGroupName(robotAccount.getGroupName());
            //清空直播房间状态
            runningInfo.setLiveRoomId(null);
            runningInfo.setAnchorId(null);
            runningInfo.setAnchorName(null);
            runningInfo.setAnchorAvatar(null);
            runningInfo.setLiveRoomName(null);
            runningInfo.setEnterLiveRoomTime(null);
            runningInfo.setExitLiveRoomTime(null);

            //退出处理
            if(roomId == null){
                runningInfo.setLogoutTime(LocalDateTime.now());
            }


            runningInfo.setCurrentBehavior(1);
            runningInfo.setLastUpdateTime(LocalDateTime.now());
            robotRunningInfoService.updateById(runningInfo);



            // 清理Redis相关状态
            stringRedisTemplate.delete(ROBOT_EXECUTION_STATUS_PREFIX + robotAccount.getUuid());
            stringRedisTemplate.delete(REDIS_CURRENT_ROOM_KEY_PREFIX + robotAccount.getUuid());

        } catch (Exception e) {
            log.error("更新退出状态异常，账号：{}", robotAccount.getEmail(), e);
        }
    }
}