<template>
  <div class="live-room-panel">
    <!-- 直播间功能 -->
    <Card :title="selectedLiveRoom?.liveRoomName">
      <div class="live-room-content">
        <!-- 上部分：直播画面和聊天 -->
        <div class="live-stream-section">
          <!-- 直播画面 -->
          <div class="live-video">
            <div class="video-placeholder">
              <!-- <div class="placeholder-text">直播画面</div> -->
              <div class="room-info">
                <div>直播间: {{ selectedLiveRoom?.title }}</div>
                <div>主播: {{ selectedLiveRoom?.nick_name }}</div>
              </div>
            </div>
          </div>

          <!-- 聊天消息悬浮层 -->
          <div class="chat-overlay">
            <div class="chat-messages" ref="chatMessagesRef">
              <div v-for="(message, index) in chatMessages" :key="index" class="chat-message"
                :class="{ 'own-message': message.isOwn }">
                <span class="sender">{{ message.sender }}（<span class="time">{{ message.time }}</span>）:</span>
                <span class="content">{{ message.content }}</span>
                
              </div>
            </div>
          </div>
        </div>

        <!-- 中部分：控制按钮 -->
          <div class="control-section">
            <Space :size="16">
              <Button type="primary" @click="handleLike" :loading="loading.like"
                :disabled="!liveRoomId">
                点赞
              </Button>
              <Button type="primary" @click="handleFollow" :loading="loading.follow"
                :disabled="!liveRoomId">
                关注
              </Button>
              <Button type="primary" @click="handleSendGift" :loading="loading.sendGift"
                :disabled="!liveRoomId">
                送礼
              </Button>
            </Space>
          </div>

          <!-- 下部分：聊天输入 -->
          <div class="chat-input-section">
            <Input v-model:value="chatInput" :placeholder="'请输入消息内容'"
              @pressEnter="handleSendChat" :maxlength="100">
              <template #suffix>
                <Button type="primary" @click="handleSendChat" :loading="loading.sendChat"
                  :disabled="!chatInput.trim() || !liveRoomId">
                  发送
                </Button>
              </template>
            </Input>
          </div>
      </div>
    </Card>

    <!-- 送礼弹窗 -->
    <Modal v-model:open="showGiftModal" :title="'送礼'" width="38%" :footer="null">
      <GiftSelection :gifts="giftList" :balance="balance" @send="handleGiftSend"
        @cancel="showGiftModal = false" />
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onUnmounted, onMounted, nextTick } from "vue";
import { Card, Button, Space, Input, message, Modal } from 'ant-design-vue';
import { takeoverApi } from '#/api';
import GiftSelection from './GiftSelection.vue';

interface RobotWsMessage {
  id: number;
  roomId: string;
  roomName: string;
  anchorName: string;
  msgType: string;
  content: string;
  rawData: string;
  sourceRole: string;
  sourceUserId: string;
  receiveTime: string;
  timestamp: number;
}

interface Emits {
  (e: 'exit'): void
  (e: 'update:balance', balance: number): void
}

interface LiveRoom {
  id: string;
  user_id: string;
  title: string;
  nick_name: string;
  liveRoomName?: string;
}

interface Props {
  selectedLiveRoom: LiveRoom | null;
  liveRoomId: string;
  robotUuid: string;
  balance: number;
  token: string;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 组件引用
const chatMessagesRef = ref();

// 响应式数据
const loading = reactive({
  like: false,
  follow: false,
  sendGift: false,
  sendChat: false,
});

const chatInput = ref('');
const chatMessages = ref<any[]>([]);
const showGiftModal = ref(false);
const giftList = ref<any[]>([]);

// 消息获取相关
const messageTimer = ref<number | null>(null);
const loadedMessageCount = ref(0);

// 监听直播间变化，加载最新数据
watch(() => props.selectedLiveRoom, (newRoom) => {
  if (newRoom) {
    // 进入新直播间时，清空旧数据
    clearLiveRoomData();
    // 加载直播间相关数据
    loadLiveRoomData();
  }
}, { immediate: true });

// 监听liveRoomId变化，确保直播间ID变化时也加载最新数据
watch(() => props.liveRoomId, (newRoomId) => {
  if (newRoomId && props.selectedLiveRoom) {
    // 直播间接入变化时，重新加载数据
    loadLiveRoomData();
  }
});

// 加载直播间数据
async function loadLiveRoomData() {
  // 这里可以添加加载直播间数据的逻辑
  // 例如：加载礼物列表、获取直播间信息等
  try {
    // 加载礼物列表
    const res = await takeoverApi.getGiftList({ robotUuid: props.robotUuid });
    if (res.data && !res.error) {
      giftList.value = res.data || [];
    }
  } catch (error) {
    console.error('加载直播间数据失败:', error);
  }
  
  // 启动定时获取消息
  startMessagePolling();
}

// 获取聊天消息
async function fetchMessages() {
  if (!props.liveRoomId) return;
  
  try {
    const res = await takeoverApi.getMessages({
      robotUuid: props.robotUuid,
      skip: loadedMessageCount.value,
      limit: 50
    });
    
    if (res.data && !res.error && Array.isArray(res.data)) {
      const messages = res.data as RobotWsMessage[];
      
      // 处理新消息，检查是否与"我"发送的消息重复
      messages.forEach(msg => {
        const messageContent = msg.content;
        const messageTime = formatTime(msg.receiveTime || msg.timestamp);
        
        // 检查是否存在与"我"发送的消息重复的消息
        const duplicateIndex = chatMessages.value.findIndex(chatMsg => 
          chatMsg.sender === '我' && 
          chatMsg.content === messageContent
        );
        
        // 如果找到重复的消息，删除之前的"我"的消息
        if (duplicateIndex !== -1) {
          chatMessages.value.splice(duplicateIndex, 1);
        }
        
        // 添加新消息
        addChatMessage({
          sender: msg.anchorName,
          content: messageContent,
          time: messageTime,
          isOwn: false
        });
      });
      
      // 更新已加载消息数量
      loadedMessageCount.value += messages.length;
    }
  } catch (error) {
    console.error('获取消息失败:', error);
  }
}

// 格式化时间
function formatTime(time: string | number): string {
  if (typeof time === 'number') {
    const date = new Date(time);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
  } else {
    const date = new Date(time);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
  }
}

// 启动定时获取消息
function startMessagePolling() {
  // 清除旧的定时器
  stopMessagePolling();
  
  // 立即获取一次消息
  fetchMessages();
  
  // 每5秒获取一次消息
  messageTimer.value = window.setInterval(() => {
    fetchMessages();
  }, 5000);
}

// 停止定时获取消息
function stopMessagePolling() {
  if (messageTimer.value) {
    clearInterval(messageTimer.value);
    messageTimer.value = null;
  }
}

// 清空直播间数据
function clearLiveRoomData() {
  chatInput.value = '';
  chatMessages.value = [];
  giftList.value = [];
  showGiftModal.value = false;
  
  // 停止定时获取消息
  stopMessagePolling();
  
  // 重置消息计数
  loadedMessageCount.value = 0;
}

// 处理点赞
async function handleLike() {
  if (!props.liveRoomId) return;
  
  loading.like = true;
  try {
    const res = await takeoverApi.like({ robotUuid: props.robotUuid, count: 1 });
    if (res.error) {
      message.error(res.error.message || '点赞失败');
      return;
    }
    message.success('点赞成功');
    // 添加点赞消息到聊天记录
    addChatMessage('系统', '点赞成功', true);
  } catch (error) {
    message.error('点赞失败');
  } finally {
    loading.like = false;
  }
}

// 处理关注
async function handleFollow() {
  if (!props.liveRoomId) return;
  
  loading.follow = true;
  try {
    const res = await takeoverApi.follow({ robotUuid: props.robotUuid });
    if (res.error) {
      message.error(res.error.message || '关注失败');
      return;
    }
    message.success('关注成功');
    // 添加关注消息到聊天记录
    addChatMessage('系统', '关注成功', true);
  } catch (error) {
    message.error('关注失败');
  } finally {
    loading.follow = false;
  }
}

// 打开送礼弹窗
async function handleSendGift() {
  try {
    // 加载礼物列表
    const res = await takeoverApi.getGiftList({ robotUuid: props.robotUuid });
    if (res.data && !res.error) {
      giftList.value = res.data || [];
      showGiftModal.value = true;
    }
  } catch (error) {
    message.error('获取礼物列表失败');
  }
}

// 处理发送聊天
async function handleSendChat() {
  if (!chatInput.value.trim() || !props.liveRoomId) return;
  
  loading.sendChat = true;
  try {
    const res = await takeoverApi.sendMessage({
      robotUuid: props.robotUuid,
      message: chatInput.value.trim()
    });
    if (res.error) {
      message.error(res.error.message || '发送消息失败');
      return;
    }

    // 添加到聊天消息列表
    addChatMessage({
      sender: '我',
      content: chatInput.value.trim(),
      time: new Date().toLocaleTimeString(),
      isOwn: true
    });

    chatInput.value = '';
  } catch (error) {
    message.error('发送消息失败');
  } finally {
    loading.sendChat = false;
  }
}

// 格式化礼物名称
function formatGiftName(gift: any) {
  return gift.gift_name || gift.name || '';
}

// 格式化礼物价格
function formatGiftPrice(gift: any) {
  const price = gift.gift_price || gift.price || gift.diamond || 0;
  return `${price} 钻石`;
}

// 处理送礼
function handleGiftSend(gift: any) {
  const giftPrice = gift.gift_price || gift.price || gift.diamond || 0;
  if (giftPrice > props.balance) {
    message.warning('余额不足');
    return;
  }
  
  // 二次确认
  Modal.confirm({
    title: '确认送礼',
    content: `确定要发送礼物「${formatGiftName(gift)}」吗？\n价格：${formatGiftPrice(gift)}`,
    onOk() {
      sendGift(gift);
    }
  });
}

// 发送礼物
async function sendGift(gift: any) {
  loading.sendGift = true;
  try {
    const res = await takeoverApi.sendGift({
      robotUuid: props.robotUuid,
      giftId: parseInt(gift.gift_id) || gift.id
    });
    if (res.error) {
      message.error(res.error.message || '送礼失败');
      return;
    }
    message.success('送礼成功');
    
    // 添加送礼消息到聊天记录
    addChatMessage('系统', `发送礼物「${formatGiftName(gift)}」成功`, true);
    
    // 更新余额
    const giftPrice = gift.gift_price || gift.price || gift.diamond || 0;
    emit('update:balance', props.balance - giftPrice);
    
    // 关闭弹窗
    showGiftModal.value = false;
  } catch (error) {
    message.error('发送礼物失败');
  } finally {
    loading.sendGift = false;
  }
}

// 添加聊天消息
function addChatMessage(sender: any, content?: string, isOwn: boolean = false) {
  let messageData;
  if (typeof sender === 'object') {
    // 处理对象形式的参数
    messageData = sender;
  } else {
    // 处理单独的参数
    const now = new Date();
    const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
    
    messageData = {
      sender,
      content,
      time,
      isOwn
    };
  }
  
  chatMessages.value.push(messageData);
  
  // 滚动到底部
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
    }
  });
}

// 组件销毁时清理数据
onUnmounted(() => {
  clearLiveRoomData();
  stopMessagePolling();
});
</script>

<style scoped>
.live-room-panel {
  width: 100%;
}

.live-room-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.live-stream-section {
  position: relative;
  width: 100%;
  height: 400px;
  background-color: #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.live-video {
  width: 100%;
  height: 100%;
}

.video-placeholder {
  padding-top: 10%;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  /* justify-content: center; */
  align-items: center;
  background-color: #000;
  color: #fff;
}

.placeholder-text {
  font-size: 24px;
  margin-bottom: 16px;
}

.room-info {
  text-align: center;
  font-size: 14px;
  line-height: 1.5;
}

.chat-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 40%;
  background-color: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10px);
  border-radius: 8px 8px 0 0;
  padding: 16px;
  overflow: hidden;
}

.chat-messages {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chat-message {
  display: flex;
  gap: 4px;
  color: #fff;
  font-size: 14px;
  width: 100%;
}

.chat-message.own-message {
  align-items: flex-start;
  color: #ffd700;
}

.sender {
  font-weight: bold;
  color: #1890ff;
}

.content {
  word-break: break-all;
}

.time {
  font-size: 10px;
  color: #999;
}

.control-section {
  display: flex;
  gap: 16px;
}

.chat-input-section {
  width: 100%;
}
</style>