<template>
  <Page>
    <!-- 查询和全局功能 -->
    <Row>
      <Col :span="24">
      <!-- 查询 -->
      <Space v-if="data.isShowQuery" :wrap="true">
        <Input v-model:value="data.query.configName" allowClear :placeholder="$t('robot.runningConfig.configName')" />
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.status"
          :placeholder="$t('robot.runningConfig.status')" style="width: 120px">
          <SelectOption v-for="(item, index) in data.statusOptions" :key="index" :value="item.value" :label="item.label"
            :text="item.label">{{ item.label }}
          </SelectOption>
        </Select>
        <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="data.query.exclusive"
          :placeholder="$t('robot.runningConfig.exclusive')" style="width: 120px">
          <SelectOption v-for="(item, index) in data.exclusiveOptions" :key="index" :value="item.value" :label="item.label"
            :text="item.label">{{ item.label }}
          </SelectOption>
        </Select>
        <!-- 查询按钮 -->
        <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>
      </Space>

      <!-- 全局功能 -->
      <div style="padding: 15px 0; display: flex; justify-content: space-between; align-items: center;">
        <Button @click="handleOpenAdd" style="background-color: #0084CA;color: white">
          {{ $t('common.add') }}
        </Button>
        <Button @click="handleOpenGlobalConfig" style="background-color: #52c41a;color: white">
          全局配置
        </Button>
      </div>
      </Col>
    </Row>

    <!-- 数据展示 -->
    <Table :dataSource="data.datas" :columns="data.columns" bordered :loading="data.loading"
      :pagination="data.pagination" :scroll="{ x: 2000 }" @change="handleQuery" size="small">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <Button type="link" size="small" @click="handleOpenLiveRoomRelation(record)">直播间</Button>
          <Button type="link" size="small" @click="handleOpenLiveRoomRelationOut(record)">排除直播间</Button>
          <Button type="link" size="small" @click="handleOpenEdit(record)">{{ $t('common.edit') }}</Button>
          <Button type="link" size="small" @click="handleDeleteConfirm(record)">{{ $t('common.delete') }}</Button>
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <span>{{ data.statusMap[record.status] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'exclusive'">
          <span>{{ data.exclusiveMap[record.exclusive] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'chatSwitch'">
          <span>{{ data.switchMap[record.chatSwitch] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'giftSwitch'">
          <span>{{ data.switchMap[record.giftSwitch] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'activitySwitch'">
          <span>{{ data.switchMap[record.activitySwitch] }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'repeatEntecycle'">
          <span>{{ data.repeatEntecycleMap[record.repeatEntecycle] }}</span>
        </template>
      </template>
    </Table>

    <!-- 添加 -->
    <Add ref="addRef" @close="reload"></Add>
    <!-- 编辑 -->
    <Edit ref="editRef" @close="reload"></Edit>
    <!-- 删除 -->
    <DeleteConfirm ref="deleteRef"></DeleteConfirm>
    <!-- 直播间关联管理 -->
    <LiveRoomRelation ref="liveRoomRelationRef" @close="reload"></LiveRoomRelation>
    <!-- 排除直播间关联管理 -->
    <LiveRoomRelationOut ref="liveRoomRelationOutRef" @close="reload"></LiveRoomRelationOut>
    <!-- 全局配置 -->
    <GlobalConfig ref="globalConfigRef" @close="reload"></GlobalConfig>
  </Page>
</template>

<script setup lang="ts">
import DeleteConfirm from "#/components/myui/deleteConfirm/index.vue";
import Add from "./components/add.vue";
import Edit from "./components/edit.vue";
import LiveRoomRelation from "./components/liveRoomRelation.vue";
import LiveRoomRelationOut from "./components/liveRoomRelationOut.vue";
import GlobalConfig from "./components/globalConfig.vue";
import { reactive, onMounted, ref } from "vue";
import { $t } from '@vben/locales';
import { Page } from '@vben/common-ui';
import { Button, Input, Space, Table, Row, Col, message, Select } from 'ant-design-vue';
import { rRunningConfig } from '#/api';
import { d } from './index';

const SelectOption = Select.Option;

const data = reactive({
  ...d,
  statusOptions: [
    { label: $t('robot.runningConfig.statusOptions.v0'), value: 0 },
    { label: $t('robot.runningConfig.statusOptions.v1'), value: 1 }
  ],
  exclusiveOptions: [
    { label: $t('robot.runningConfig.exclusiveOptions.v0'), value: 0 },
    { label: $t('robot.runningConfig.exclusiveOptions.v1'), value: 1 }
  ],
  switchOptions: [
    { label: $t('robot.runningConfig.switchOptions.0'), value: 0 },
    { label: $t('robot.runningConfig.switchOptions.1'), value: 1 }
  ],
  repeatEntecycleOptions: [
    { label: $t('robot.runningConfig.repeatEntecycleOptions.1'), value: 1 },
    { label: $t('robot.runningConfig.repeatEntecycleOptions.2'), value: 2 },
    { label: $t('robot.runningConfig.repeatEntecycleOptions.3'), value: 3 },
    { label: $t('robot.runningConfig.repeatEntecycleOptions.4'), value: 4 }
  ]
});

const addRef = ref();
const deleteRef = ref();
const editRef = ref();
const liveRoomRelationRef = ref();
const liveRoomRelationOutRef = ref();
const globalConfigRef = ref();

// 选择框过滤方法
const selectFilterOption = (input: string, option: any) => {
  return option.text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

onMounted(() => {
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
})

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

function handleOpenEdit(item) {
  editRef.value._open(item);
}

function handleOpenLiveRoomRelation(item) {
  liveRoomRelationRef.value._open(item);
}

function handleOpenLiveRoomRelationOut(item) {
  liveRoomRelationOutRef.value._open(item);
}

function handleOpenGlobalConfig() {
  globalConfigRef.value._open();
}

function handleDeleteConfirm(item) {
  deleteRef.value._open($t('common.deleteConfirm') + '【' + item.configName + '】?').then(() => {
    rRunningConfig.removeByUid(item).then((res) => {
      if (res.error) {
        return;
      }
      message.success($t('common.deleteSuccess'));
      handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
    })
  })
}

/**
 * 包装查询参数
 * @param page
 * @param filter
 * @param sorter
 */
function wrapQueryParam(page, filter, sorter) {
  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];
  }
  //过滤
  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 = {}
  handleQuery({ current: 1, pageSize: data.pagination.pageSize });
}

/**
 * 查询
 * @param page
 * @param filter
 * @param sorter
 */
function handleQuery(page, filter, sorter) {
  data.loading = true;
  let param = wrapQueryParam(page, filter, sorter);
  rRunningConfig.queryPage(param).then((res) => {
    if (res.error) {
      return;
    }
    data.datas = res.data.list || [];
    data.pagination.total = res.data.total || 0;
    data.pagination.current = res.data.current || res.data.pageNum || 1;
    data.pagination.pageSize = res.data.pageSize && res.data.pageSize > 10 ? res.data.pageSize : 10;
    
  }).finally(() => {
    data.loading = false;
  })
}

function reload() {
  handleQuery({ current: data.pagination.current, pageSize: data.pagination.pageSize });
}
</script>