<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null"
    :title="$t('robot.runningInfo.takeoverTitle')" width="60%" @cancel="_close">
    <div class="takeover-container">
      <!-- 左右分栏布局 -->
      <Row :gutter="16">
        <!-- 左侧：机器人信息和通用功能 -->
        <Col :span="8">
          <div class="left-panel">
            <!-- 机器人信息卡片 -->
            <Card :title="$t('robot.runningInfo.robotInfo')" class="robot-info-card">
              <div class="robot-info">
                <div class="info-item">
                  <span class="label">{{ $t('robot.runningInfo.robotAccount') }}:</span>
                  <span class="value">{{ robotInfo.robotAccount }}</span>
                </div>
                <div class="info-item">
                  <span class="label">{{ $t('robot.runningInfo.robotNickName') }}:</span>
                  <span class="value">{{ robotInfo.robotNickName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">运行状态:</span>
                  <span class="value" :class="getStatusClass(robotInfo.runningStatus)">
                    {{ data.runningStatusMap[robotInfo.runningStatus] }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="label">当前行为:</span>
                  <span class="value">{{ data.currentBehaviorMap[robotInfo.currentBehavior] }}</span>
                </div>
                <div class="info-item" v-if="robotInfo.liveRoomName">
                  <span class="label">当前直播间:</span>
                  <span class="value">{{ robotInfo.liveRoomName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">余额:</span>
                  <span class="value">{{ robotInfo.balance || '0.00' }} 元</span>
                </div>
              </div>
            </Card>

            <!-- 通用功能按钮 -->
            <Card :title="$t('robot.runningInfo.commonFunctions')" class="functions-card">
              <Space direction="vertical" style="width: 100%">
                <Button :type="robotInfo.runningStatus === 1 ? 'primary' : 'default'"
                  :disabled="robotInfo.runningStatus === 1" @click="handleLogin" :loading="data.loading.login" block>
                  {{ $t('robot.runningInfo.login') }}
                </Button>
                <Button :type="robotInfo.runningStatus === 2 ? 'primary' : 'default'"
                  :disabled="robotInfo.runningStatus !== 1" @click="handleLogout" :loading="data.loading.logout" block>
                  {{ $t('robot.runningInfo.logout') }}
                </Button>
                <Button type="primary" @click="handleEnterLiveRoom" :loading="data.loading.enterLiveRoom"
                  :disabled="robotInfo.runningStatus !== 1" block>
                  {{ $t('robot.runningInfo.enterLiveRoom') }}
                </Button>
                <Button v-if="robotInfo.liveRoomId" type="primary" @click="handleExitLiveRoom"
                  :loading="data.loading.exitLiveRoom" block>
                  {{ $t('robot.runningInfo.exitLiveRoom') }}
                </Button>
              </Space>
            </Card>
          </div>
        </Col>

        <!-- 右侧：直播间功能 -->
        <Col :span="16">
          <div class="right-panel">
            <!-- 直播间选择 -->
            <div v-if="!data.selectedLiveRoom" class="live-room-selection">
              <Card :title="$t('robot.runningInfo.selectLiveRoom')">
                <template #extra>
                  <Button type="link" @click="loadOnlineLiveRooms({refresh: true})" :loading="data.loading.refreshRooms" size="small">
                    <ReloadOutlined /> 刷新
                  </Button>
                </template>
                <div class="online-rooms">
                  <div v-if="data.onlineLiveRooms.length === 0" class="no-rooms">
                    {{ $t('robot.runningInfo.noOnlineRooms') }}
                  </div>
                  <Table v-else :dataSource="data.onlineLiveRooms" :columns="data.liveRoomColumns" :pagination="false"
                    size="small" :rowClassName="getRowClassName" @rowClick="selectLiveRoom">
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex === 'action'">
                        <div style="display: flex; align-items: center; gap: 8px;">
                          <Button 
                            type="link" 
                            size="small" 
                            @click="selectLiveRoom(record)"
                            :class="{ 'selected-button': data.preSelectedLiveRoom?.id === record.id }"
                          >
                            {{ data.preSelectedLiveRoom?.id === record.id ? '已预选' : '选择' }}
                          </Button>
                          <span v-if="data.preSelectedLiveRoom?.id === record.id" class="pre-selected-indicator">●</span>
                        </div>
                      </template>
                      <template v-else-if="column.dataIndex === 'number_of_people'">
                        <span>{{ record.number_of_people || 0 }}人</span>
                      </template>
                      <template v-else-if="column.dataIndex === 'start_time'">
                        <span>{{ formatTime(record.start_time) }}</span>
                      </template>
                    </template>
                  </Table>
                </div>
              </Card>
            </div>

            <!-- 直播间功能 -->
            <LiveRoomPanel 
              v-else 
              :selectedLiveRoom="data.selectedLiveRoom"
              :liveRoomId="robotInfo.liveRoomId"
              :robotUuid="robotInfo.robotUuid"
              :balance="robotInfo.balance"
              :token="data.wsToken"
              @exit="handleExitLiveRoom"
              @update:balance="(newBalance) => robotInfo.balance = newBalance"
            />
          </div>
        </Col>
      </Row>
    </div>




  </Modal>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, onMounted, onUnmounted } from "vue";
import { $t } from '@vben/locales';
import { Modal, Card, Button, Space, Row, Col, message, Table } from 'ant-design-vue';
import { takeoverApi } from '#/api';
import LiveRoomPanel from './LiveRoomPanel.vue';
import { ReloadOutlined } from '@ant-design/icons-vue';

interface Emits {
  (e: 'close', submit: Boolean): void
}
const emits = defineEmits<Emits>()



// 响应式数据
const data = reactive({
  isShowModal: false,
  loading: {
    takeOver: false,
    refreshRooms: false,
    login: false,
    logout: false,
    enterLiveRoom: false,
    exitLiveRoom: false,
  },
  onlineLiveRooms: [],
  selectedLiveRoom: null,
  preSelectedLiveRoom: null, // 预选中的直播间
  liveRoomColumns: [
    {
      title: '直播间名称',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      width: 120
    },
    {
      title: '主播昵称',
      dataIndex: 'nick_name',
      key: 'nick_name',
      width: 80
    },
    {
      title: '在线人数',
      dataIndex: 'number_of_people',
      key: 'number_of_people',
      width: 80
    },
    {
      title: '开播时间',
      dataIndex: 'start_time',
      key: 'start_time',
      width: 120
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100
    }
  ],


  runningStatusMap: {
    1: '运行中',
    2: '已停止',
    3: '异常'
  },
  currentBehaviorMap: {
    1: '空闲',
    2: '观看直播',
    3: '互动',
    4: '异常'
  }
});

// 机器人信息
const robotInfo = reactive({
  robotUuid: '',
  robotAccount: '',
  robotNickName: '',
  runningStatus: 0,
  currentBehavior: 0,
  liveRoomId: '',
  liveRoomName: '',
  balance: 0
});

// 组件方法
function _open(item) {
  data.isShowModal = true;
  Object.assign(robotInfo, item);
  robotInfo.robotUuid = item.robotUuid;
  // 先获取机器人余额
  loadRobotBalance();
  // 再接管机器人控制权
  handleTakeOver();
}

function _close() {
  // 释放机器人控制权
  handleRelease();
  // 清空直播间相关信息
  if (robotInfo.liveRoomId) {
    robotInfo.liveRoomId = '';
    robotInfo.liveRoomName = '';
    data.selectedLiveRoom = null;
  }
  data.isShowModal = false;
  emits('close', true);
}

function _closeWithoutRelease() {
  data.isShowModal = false;
  emits('close', false);
}

async function handleTakeOver() {
  data.loading.takeOver = true;
  try {
    const res = await takeoverApi.takeOver({
      robotUuid: robotInfo.robotUuid,
      durationMinutes: 30 // 默认控制30分钟
    });
    if (res.error) {
      message.error(res.error.message || '接管失败');
      _closeWithoutRelease();
      return;
    }
    message.success('接管成功');
    // 接管成功后加载最新数据
    loadOnlineLiveRooms({ refresh: true });
  } catch (error) {
    message.error('接管失败');
    _closeWithoutRelease();
  } finally {
    data.loading.takeOver = false;
  }
}

async function handleRelease() {
  try {
    // 如果机器人在直播间内，先退出直播间
    if (robotInfo.liveRoomId) {
      try {
        await takeoverApi.quitLiveRoom({ robotUuid: robotInfo.robotUuid });
      } catch (error) {
        console.error('退出直播间失败:', error);
      }
    }
    // 然后释放控制权
    await takeoverApi.release({ robotUuid: robotInfo.robotUuid });
    message.success('已释放控制权');
  } catch (error) {
    console.error('释放控制权失败:', error);
  }
}

async function loadRobotBalance() {
  try {
    const res = await takeoverApi.getFee({ robotUuid: robotInfo.robotUuid });
    if (res.data && !res.error) {
      // 真实金额计算：总金额 - 已使用金额 + 申请未使用金额
      const totalAmount = res.data.totalAmount || 0;
      const usedAmount = res.data.usedAmount || 0;
      const applyAmount = res.data.applyAmount || 0;
      
      robotInfo.balance = totalAmount - usedAmount + applyAmount;
    }
  } catch (error) {
    console.error('获取余额失败:', error);
  }
}

async function loadOnlineLiveRooms(params) {
  data.loading.refreshRooms = true;
  try {
    const res = await takeoverApi.getLiveRooms({ refresh: params?.refresh ,robotUuid: robotInfo.robotUuid });
    if (res.data && !res.error) {
      data.onlineLiveRooms = res.data || [];
      message.success(`已刷新，共 ${data.onlineLiveRooms.length} 个在线直播间`);
    } else {
      message.error(res.error?.message || '获取直播间列表失败');
    }
  } catch (error) {
    console.error('获取在线直播间失败:', error);
    message.error('获取直播间列表失败');
  } finally {
    data.loading.refreshRooms = false;
  }
}

function getStatusClass(status) {
  return {
    'status-running': status === 1,
    'status-stopped': status === 2,
    'status-error': status === 3
  };
}

// 通用功能方法
async function handleLogin() {
  data.loading.login = true;
  try {
    const res = await takeoverApi.robotLogin({ robotUuid: robotInfo.robotUuid });
    if (res.error) {
      message.error(res.error.message || '登录失败');
      return;
    }
    message.success('登录成功');
    robotInfo.runningStatus = 1;
    // 存储用户信息和token（如果需要）
    emits('close', true);
  } catch (error) {
    message.error('登录失败');
  } finally {
    data.loading.login = false;
  }
}

async function handleLogout() {
  data.loading.logout = true;
  try {
    const res = await takeoverApi.robotLogout({ robotUuid: robotInfo.robotUuid });
    if (res.error) {
      message.error(res.error.message || '登出失败');
      return;
    }
    message.success('登出成功');
    robotInfo.runningStatus = 2;
    robotInfo.liveRoomId = '';
    robotInfo.liveRoomName = '';
    data.selectedLiveRoom = null;
    closeWebSocket();
    emits('close', true);
  } catch (error) {
    message.error('登出失败');
  } finally {
    data.loading.logout = false;
  }
}

async function handleEnterLiveRoom() {
  if (!data.preSelectedLiveRoom) {
    message.warning('请先预选直播间');
    return;
  }

  data.loading.enterLiveRoom = true;
  try {
    const res = await takeoverApi.enterLiveRoom({
      robotUuid: robotInfo.robotUuid,
      roomId: parseInt(data.preSelectedLiveRoom?.user_id) || data.preSelectedLiveRoom?.user_id
    });
    if (res.error) {
      message.error(res.error.message || '进入直播间失败');
      return;
    }
    message.success('进入直播间成功');
    // 进入直播间成功后才正式选中
    data.selectedLiveRoom = data.preSelectedLiveRoom;
    robotInfo.liveRoomId = data.selectedLiveRoom?.user_id;
    robotInfo.liveRoomName = data.selectedLiveRoom?.title;
    // 清空预选状态
    data.preSelectedLiveRoom = null;
    
    // 刷新机器人信息
    loadRobotBalance();
    

    emits('close', true);
  } catch (error) {
    message.error('进入直播间失败');
  } finally {
    data.loading.enterLiveRoom = false;
  }
}

async function handleExitLiveRoom() {
  data.loading.exitLiveRoom = true;
  try {
    const res = await takeoverApi.quitLiveRoom({ robotUuid: robotInfo.robotUuid });
    if (res.error) {
      message.error(res.error.message || '退出直播间失败');
      return;
    }
    message.success('退出直播间成功');
    robotInfo.liveRoomId = '';
    robotInfo.liveRoomName = '';
    data.selectedLiveRoom = null;
    // 刷新机器人信息
    loadRobotBalance();
    // 刷新直播间列表
    loadOnlineLiveRooms({ refresh: true });
    emits('close', true);
  } catch (error) {
    message.error('退出直播间失败');
  } finally {
    data.loading.exitLiveRoom = false;
  }
}

// 直播间功能方法
function selectLiveRoom(room) {
  // 如果点击的是已经预选中的房间，则取消预选
  if (data.preSelectedLiveRoom?.id === room.id) {
    data.preSelectedLiveRoom = null;
  } else {
    // 否则设置新的预选房间
    data.preSelectedLiveRoom = room;
  }
}

function formatTime(timestamp) {
  if (!timestamp) return '-';
  const date = new Date(timestamp * 1000);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

function getRowClassName(record) {
  if (record.id === data.selectedLiveRoom?.id) {
    return 'selected-row';
  } else if (record.id === data.preSelectedLiveRoom?.id) {
    return 'pre-selected-row';
  }
  return '';
}



defineExpose({
  _open,
  _close
});

// 生命周期
onUnmounted(() => {
});
</script>

<style scoped>
.takeover-container {
  height: 600px;
}

.left-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.right-panel {
  height: 100%;
}

.robot-info-card,
.functions-card {
  flex: 1;
}

.robot-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.label {
  font-weight: 500;
  color: #666;
}

.value {
  color: #333;
}

.status-running {
  color: #52c41a;
}

.status-stopped {
  color: #faad14;
}

.status-error {
  color: #ff4d4f;
}

.online-rooms {
  max-height: 200px;
  overflow-y: auto;
}

.room-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.room-item {
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.room-item:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.room-item.selected {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.room-name {
  font-weight: 500;
  font-size: 14px;
}

.room-id,
.anchor-name {
  font-size: 12px;
  color: #666;
}

.live-room-content {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.live-stream-section {
  flex: 1;
  position: relative;
  margin-bottom: 16px;
}

.live-video {
  width: 100%;
  height: 300px;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
}

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

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

.chat-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120px;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(10px);
  border-radius: 0 0 8px 8px;
  padding: 8px;
  overflow: hidden;
}

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

.chat-message {
  font-size: 12px;
  color: #fff;
  line-height: 1.4;
}

.chat-message.own-message {
  color: #ffd700;
}

.sender {
  font-weight: 500;
  margin-right: 4px;
}

.time {
  font-size: 10px;
  color: #ccc;
  margin-left: 8px;
}

.control-section {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.chat-input-section {
  padding-top: 16px;
}

.no-rooms {
  text-align: center;
  color: #999;
  padding: 20px;
}

.selected-row {
  background-color: #e6f7ff !important;
}

.selected-row:hover {
  background-color: #bae7ff !important;
}

.selected-row td {
  border-color: #1890ff !important;
}

.pre-selected-row {
  background-color: #fff7e6 !important;
  border-left: 3px solid #faad14;
}

.selected-button {
  color: #faad14;
  font-weight: bold;
}

.pre-selected-indicator {
  color: #faad14;
  font-size: 16px;
  font-weight: bold;
}
</style>