<template>
  <div class="art-page-view">
    <!-- 1. 筛选区 -->
    <ElCard class="art-search-card" shadow="never">
      <ElForm :model="formFilters" label-width="80px">
        <ElRow :gutter="16">
          <ElCol :span="6">
            <ElFormItem :label="$t('subscription.search.status')">
              <ElSelect
                v-model="formFilters.status"
                :placeholder="$t('subscription.search.statusPlaceholder')"
                clearable
              >
                <ElOption
                  v-for="status in statusOptions"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="6">
            <ElFormItem :label="$t('subscription.search.package')">
              <ElSelect
                v-model="formFilters.packageId"
                :placeholder="$t('subscription.search.packagePlaceholder')"
                clearable
              >
                <ElOption
                  v-for="pkg in packageOptions"
                  :key="pkg.id"
                  :label="pkg.name"
                  :value="pkg.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="6">
            <ElFormItem :label="$t('subscription.search.expireDateRange')">
              <ElDatePicker
                v-model="formFilters.expireDateRange"
                type="daterange"
                :placeholder="$t('subscription.search.expireDateRangePlaceholder')"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="6">
            <ElFormItem :label="$t('subscription.search.tenantKeyword')">
              <ElInput
                v-model="formFilters.tenantKeyword"
                :placeholder="$t('subscription.search.tenantKeywordPlaceholder')"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow>
          <ElCol :span="24" 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 #extra>
          <div class="batch-actions">
            <ElButton
              type="primary"
              :disabled="selectedRows.length === 0"
              @click="handleBatchExtend"
            >
              <ArtSvgIcon icon="ri:time-line" class="mr-1" />
              {{ $t('batch.extend.title') }}
            </ElButton>
            <ElButton
              type="warning"
              :disabled="selectedRows.length === 0"
              @click="handleBatchRemind"
            >
              <ArtSvgIcon icon="ri:notification-line" class="mr-1" />
              {{ $t('batch.remind.title') }}
            </ElButton>
            <span v-if="selectedRows.length > 0" class="selected-count">
              {{ $t('batch.selectedCount', { count: selectedRows.length }) }}
            </span>
          </div>
        </template>
      </ArtTableHeader>

      <ArtTable
        :data="data"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @pagination:current-change="handleCurrentChange"
        @pagination:size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <template #currentPackage="{ row }">
          {{ row.packageName || row.tenantPackageName || '-' }}
        </template>
        <template #status="{ row }">
          <ElTag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</ElTag>
        </template>
        <template #effectiveDate="{ row }">
          {{ formatDate(row.effectiveFrom) }} - {{ formatDate(row.effectiveTo) }}
        </template>
        <template #expireDate="{ row }">
          {{ formatDate(row.effectiveTo) }}
        </template>
        <template #createdAt="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
        <template #autoRenew="{ row }">
          <ElTag :type="row.autoRenew ? 'success' : 'info'">
            {{ row.autoRenew ? $t('common.yes') : $t('common.no') }}
          </ElTag>
        </template>
        <template #action="{ row }">
          <div class="action-wrap">
            <button class="art-action-btn" @click="handleDetail(row)">
              <ArtSvgIcon icon="ri:information-line" class="art-action-icon" />
              <span>{{ t('dictionary.common.detail') }}</span>
            </button>
            <ElDropdown @command="(cmd) => handleMoreCommand(cmd, row)">
              <button class="art-action-btn info">
                <ArtSvgIcon icon="ri:more-2-line" class="art-action-icon" />
                <span>{{ $t('subscription.action.more') }}</span>
              </button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem command="extend">
                    <span class="dropdown-item">
                      <ArtSvgIcon icon="ri:time-line" class="dropdown-icon" />
                      <span>{{ $t('subscription.action.extend') }}</span>
                    </span>
                  </ElDropdownItem>
                  <ElDropdownItem command="changePlan">
                    <span class="dropdown-item">
                      <ArtSvgIcon icon="ri:refresh-line" class="dropdown-icon" />
                      <span>{{ $t('subscription.action.changePlan') }}</span>
                    </span>
                  </ElDropdownItem>
                  <ElDropdownItem divided command="changeStatus">
                    <span class="dropdown-item danger">
                      <ArtSvgIcon icon="ri:exchange-line" class="dropdown-icon" />
                      <span>{{ $t('subscription.action.changeStatus') }}</span>
                    </span>
                  </ElDropdownItem>
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 3. 弹窗/抽屉 -->
    <SubscriptionDetailDrawer ref="detailDrawerRef" />
    <ExtendSubscriptionDialog ref="extendDialogRef" @success="refreshData" />
    <ChangePlanDialog ref="changePlanDialogRef" @success="refreshData" />
    <StatusChangeDialog ref="statusChangeDialogRef" @success="refreshData" />
    <BatchExtendDialog ref="batchExtendDialogRef" @success="handleBatchSuccess" />
    <BatchRemindDialog ref="batchRemindDialogRef" @success="handleBatchSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  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 SubscriptionDetailDrawer from './components/SubscriptionDetailDrawer.vue'
  import ExtendSubscriptionDialog from './components/ExtendSubscriptionDialog.vue'
  import ChangePlanDialog from './components/ChangePlanDialog.vue'
  import StatusChangeDialog from './components/StatusChangeDialog.vue'
  import BatchExtendDialog from './components/BatchExtendDialog.vue'
  import BatchRemindDialog from './components/BatchRemindDialog.vue'
  import { useTable } from '@/hooks/core/useTable'
  import { getSubscriptionList } from '@/api/subscription'
  import { fetchTenantPackageList } from '@/api/tenant-package'
  import { SubscriptionStatus } from '@/enums/SubscriptionStatus'
  import type { ColumnOption } from '@/types/component'
  import {
    ElButton,
    ElCard,
    ElCol,
    ElDatePicker,
    ElDropdown,
    ElDropdownItem,
    ElDropdownMenu,
    ElForm,
    ElFormItem,
    ElInput,
    ElOption,
    ElRow,
    ElSelect,
    ElTag
  } from 'element-plus'

  defineOptions({ name: 'SubscriptionList' })

  const { t } = useI18n()

  // 1. 响应式变量
  const showSearchBar = ref(true)
  const detailDrawerRef = ref<InstanceType<typeof SubscriptionDetailDrawer>>()
  const extendDialogRef = ref<InstanceType<typeof ExtendSubscriptionDialog>>()
  const changePlanDialogRef = ref<InstanceType<typeof ChangePlanDialog>>()
  const statusChangeDialogRef = ref<InstanceType<typeof StatusChangeDialog>>()
  const batchExtendDialogRef = ref<InstanceType<typeof BatchExtendDialog>>()
  const batchRemindDialogRef = ref<InstanceType<typeof BatchRemindDialog>>()

  const selectedRows = ref<Api.Subscription.SubscriptionDto[]>([])

  const formFilters = ref({
    status: undefined as SubscriptionStatus | undefined,
    packageId: '',
    expireDateRange: [] as string[],
    tenantKeyword: ''
  })

  const packageOptions = ref<Array<{ id: string; name: string }>>([])

  // 2. 状态选项
  const statusOptions = [
    { value: SubscriptionStatus.Pending, label: t('subscription.status.pending') },
    { value: SubscriptionStatus.Active, label: t('subscription.status.active') },
    { value: SubscriptionStatus.GracePeriod, label: t('subscription.status.gracePeriod') },
    { value: SubscriptionStatus.Cancelled, label: t('subscription.status.cancelled') },
    { value: SubscriptionStatus.Suspended, label: t('subscription.status.suspended') }
  ]

  // 3. 表格配置
  const {
    data,
    loading,
    pagination,
    columns,
    searchParams,
    refreshData,
    getData: getDataByPage,
    handleCurrentChange,
    handleSizeChange
  } = useTable<typeof getSubscriptionList, Api.Subscription.SubscriptionDto>({
    core: {
      apiFn: getSubscriptionList,
      apiParams: {},
      paginationKey: {
        current: 'Page',
        size: 'PageSize'
      },
      columnsFactory: (): ColumnOption<Api.Subscription.SubscriptionDto>[] => [
        { type: 'selection', width: 55, fixed: 'left' },
        { type: 'globalIndex', label: t('subscription.table.index'), width: 60, fixed: 'left' },
        {
          prop: 'tenantName',
          label: t('subscription.table.tenantName'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'currentPackage',
          label: t('subscription.table.currentPackage'),
          minWidth: 150,
          useSlot: true
        },
        { prop: 'status', label: t('subscription.table.status'), width: 120, useSlot: true },
        {
          prop: 'effectiveDate',
          label: t('subscription.table.effectiveDate'),
          width: 240,
          useSlot: true
        },
        {
          prop: 'effectiveTo',
          label: t('subscription.table.expireDate'),
          width: 160,
          useSlot: true,
          slotName: 'expireDate',
          sortable: true
        },
        {
          prop: 'createdAt',
          label: t('subscription.table.createdAt'),
          width: 180,
          useSlot: true,
          sortable: true
        },
        { prop: 'autoRenew', label: t('subscription.table.autoRenew'), width: 120, useSlot: true },
        {
          prop: 'action',
          label: t('subscription.table.action'),
          width: 400,
          fixed: 'right',
          useSlot: true
        }
      ]
    }
  })

  // 4. 获取套餐列表
  const loadPackageOptions = async () => {
    try {
      const response = await fetchTenantPackageList({ PageSize: 100 })
      packageOptions.value = response.items.map((item) => ({
        id: item.id,
        name: item.name
      }))
    } catch (error) {
      console.error('Failed to load package options:', error)
    }
  }

  // 5. 状态处理函数
  const getStatusType = (status: number) => {
    switch (status) {
      case SubscriptionStatus.Pending:
        return 'warning'
      case SubscriptionStatus.Active:
        return 'success'
      case SubscriptionStatus.GracePeriod:
        return 'warning'
      case SubscriptionStatus.Cancelled:
        return 'info'
      case SubscriptionStatus.Suspended:
        return 'danger'
      default:
        return 'info'
    }
  }

  const getStatusText = (status: number) => {
    switch (status) {
      case SubscriptionStatus.Pending:
        return t('subscription.status.pending')
      case SubscriptionStatus.Active:
        return t('subscription.status.active')
      case SubscriptionStatus.GracePeriod:
        return t('subscription.status.gracePeriod')
      case SubscriptionStatus.Cancelled:
        return t('subscription.status.cancelled')
      case SubscriptionStatus.Suspended:
        return t('subscription.status.suspended')
      default:
        return '-'
    }
  }

  // 6. 日期格式化
  const formatDate = (date: string | undefined) => {
    if (!date) return '-'
    return new Date(date).toLocaleDateString()
  }

  const formatDateTime = (date: string | undefined) => {
    if (!date) return '-'
    return new Date(date).toLocaleString()
  }

  // 7. 搜索与重置
  const handleSearch = () => {
    searchParams.Status = formFilters.value.status
    searchParams.TenantPackageId = formFilters.value.packageId || undefined
    searchParams.TenantKeyword = formFilters.value.tenantKeyword.trim() || undefined
    searchParams.ExpireFrom =
      formFilters.value.expireDateRange.length > 0
        ? formFilters.value.expireDateRange[0]
        : undefined
    searchParams.ExpireTo =
      formFilters.value.expireDateRange.length > 1
        ? formFilters.value.expireDateRange[1]
        : undefined

    void getDataByPage()
  }

  const handleReset = () => {
    formFilters.value.status = undefined
    formFilters.value.packageId = ''
    formFilters.value.expireDateRange = []
    formFilters.value.tenantKeyword = ''
    handleSearch()
  }

  // 8. 操作处理
  const handleDetail = (row: Api.Subscription.SubscriptionDto) => {
    detailDrawerRef.value?.open(row)
  }

  const handleExtend = (row: Api.Subscription.SubscriptionDto) => {
    extendDialogRef.value?.open(row)
  }

  const handleChangePlan = (row: Api.Subscription.SubscriptionDto) => {
    changePlanDialogRef.value?.open(row)
  }

  const handleChangeStatus = (row: Api.Subscription.SubscriptionDto) => {
    statusChangeDialogRef.value?.open(row)
  }

  const handleMoreCommand = (command: string, row: Api.Subscription.SubscriptionDto) => {
    // 1. 根据指令分发
    switch (command) {
      case 'extend':
        handleExtend(row)
        break
      case 'changePlan':
        handleChangePlan(row)
        break
      case 'changeStatus':
        handleChangeStatus(row)
        break
      default:
        break
    }
  }

  // 9. 多选处理
  const handleSelectionChange = (selection: Api.Subscription.SubscriptionDto[]) => {
    selectedRows.value = selection
  }

  // 10. 批量操作
  const handleBatchExtend = () => {
    batchExtendDialogRef.value?.open(selectedRows.value)
  }

  const handleBatchRemind = () => {
    batchRemindDialogRef.value?.open(selectedRows.value)
  }

  const handleBatchSuccess = () => {
    selectedRows.value = []
    void refreshData()
  }

  // 11. 生命周期
  onMounted(() => {
    void loadPackageOptions()
  })
</script>

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

  .batch-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .batch-actions .selected-count {
    margin-left: 8px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  .mr-1 {
    margin-right: 4px;
  }

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

  .dropdown-item {
    display: inline-flex;
    gap: 8px;
    align-items: center;
  }

  .dropdown-item.danger {
    color: var(--el-color-danger);
  }

  .dropdown-icon {
    font-size: 16px;
  }
</style>
