<script lang="ts" setup>
/**
 * VIP 等级配置：卡片布局 + 筛选（名称/编码/等级组/状态）
 */
import { onMounted, reactive, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  Empty,
  Input,
  Pagination,
  Select,
  Tag,
  message,
} from 'ant-design-vue';

import { TableAction } from '#/components/table-action';

import { deleteVipLevel, getVipLevelList } from './api';
import FormModal from './components/modal.vue';
import {
  STATUS_OPTIONS,
  VIP_TIER_GROUP_OPTIONS,
} from './config/constants';

defineOptions({ name: 'VipLevel' });

const loading = ref(false);
const list = ref<any[]>([]);
const total = ref(0);
const page = reactive({ current: 1, pageSize: 12 });
const filters = reactive({
  code: '',
  name: '',
  tier_group: undefined as number | undefined,
  status: undefined as number | undefined,
});

const [FormModalComp, formModalApi] = useVbenModal({
  connectedComponent: FormModal,
});

/** 拉取卡片数据 */
async function loadList() {
  loading.value = true;
  try {
    const res = await getVipLevelList({
      page: page.current,
      pageSize: page.pageSize,
      code: filters.code || undefined,
      name: filters.name || undefined,
      tier_group: filters.tier_group,
      status: filters.status,
    });
    list.value = res?.items || [];
    total.value = Number(res?.total || 0);
  } finally {
    loading.value = false;
  }
}

function onSearch() {
  page.current = 1;
  loadList();
}

function onReset() {
  filters.code = '';
  filters.name = '';
  filters.tier_group = undefined;
  filters.status = undefined;
  onSearch();
}

const showModal = (data: any = {}, isUpdate = false) => {
  formModalApi.setData({
    values: data,
    update: isUpdate,
    gridApi: { query: loadList, reload: loadList },
  });
  formModalApi.open();
};

const handleDelete = (id: number) => {
  deleteVipLevel({ ids: [id] }).then(() => {
    message.success('删除成功');
    loadList();
  });
};

function tierLabel(v: number) {
  return VIP_TIER_GROUP_OPTIONS.find((o) => o.value === v)?.label || '-';
}

onMounted(loadList);
</script>
<template>
  <Page auto-content-height title="VIP等级配置">
    <FormModalComp />
    <div class="p-4">
      <div class="mb-4 flex flex-wrap items-center gap-3">
        <Input
          v-model:value="filters.code"
          allow-clear
          placeholder="等级编码"
          class="w-36"
          @press-enter="onSearch"
        />
        <Input
          v-model:value="filters.name"
          allow-clear
          placeholder="等级名称"
          class="w-40"
          @press-enter="onSearch"
        />
        <Select
          v-model:value="filters.tier_group"
          allow-clear
          placeholder="等级组"
          class="w-32"
          :options="VIP_TIER_GROUP_OPTIONS"
        />
        <Select
          v-model:value="filters.status"
          allow-clear
          placeholder="状态"
          class="w-28"
          :options="STATUS_OPTIONS"
        />
        <Button type="primary" @click="onSearch">查询</Button>
        <Button @click="onReset">重置</Button>
        <div class="ml-auto">
          <TableAction
            :actions="[
              {
                label: '新增等级',
                type: 'primary',
                icon: 'ant-design:plus-outlined',
                onClick: () => showModal({}, false),
              },
            ]"
          />
        </div>
      </div>
      <Empty v-if="!loading && !list.length" description="暂无等级数据" />
      <div
        v-else
        class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
      >
        <Card
          v-for="item in list"
          :key="item.id"
          size="small"
          class="vip-level-card"
          :loading="loading"
        >
          <div class="flex flex-col items-center text-center">
            <img
              v-if="item.badge_url"
              :src="item.badge_url"
              alt=""
              class="mb-3 h-24 w-24 object-contain"
            />
            <div
              v-else
              class="mb-3 flex h-24 w-24 items-center justify-center rounded-full bg-gray-100 text-2xl font-bold text-gray-400 dark:bg-gray-800 dark:text-gray-500"
            >
              {{ item.code }}
            </div>
            <div class="mb-1 text-base font-semibold dark:text-gray-100">
              {{ item.name }}
              <span class="ml-1 text-sm font-normal text-gray-500 dark:text-gray-400">{{ item.code }}</span>
            </div>
            <div class="mb-2 flex flex-wrap justify-center gap-1">
              <Tag>{{ tierLabel(item.tier_group) }}</Tag>
              <Tag :color="item.status === 1 ? 'success' : 'default'">
                {{ item.status === 1 ? '启用' : '禁用' }}
              </Tag>
              <Tag color="blue">¥{{ item.price }}</Tag>
            </div>
            <div class="mb-3 line-clamp-2 min-h-10 text-xs text-gray-500 dark:text-gray-400">
              {{ item.description || '暂无说明' }}
            </div>
            <TableAction
              :actions="[
                { label: '编辑', onClick: () => showModal(item, true) },
                {
                  label: '删除',
                  color: 'error',
                  popConfirm: {
                    title: '确定删除该等级？',
                    onConfirm: () => handleDelete(item.id),
                  },
                },
              ]"
            />
          </div>
        </Card>
      </div>
      <div class="mt-4 flex justify-end">
        <Pagination
          v-model:current="page.current"
          v-model:page-size="page.pageSize"
          :total="total"
          :page-size-options="['12', '24', '48']"
          show-size-changer
          show-quick-jumper
          @change="loadList"
          @show-size-change="loadList"
        />
      </div>
    </div>
  </Page>
</template>
<style scoped>
.vip-level-card :deep(.ant-card-body) {
  padding: 20px 16px;
}
</style>
