<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="shop-event-table"
      >
        <template #toolbar>
          <search @search="reload" :selection="selection" @add="openEdit" />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <a-image :src="record.image" :width="50" :height="50" fit="cover" />
          </template>
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status === 0" color="blue">未开始</a-tag>
            <a-tag v-if="record.status === 1" color="green">报名中</a-tag>
            <a-tag v-if="record.status === 2" color="orange">已截止</a-tag>
            <a-tag v-if="record.status === 3" color="red">已结束</a-tag>
          </template>
          <template v-if="column.key === 'entryFee'">
            <span :class="record.entryFee > 0 ? 'text-price' : 'text-free'">
              {{ record.entryFee > 0 ? '¥' + record.entryFee : '免费' }}
            </span>
          </template>
          <template v-if="column.key === 'isHot'">
            <a-tag v-if="record.isHot === 1" color="red">热门</a-tag>
            <span v-else class="text-gray">-</span>
          </template>
          <template v-if="column.key === 'participants'">
            <span>{{ record.paidCount || 0 }}/{{ record.maxParticipants || '不限' }}</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="openRegistration(record)">报名记录</a>
              <a-divider type="vertical" />
              <a @click="openEdit(record)">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此赛事吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <ShopEventEdit v-model:visible="showEdit" :data="current" @done="reload" />

    <!-- 报名记录弹窗 -->
    <ShopEventRegistrationList
      v-model:visible="showRegistration"
      :event="currentEvent"
    />
  </a-page-header>
</template>

<script lang="ts" setup>
  import { createVNode, ref, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import { toDateString } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import { getPageTitle } from '@/utils/common';
  import ShopEventEdit from './components/shopEventEdit.vue';
  import ShopEventRegistrationList from './components/shopEventRegistrationList.vue';
  import { pageShopEvent, removeShopEvent } from '@/api/shop/shopEvent';
  import type { ShopEvent, ShopEventParam } from '@/api/shop/shopEvent/model';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<ShopEvent[]>([]);
  // 当前编辑数据
  const current = ref<ShopEvent | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示报名记录弹窗
  const showRegistration = ref(false);
  // 当前赛事
  const currentEvent = ref<ShopEvent | null>(null);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    return pageShopEvent({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 完整的列配置
  const allColumns = ref<ColumnItem[]>([
    {
      title: '赛事ID',
      dataIndex: 'id',
      key: 'id',
      width: 90,
    },
    {
      title: '封面图',
      dataIndex: 'image',
      key: 'image',
      width: 80,
    },
    {
      title: '赛事名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true
    },
    {
      title: '赛事日期',
      dataIndex: 'eventDate',
      key: 'eventDate',
      width: 160
    },
    {
      title: '赛事地点',
      dataIndex: 'location',
      key: 'location',
      width: 150,
      ellipsis: true
    },
    {
      title: '报名费',
      dataIndex: 'entryFee',
      key: 'entryFee',
      width: 100
    },
    {
      title: '名额',
      dataIndex: 'participants',
      key: 'participants',
      width: 100,
      align: 'center'
    },
    {
      title: '热门',
      dataIndex: 'isHot',
      key: 'isHot',
      width: 80,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
      align: 'center',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => text ? toDateString(text, 'yyyy-MM-dd HH:mm') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 默认显示的核心列
  const defaultVisibleColumns = [
    'name',
    'eventDate',
    'location',
    'entryFee',
    'participants',
    'status',
    'action'
  ];

  // 根据默认可见列过滤显示的列
  const columns = computed(() => {
    return allColumns.value.filter(col =>
      defaultVisibleColumns.includes(col.dataIndex) || col.key === 'action'
    );
  });

  /* 搜索 */
  const reload = (where?: ShopEventParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: ShopEvent) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 打开报名记录弹窗 */
  const openRegistration = (row: ShopEvent) => {
    currentEvent.value = row;
    showRegistration.value = true;
  };

  /* 删除单个 */
  const remove = (row: ShopEvent) => {
    const hide = message.loading('请求中..', 0);
    removeShopEvent(row.id!)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e: Error) => {
        hide();
        message.error(e.message);
      });
  };

  /* 自定义行属性 */
  const customRow = (record: ShopEvent) => {
    return {
      onClick: () => {
        // console.log(record);
      },
      onDblclick: () => {
        openEdit(record);
      }
    };
  };
</script>

<script lang="ts">
  export default {
    name: 'ShopEvent'
  };
</script>

<style lang="less" scoped>
  .text-price {
    color: #f5222d;
    font-weight: 500;
  }

  .text-free {
    color: #52c41a;
  }

  .text-gray {
    color: #999;
  }
</style>
