<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null" title="在线添加直播间关联"
    width="50%" @cancel="_close">

    <!-- 查询功能 -->
    <div style="margin-bottom: 16px;">
      <Space :wrap="true" style="margin-bottom: 10px;">
        <Input v-model:value="data.query.roomId" allowClear placeholder="请输入直播间ID" style="width: 150px" />
        <Input v-model:value="data.query.roomName" allowClear placeholder="请输入直播间名称" style="width: 150px" />
        <Input v-model:value="data.query.anchorName" allowClear placeholder="请输入主播名称" style="width: 150px" />

        <!-- 查询按钮 -->
        <Button @click="handleQuery" :loading="data.loading" :disabled="data.loading"
          style="background-color: #0084CA;color: white">
          {{ $t('common.search') }}
        </Button>
        <Button @click="resetQuery" :loading="data.loading" :disabled="data.loading" danger>
          {{ $t('common.reset') }}
        </Button>

        <Button type="primary" @click="handleBatchAdd" :disabled="selectedRowKeys.length === 0 || data.loading">
          批量添加选中直播间
        </Button>

        <!-- 刷新缓存按钮 -->
        <Button @click="handleRefreshCache" :loading="data.refreshCacheLoading"
          :disabled="data.loading || data.refreshCacheLoading" type="dashed">
          刷新缓存
        </Button>
      </Space>
    </div>

    <!-- 数据展示 -->
    <Table :dataSource="data.datas" :columns="data.columns" bordered :loading="data.loading"
      :pagination="data.pagination" :scroll="{ x: 1200 }" @change="handleQuery" size="small"
      :rowSelection="rowSelection" :rowKey="(record) => record.id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'status'">
          <Tag :color="record.status === 1 ? 'green' : 'red'">
            {{ record.status === 1 ? '启用' : '禁用' }}
          </Tag>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          <span>{{ formatTime(record.createTime) }}</span>
        </template>
      </template>
    </Table>
  </Modal>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { $t } from '@vben/locales';
import { Modal, Input, Table, Button, Space, message, Tag } from 'ant-design-vue';
import { liveService } from '#/api';
import { liveRoomRelation } from '#/api';

interface Emits {
  (e: 'close', submit: Boolean): void
}

const emits = defineEmits<Emits>();

// 选中的行的key
const selectedRowKeys = ref([]);
const selectedRows = ref([]);

// 行选择配置
const rowSelection = {
  selectedRowKeys,
  onChange: (newSelectedRowKeys: string[], newSelectedRows: any[]) => {
    selectedRowKeys.value = newSelectedRowKeys;
    selectedRows.value = newSelectedRows;
  }
};

// 列定义
const columns = [
  {
    title: '直播间ID',
    dataIndex: 'user_id',
    width: 120
  },
  {
    title: '直播间名称',
    dataIndex: 'title',
    width: 150
  },
  {
    title: '主播id',
    dataIndex: 'user_number',
    width: 120
  },
  {
    title: '主播名称',
    dataIndex: 'nick_name',
    width: 120
  },
];

const data = reactive({
  isShowModal: false,
  loading: false,
  refreshCacheLoading: false,
  pagination: {
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: (total, range) => `共 ${total} 条`,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100', '500'],
    showQuickJumper: true,
  },
  datas: [],
  query: {
    roomId: '',
    roomName: '',
    anchorName: '',
  },
  columns,
  runningConfigInfo: null
});

/**
 * 格式化时间
 */
function formatTime(timestamp) {
  if (!timestamp) return '-';
  return new Date(timestamp).toLocaleString('zh-CN');
}

/**
 * 包装查询参数
 */
function wrapQueryParam(page) {
  let { current, pageSize } = { ...data.pagination, ...(page || {}) };
  let param = {
    pageNum: current,
    pageSize: pageSize
  };

  // 查询条件
  for (const key in data.query) {
    if (data.query[key] == null || data.query[key] === '') {
      continue;
    }
    param[key] = data.query[key];
  }

  return param;
}

/**
 * 重置查询
 */
function resetQuery() {
  data.query = {
    roomId: '',
    roomName: '',
    anchorName: '',
  };
  // 清空选中状态
  selectedRowKeys.value = [];
  selectedRows.value = [];
  data.pagination.current = 1;
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}

/**
 * 查询方法
 */
function handleQuery(page) {
  let param = wrapQueryParam(page);

  data.loading = true;
  liveService.getLiveRoomList().then(res => {
    if (res.data && Array.isArray(res.data)) {
      // 过滤数据
      let filteredData = res.data.filter(item => {
        let match = true;
        if (param.roomId && !item.roomId?.toString().includes(param.roomId)) {
          match = false;
        }
        if (param.roomName && !item.roomName?.includes(param.roomName)) {
          match = false;
        }
        if (param.anchorName && !item.anchorName?.includes(param.anchorName)) {
          match = false;
        }
        return match;
      });

      // 分页处理
      const startIndex = (param.pageNum - 1) * param.pageSize;
      const endIndex = startIndex + param.pageSize;
      data.datas = filteredData.slice(startIndex, endIndex);
      data.pagination.current = param.pageNum;
      data.pagination.pageSize = param.pageSize;
      data.pagination.total = filteredData.length;
    } else {
      data.datas = [];
      data.pagination.total = 0;
    }
  }).catch(error => {
    console.error('获取直播间列表失败:', error);
    message.error('获取直播间列表失败');
    data.datas = [];
    data.pagination.total = 0;
  }).finally(() => {
    data.loading = false;
  });
}

/**
 * 批量添加
 */
function handleBatchAdd() {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要添加的直播间');
    return;
  }

  const selectedLiveRooms = selectedRows.value;
  const queries = selectedLiveRooms.map(room => ({
    relationType: 'runningConfigOut',
    liveRoomId: room.user_id,
    liveRoomName: room.title,
    anchorId: room.number_of_people,
    anchorName: room.nick_name,
    anchorCode: room.user_number,
    anchorAvatar: room.heade_portrait,
    configName: data.runningConfigInfo?.name || '',
    relationCode: data.runningConfigInfo?.uuid || '',
    status: 1,
    runningConfigUuid: data.runningConfigInfo?.uuid
  }));

  Modal.confirm({
    title: '批量添加确认',
    content: `确定要批量添加选中的 ${selectedLiveRooms.length} 个直播间关联吗？`,
    onOk() {
      data.loading = true;
      liveRoomRelation.addBatch({ queries }).then(res => {
        if (!res.error) {
          message.success(`成功添加 ${selectedLiveRooms.length} 个直播间关联`);
          _close(true);
        } else {
          message.error('批量添加失败');
        }
      }).catch(error => {
        console.error('批量添加失败:', error);
        message.error('批量添加失败');
      }).finally(() => {
        data.loading = false;
      });
    }
  });
}

/**
 * 刷新缓存
 */
function handleRefreshCache() {
  Modal.confirm({
    title: '刷新缓存确认',
    content: '确定要刷新直播间缓存吗？刷新后可能需要重新加载数据。',
    onOk() {
      data.refreshCacheLoading = true;
      liveService.resetCache().then(res => {
        if (!res.error) {
          message.success('缓存刷新成功');
          // 刷新后重新查询数据
          handleQuery();
        } else {
          message.error('缓存刷新失败');
        }
      }).catch(error => {
        console.error('刷新缓存失败:', error);
        message.error('刷新缓存失败');
      }).finally(() => {
        data.refreshCacheLoading = false;
      });
    }
  });
}

function _open(runningConfigInfo) {
  data.isShowModal = true;
  data.runningConfigInfo = runningConfigInfo;
  // 重置查询
  resetQuery();
}

function _close(submit: Boolean = false) {
  data.isShowModal = false;
  data.datas = [];
  // 清空选中状态
  selectedRowKeys.value = [];
  selectedRows.value = [];
  submit && typeof submit == 'boolean' && emits('close', submit);
}

//开放方法
defineExpose({ _open, _close });
</script>

<style scoped></style>