<template>
  <div>
    <!-- 1. 筛选区 -->
    <ElCard class="art-search-card" shadow="never">
      <ElForm :model="formFilters" label-width="100px">
        <ElRow :gutter="16">
          <ElCol :span="8">
            <ElFormItem :label="$t('quotaPackage.search.quotaType')">
              <ElSelect
                v-model="formFilters.quotaType"
                :placeholder="$t('quotaPackage.search.quotaTypePlaceholder')"
                clearable
              >
                <ElOption
                  v-for="option in quotaTypeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="8">
            <ElFormItem :label="$t('quotaPackage.search.status')">
              <ElSelect
                v-model="formFilters.isActive"
                :placeholder="$t('quotaPackage.search.statusPlaceholder')"
                clearable
              >
                <ElOption :label="$t('quotaPackage.status.active')" :value="true" />
                <ElOption :label="$t('quotaPackage.status.inactive')" :value="false" />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="8" class="text-right">
            <ElButton @click="handleReset">{{ $t('table.searchBar.reset') }}</ElButton>
            <ElButton type="primary" @click="handleSearch" v-ripple>
              {{ $t('table.searchBar.search') }}
            </ElButton>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElCard>

    <!-- 2. 表格区 -->
    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columns"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElButton type="primary" @click="handleCreate">
            <ArtSvgIcon icon="ri:add-line" class="mr-1" />
            {{ $t('quotaPackage.action.create') }}
          </ElButton>
        </template>
      </ArtTableHeader>

      <ArtTable
        :data="data"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @pagination:current-change="handleCurrentChange"
        @pagination:size-change="handleSizeChange"
      >
        <template #quotaType="{ row }">
          <ElTag>{{ getQuotaTypeText(row.quotaType) }}</ElTag>
        </template>
        <template #quotaValue="{ row }">
          {{ formatQuotaValue(row.quotaType, row.quotaValue) }}
        </template>
        <template #price="{ row }">
          <span class="text-primary font-medium">￥{{ row.price }}</span>
        </template>
        <template #isActive="{ row }">
          <ElSwitch
            :model-value="row.isActive"
            @change="(val) => handleStatusChange(row, val as boolean)"
          />
        </template>
        <template #action="{ row }">
          <div class="action-wrap">
            <button class="art-action-btn primary" @click="handleEdit(row)">
              <ArtSvgIcon icon="ri:edit-line" class="art-action-icon" />
              <span>{{ $t('common.edit') }}</span>
            </button>
            <button class="art-action-btn danger" @click="handleDelete(row)">
              <ArtSvgIcon icon="ri:delete-bin-line" class="art-action-icon" />
              <span>{{ $t('common.delete') }}</span>
            </button>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 3. 弹窗 -->
    <QuotaPackageFormDialog ref="formDialogRef" @success="refreshData" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import ArtTableHeader from '@/components/core/tables/art-table-header/index.vue'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import QuotaPackageFormDialog from './QuotaPackageFormDialog.vue'
  import { useTable } from '@/hooks/core/useTable'
  import {
    fetchQuotaPackageList,
    fetchDeleteQuotaPackage,
    fetchUpdateQuotaPackageStatus
  } from '@/api/quotaPackage'
  import type { ColumnOption } from '@/types/component'
  import {
    ElButton,
    ElCard,
    ElCol,
    ElForm,
    ElFormItem,
    ElOption,
    ElRow,
    ElSelect,
    ElSwitch,
    ElTag
  } from 'element-plus'

  defineOptions({ name: 'QuotaPackageListPanel' })

  const { t } = useI18n()

  // 1. 响应式变量
  const showSearchBar = ref(true)
  const formDialogRef = ref<InstanceType<typeof QuotaPackageFormDialog>>()

  const formFilters = ref({
    quotaType: undefined as number | undefined,
    isActive: undefined as boolean | undefined
  })

  // 2. 配额类型选项
  const quotaTypeOptions = [
    { value: 0, label: t('quotaPackage.quotaType.storeCount') },
    { value: 1, label: t('quotaPackage.quotaType.accountCount') },
    { value: 2, label: t('quotaPackage.quotaType.storage') },
    { value: 3, label: t('quotaPackage.quotaType.smsCredits') },
    { value: 4, label: t('quotaPackage.quotaType.deliveryOrders') },
    { value: 5, label: t('quotaPackage.quotaType.promotionSlots') }
  ]

  // 3. 表格配置
  const {
    data,
    loading,
    pagination,
    columns,
    searchParams,
    refreshData,
    getData: getDataByPage,
    handleCurrentChange,
    handleSizeChange
  } = useTable<typeof fetchQuotaPackageList, Api.QuotaPackage.QuotaPackageListDto>({
    core: {
      apiFn: fetchQuotaPackageList,
      apiParams: {},
      paginationKey: {
        current: 'page',
        size: 'pageSize'
      },
      columnsFactory: (): ColumnOption<Api.QuotaPackage.QuotaPackageListDto>[] => [
        { type: 'globalIndex', label: t('quotaPackage.table.index'), width: 60, fixed: 'left' },
        {
          prop: 'name',
          label: t('quotaPackage.table.name'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        { prop: 'quotaType', label: t('quotaPackage.table.quotaType'), width: 140, useSlot: true },
        {
          prop: 'quotaValue',
          label: t('quotaPackage.table.quotaValue'),
          width: 140,
          useSlot: true
        },
        { prop: 'price', label: t('quotaPackage.table.price'), width: 120, useSlot: true },
        { prop: 'isActive', label: t('quotaPackage.table.status'), width: 100, useSlot: true },
        { prop: 'sortOrder', label: t('quotaPackage.table.sortOrder'), width: 100 },
        {
          prop: 'action',
          label: t('quotaPackage.table.action'),
          width: 200,
          fixed: 'right',
          useSlot: true
        }
      ]
    }
  })

  // 4. 配额类型文本
  const getQuotaTypeText = (quotaType: number) => {
    const option = quotaTypeOptions.find((o) => o.value === quotaType)
    return option?.label || '-'
  }

  // 5. 格式化配额值
  const formatQuotaValue = (quotaType: number, value: number) => {
    switch (quotaType) {
      case 2: // Storage
        return `${value} GB`
      case 3: // SmsCredits
        return `${value} ${t('quotaPackage.unit.sms')}`
      case 4: // DeliveryOrders
        return `${value} ${t('quotaPackage.unit.orders')}`
      default:
        return value.toString()
    }
  }

  // 6. 搜索与重置
  const handleSearch = () => {
    searchParams.quotaType = formFilters.value.quotaType
    searchParams.isActive = formFilters.value.isActive
    void getDataByPage()
  }

  const handleReset = () => {
    formFilters.value.quotaType = undefined
    formFilters.value.isActive = undefined
    handleSearch()
  }

  // 7. 操作处理
  const handleCreate = () => {
    formDialogRef.value?.open()
  }

  const handleEdit = (row: Api.QuotaPackage.QuotaPackageListDto) => {
    formDialogRef.value?.open(row)
  }

  const handleDelete = async (row: Api.QuotaPackage.QuotaPackageListDto) => {
    try {
      await ElMessageBox.confirm(t('quotaPackage.message.deleteConfirm'), t('common.warning'), {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
      await fetchDeleteQuotaPackage(row.id)
      ElMessage.success(t('quotaPackage.message.deleteSuccess'))
      void refreshData()
    } catch {
      // 取消操作
    }
  }

  const handleStatusChange = async (
    row: Api.QuotaPackage.QuotaPackageListDto,
    isActive: boolean
  ) => {
    try {
      await fetchUpdateQuotaPackageStatus(row.id, isActive)
      ElMessage.success(t('quotaPackage.message.statusUpdateSuccess'))
      void refreshData()
    } catch {
      // 错误处理
    }
  }

  // 8. 生命周期
  onMounted(() => {
    // 初始化加载
  })
</script>

<style scoped>
  .art-search-card {
    margin-bottom: 16px;
  }

  .art-action-btn {
    display: inline-flex;
    gap: 6px;
    align-items: center;
    min-width: 64px;
    padding: 6px 12px;
    font-size: 13px;
    line-height: 1;
    color: var(--el-text-color-primary);
    cursor: pointer;
    background: var(--el-fill-color-light);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 10px;
  }

  .art-action-btn .art-action-icon {
    display: flex;
    font-size: 16px;
  }

  .art-action-btn.primary {
    color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-8);
  }

  .art-action-btn.danger {
    color: var(--el-color-danger);
    background: var(--el-color-danger-light-9);
    border-color: var(--el-color-danger-light-8);
  }

  .art-action-btn:hover {
    filter: brightness(0.97);
    transition: all 0.15s ease;
  }

  .action-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }
</style>
