<template>
  <div class="art-page-view">
    <TenantReviewSearch v-model="formFilters" @search="handleSearch" @reset="handleReset" />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columns"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      />

      <ArtTable
        :data="data"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @pagination:current-change="handleCurrentChange"
        @pagination:size-change="handleSizeChange"
      >
        <template #status="{ row }">
          <ElTag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</ElTag>
        </template>
        <template #verificationStatus="{ row }">
          <ElTag :type="getVerificationStatusType(row.verificationStatus)">
            {{ getVerificationStatusText(row.verificationStatus) }}
          </ElTag>
        </template>
        <template #action="{ row }">
          <div class="flex-start gap-2">
            <button class="art-action-btn primary" @click="handleReview(row)">
              <ArtSvgIcon icon="ri:check-double-line" class="art-action-icon" />
              <span>{{ t('tenant.review.action') }}</span>
            </button>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <ReviewDialog ref="reviewDialogRef" @success="refreshData" />
  </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 ReviewDialog from './components/ReviewDialog.vue'
  import TenantReviewSearch from './modules/tenant-review-search.vue'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import { useTable } from '@/hooks/core/useTable'
  import { fetchGetTenantList } from '@/api/tenant'
  import { TenantStatus } from '@/enums/TenantStatus'
  import { TenantVerificationStatus } from '@/enums/TenantVerificationStatus'
  import type { TenantReviewSearchForm } from './types'
  import type { ColumnOption } from '@/types/component'
  import { ElTag, ElCard } from 'element-plus'

  defineOptions({ name: 'TenantReview' })

  const { t } = useI18n()

  const showSearchBar = ref(true)
  const reviewDialogRef = ref<InstanceType<typeof ReviewDialog>>()
  const formFilters = ref<TenantReviewSearchForm>({
    tenantName: '',
    contactName: '',
    contactPhone: '',
    status: TenantStatus.PendingReview,
    verificationStatus: TenantVerificationStatus.Pending
  })

  const {
    data,
    loading,
    pagination,
    columns,
    searchParams,
    refreshData,
    getData: getDataByPage,
    handleCurrentChange,
    handleSizeChange
  } = useTable<typeof fetchGetTenantList, Api.Tenant.TenantDto>({
    core: {
      apiFn: fetchGetTenantList,
      apiParams: {
        Status: TenantStatus.PendingReview,
        VerificationStatus: TenantVerificationStatus.Pending
      },
      paginationKey: {
        current: 'Page',
        size: 'PageSize'
      },
      columnsFactory: (): ColumnOption<Api.Tenant.TenantDto>[] => [
        { type: 'globalIndex', label: t('tenant.table.index'), width: 60, fixed: 'left' },
        {
          prop: 'name',
          label: t('tenant.table.name'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        { prop: 'code', label: t('tenant.table.code'), minWidth: 240, showOverflowTooltip: true },
        { prop: 'contactName', label: t('tenant.table.contactName'), width: 150 },
        { prop: 'contactPhone', label: t('tenant.table.contactPhone'), width: 150 },
        { prop: 'status', label: t('tenant.table.status'), width: 120, useSlot: true },
        {
          prop: 'verificationStatus',
          label: t('tenant.table.verificationStatus'),
          width: 150,
          useSlot: true
        },
        {
          prop: 'effectiveFrom',
          label: t('tenant.table.effectiveFrom'),
          width: 180,
          formatter: (row: Api.Tenant.TenantDto) =>
            row.effectiveFrom ? new Date(row.effectiveFrom).toLocaleDateString() : '-'
        },
        {
          prop: 'action',
          label: t('tenant.table.action'),
          width: 110,
          fixed: 'right',
          useSlot: true
        }
      ]
    }
  })

  // 1. 初始化时设置默认筛选参数
  onMounted(() => {
    searchParams.Status = formFilters.value.status
    searchParams.VerificationStatus = formFilters.value.verificationStatus
    searchParams.Name = undefined
    searchParams.ContactName = undefined
    searchParams.ContactPhone = undefined
    searchParams.Keyword = undefined
  })

  // 2. 按后端 TenantStatus 枚举值渲染租户服务状态
  const getStatusType = (status: number) => {
    switch (status) {
      case TenantStatus.PendingReview:
        return 'warning'
      case TenantStatus.Active:
        return 'success'
      case TenantStatus.Suspended:
        return 'danger'
      case TenantStatus.Expired:
        return 'warning'
      case TenantStatus.Closed:
        return 'info'
      default:
        return 'info'
    }
  }

  const getStatusText = (status: number) => {
    switch (status) {
      case TenantStatus.PendingReview:
        return t('tenant.status.pendingReview')
      case TenantStatus.Active:
        return t('tenant.status.active')
      case TenantStatus.Suspended:
        return t('tenant.status.suspended')
      case TenantStatus.Expired:
        return t('tenant.status.expired')
      case TenantStatus.Closed:
        return t('tenant.status.closed')
      default:
        return t('tenant.status.unknown')
    }
  }

  const getVerificationStatusType = (status: number) => {
    switch (status) {
      case TenantVerificationStatus.Draft:
        return 'info'
      case TenantVerificationStatus.Pending:
        return 'warning'
      case TenantVerificationStatus.Approved:
        return 'success'
      case TenantVerificationStatus.Rejected:
        return 'danger'
      default:
        return 'info'
    }
  }

  const getVerificationStatusText = (status: number) => {
    switch (status) {
      case TenantVerificationStatus.Draft:
        return t('tenant.verificationStatus.draft')
      case TenantVerificationStatus.Pending:
        return t('tenant.verificationStatus.pending')
      case TenantVerificationStatus.Approved:
        return t('tenant.verificationStatus.approved')
      case TenantVerificationStatus.Rejected:
        return t('tenant.verificationStatus.rejected')
      default:
        return t('tenant.verificationStatus.unknown')
    }
  }

  const handleSearch = () => {
    // 1. 同步服务端查询参数（按 Swagger 字段直传）
    searchParams.Name = formFilters.value.tenantName.trim() || undefined
    searchParams.ContactName = formFilters.value.contactName.trim() || undefined
    searchParams.ContactPhone = formFilters.value.contactPhone.trim() || undefined
    searchParams.Status = formFilters.value.status
    searchParams.VerificationStatus = formFilters.value.verificationStatus
    searchParams.Keyword = undefined

    // 2. 回到第一页并触发请求（避免当前已在第一页时不刷新）
    void getDataByPage()
  }

  const handleReset = () => {
    // 1. 恢复默认筛选
    formFilters.value.tenantName = ''
    formFilters.value.contactName = ''
    formFilters.value.contactPhone = ''
    formFilters.value.status = TenantStatus.PendingReview
    formFilters.value.verificationStatus = TenantVerificationStatus.Pending

    // 2. 触发查询
    handleSearch()
  }

  const handleReview = (row: Api.Tenant.TenantDto) => {
    reviewDialogRef.value?.open(row)
  }
</script>

<style scoped>
  .flex-start {
    display: flex;
    align-items: center;
  }

  .gap-2 {
    gap: 8px;
  }
</style>
