<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.liveRoomId" allowClear placeholder="请输入直播间ID" />
        <Input v-model:value="data.query.liveRoomName" allowClear placeholder="请输入直播间名称" />
        <Input v-model:value="data.query.anchorId" allowClear placeholder="请输入主播id" />
        <Input v-model:value="data.query.anchorName" allowClear placeholder="请输入主播名称" />

        <!-- 查询按钮 -->
        <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="handleOpenAdd" :disabled="data.loading">
          {{ $t('common.add') }}
        </Button>
        <Button type="primary" @click="handleOpenAddOnline" :disabled="data.loading">
          在线添加
        </Button>
        <Button type="primary" @click="handleBatchDelete" :disabled="selectedRowKeys.length === 0 || data.loading">
          {{ $t('common.batchDelete') }}
        </Button>

        <Dropdown>
          <template #overlay>
            <Menu @click="handleExportClick">
              <MenuItem key="1">
              导出全部数据
              </MenuItem>
              <MenuItem key="2">
              导出当前数据
              </MenuItem>
            </Menu>
          </template>
          <Button>
            导出
            <DownOutlined />
          </Button>
        </Dropdown>
      </Space>
    </div>

    <!-- 数据展示 -->
    <Table :dataSource="data.datas" :columns="data.columns" bordered :loading="data.loading"
      :pagination="data.pagination" @change="handleQuery" size="small" :rowSelection="rowSelection"
      :rowKey="(record) => record.uuid">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <Button type="link" size="small" @click="handleOpenEdit(record)">{{ $t('common.edit') }}</Button>
          <Button type="link" size="small" danger @click="handleDeleteConfirm(record)">{{ $t('common.delete')
            }}</Button>
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <span>{{ data.statusMap[record.status] }}</span>
        </template>
      </template>
    </Table>

    <!-- 添加 -->
    <Add ref="addRef" @close="reload"></Add>
    <!-- 在线添加 -->
    <AddOnline ref="addOnlineRef" @close="reload"></AddOnline>
    <!-- 编辑 -->
    <Edit ref="editRef" @close="reload"></Edit>
    <!-- 删除确认 -->
    <DeleteConfirm ref="deleteRef"></DeleteConfirm>
  </Modal>
</template>

<script setup lang="ts">
import DeleteConfirm from "#/components/myui/deleteConfirm/index.vue";
import Add from "./liveRoomRelationAddOut.vue";
import AddOnline from "./liveRoomRelationAddOnlineOut.vue";
import Edit from "./liveRoomRelationEditOut.vue";
import { reactive, ref } from "vue";
import { $t } from '@vben/locales';
import { Modal, Input, Table, Button, Space, message, Select, Dropdown, Menu } from 'ant-design-vue';
import { DownOutlined } from '@ant-design/icons-vue';

const { Item: MenuItem } = Menu;
import { liveRoomRelation, exportFile } from '#/api';

const SelectOption = Select.Option;

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: 'liveRoomId',
    width: 120,
    sorter: true,
  },
  {
    title: '直播间名称',
    dataIndex: 'liveRoomName',
    width: 150
  },
  {
    title: '主播id',
    dataIndex: 'anchorCode',
    width: 120,
    sorter: true,
  },
  {
    title: '主播名称',
    dataIndex: 'anchorName',
    width: 120
  },
  {
    title: $t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
    width: 120
  }
];

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

const addRef = ref();
const addOnlineRef = ref();
const editRef = ref();
const deleteRef = ref();

/**
 * 重置内容
 */
function reload(success) {
  success && handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}

function handleOpenAdd() {
  addRef.value._open(data.runningConfigInfo);
}

function handleOpenAddOnline() {
  addOnlineRef.value._open(data.runningConfigInfo);
}

function handleOpenEdit(record) {
  editRef.value._open(record, data.runningConfigInfo);
}

function handleDeleteConfirm(record) {
  deleteRef.value._open($t('common.deleteConfirm') + '【' + record.liveRoomName + '】?').then(() => {
    liveRoomRelation.removeByUid({ uuid: record.uuid }).then(res => {
      if (!res.error) {
        message.success($t('common.deleteSuccess'));
        handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
      }
    }).catch(() => {
      message.error($t('common.deleteFailed'));
    });
  });
}

function handleBatchDelete() {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的数据');
    return;
  }
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的${selectedRowKeys.value.length}条数据吗？`,
    onOk: async () => {
      try {
        await liveRoomRelation.removeBatchByUid(selectedRowKeys.value);
        message.success('删除成功');
        reload();
        selectedRowKeys.value = [];
      } catch (error) {
        message.error('删除失败');
      }
    }
  });
}

function handleExportClick({ key }) {
  if (key === '1') {
    handleExportAll();
  } else if (key === '2') {
    handleExportPart();
  }
}
function handleExportAll() {
  // 包装查询参数，确保导出的数据与查询条件一致
  const param = wrapQueryParam();
  param.pageNum = 1;
  param.pageSize = 100000;
  exportFile(liveRoomRelation.exportAllUrl(param), param, '排除直播间' + new Date().getTime() + '.xlsx');
}

function handleExportPart() {
  // 包装查询参数，确保导出的数据与查询条件一致
  const param = wrapQueryParam();
  exportFile(liveRoomRelation.exportPartUrl(param), param, '排除直播间' + new Date().getTime() + '.xlsx');
}

/**
 * 包装查询参数
 * @param page
 * @param filter
 * @param sorter
 */
function wrapQueryParam(page, filter, sorter) {
  let { current, pageSize } = { ...data.pagination, ...(page || {}) };
  let param = {
    pageNum: current,
    pageSize: pageSize,
    relationCode: data.runningConfigInfo?.uuid
  };
  //查询
  for (const key in data.query) {
    if (data.query[key] == null || data.query[key] === '') {
      continue;
    }
    param[key] = data.query[key];
  }
  //过滤
  if (filter) {
    for (const key in filter) {
      const value = Array.isArray(filter[key]) && filter[key].length > 0 ? filter[key][0] : filter[key];
      param[key] = value || param[key];
    }
  }
  //排序
  if (sorter && sorter.field && sorter.order) {
    param.sorts = [{ name: sorter.field, desc: sorter.order == 'descend' }];
  }
  return param;
}

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

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

  data.loading = true;
  liveRoomRelation.queryPage(param).then(res => {
    if (res.data) {
      data.datas = res.data.list || [];
      data.pagination.current = res.data.pageNum || 1;
      data.pagination.pageSize = res.data.pageSize || 10;
      data.pagination.total = res.data.total;
    }
  }).finally(() => {
    data.loading = 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>