<template>
  <div class="art-page-view">
    <TenantSearch 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"
      >
        <template #left>
          <ElButton type="primary" @click="handleAdd" v-ripple>
            <template #icon><ArtSvgIcon icon="ri:add-line" /></template>
            {{ t('tenant.action.addTenant') }}
          </ElButton>
        </template>
      </ArtTableHeader>

      <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="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>
            <button class="art-action-btn primary" @click="handleEdit(row)">
              <ArtSvgIcon icon="ri:edit-2-line" class="art-action-icon" />
              <span>{{ t('tenant.action.edit') }}</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('tenant.action.more') }}</span>
              </button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem command="impersonate">
                    <span class="dropdown-item">
                      <ArtSvgIcon icon="ri:user-shared-line" class="dropdown-icon" />
                      <span>{{ t('tenant.action.impersonateLogin') }}</span>
                    </span>
                  </ElDropdownItem>
                  <ElDropdownItem command="quota">
                    <span class="dropdown-item">
                      <ArtSvgIcon icon="ri:stack-line" class="dropdown-icon" />
                      <span>{{ t('tenant.action.quotaOverview') }}</span>
                    </span>
                  </ElDropdownItem>
                  <ElDropdownItem command="freeze">
                    <span class="dropdown-item">
                      <ArtSvgIcon icon="ri:snowflake-line" class="dropdown-icon" />
                      <span>{{ getFreezeActionText(row.status) }}</span>
                    </span>
                  </ElDropdownItem>
                  <ElDropdownItem command="extend">
                    <span class="dropdown-item">
                      <ArtSvgIcon icon="ri:time-line" class="dropdown-icon" />
                      <span>{{ t('tenant.action.extendOrGift') }}</span>
                    </span>
                  </ElDropdownItem>
                  <ElDropdownItem divided command="resetAdmin">
                    <span class="dropdown-item danger">
                      <ArtSvgIcon icon="ri:refresh-line" class="dropdown-icon" />
                      <span>{{ t('tenant.action.resetAdmin') }}</span>
                    </span>
                  </ElDropdownItem>
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <TenantManualCreateDialog ref="tenantManualCreateRef" @success="refreshData" />
    <TenantEdit ref="tenantEditRef" @success="refreshData" />
    <TenantImpersonateDialog ref="tenantImpersonateRef" @success="refreshData" />
    <TenantFreezeDialog ref="tenantFreezeRef" @success="refreshData" />
    <TenantExtendSubscriptionDialog ref="tenantExtendSubscriptionRef" @success="refreshData" />
    <TenantResetAdminDialog ref="tenantResetAdminRef" @success="refreshData" />
    <TenantDetailDrawer ref="tenantDetailDrawerRef" />
    <TenantQuotaDrawer ref="tenantQuotaDrawerRef" />
  </div>
</template>

<script setup lang="ts">
  import { ref } 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 TenantEdit from './components/TenantEdit.vue'
  import TenantImpersonateDialog from './components/TenantImpersonateDialog.vue'
  import TenantFreezeDialog from './components/TenantFreezeDialog.vue'
  import TenantExtendSubscriptionDialog from './components/TenantExtendSubscriptionDialog.vue'
  import TenantManualCreateDialog from './components/TenantManualCreateDialog.vue'
  import TenantResetAdminDialog from './components/TenantResetAdminDialog.vue'
  import TenantQuotaDrawer from './components/TenantQuotaDrawer.vue'
  import TenantDetailDrawer from './components/TenantDetailDrawer.vue'
  import TenantSearch from './modules/tenant-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 { ColumnOption } from '@/types/component'
  import { ElButton, ElDropdown, ElDropdownItem, ElDropdownMenu, ElTag } from 'element-plus'

  defineOptions({ name: 'TenantList' })

  const { t } = useI18n()

  const showSearchBar = ref(true)
  const tenantManualCreateRef = ref<InstanceType<typeof TenantManualCreateDialog>>()
  const tenantEditRef = ref<InstanceType<typeof TenantEdit>>()
  const tenantImpersonateRef = ref<InstanceType<typeof TenantImpersonateDialog>>()
  const tenantFreezeRef = ref<InstanceType<typeof TenantFreezeDialog>>()
  const tenantExtendSubscriptionRef = ref<InstanceType<typeof TenantExtendSubscriptionDialog>>()
  const tenantResetAdminRef = ref<InstanceType<typeof TenantResetAdminDialog>>()
  const tenantQuotaDrawerRef = ref<InstanceType<typeof TenantQuotaDrawer>>()
  const tenantDetailDrawerRef = ref<InstanceType<typeof TenantDetailDrawer>>()
  const formFilters = ref({
    tenantName: '',
    contactName: '',
    contactPhone: '',
    status: TenantStatus.Active as TenantStatus | undefined,
    verificationStatus: undefined as TenantVerificationStatus | undefined
  })

  const {
    data,
    loading,
    pagination,
    columns,
    searchParams,
    refreshData,
    getData: getDataByPage,
    handleCurrentChange,
    handleSizeChange
  } = useTable<typeof fetchGetTenantList, Api.Tenant.TenantDto>({
    core: {
      apiFn: fetchGetTenantList,
      apiParams: {
        Status: TenantStatus.Active
      },
      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: 200 },
        { prop: 'contactPhone', label: t('tenant.table.contactPhone'), width: 200 },
        { prop: 'status', label: t('tenant.table.status'), width: 150, useSlot: true },
        {
          prop: 'verificationStatus',
          label: t('tenant.table.verificationStatus'),
          width: 200,
          useSlot: true
        },
        {
          prop: 'effectiveTo',
          label: t('tenant.table.effectiveTo'),
          width: 160,
          formatter: (row) =>
            row.effectiveTo ? new Date(row.effectiveTo).toLocaleDateString() : '-'
        },
        {
          prop: 'action',
          label: t('tenant.table.action'),
          width: 260,
          fixed: 'right',
          useSlot: true
        }
      ]
    }
  })

  // 1. 按后端 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'
    }
  }

  // 2. 按后端 TenantVerificationStatus 枚举值渲染租户实名认证状态
  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 handleAdd = () => {
    tenantManualCreateRef.value?.open()
  }

  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.Active
    formFilters.value.verificationStatus = undefined

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

  const handleEdit = (row: Api.Tenant.TenantDto) => {
    tenantEditRef.value?.open(row)
  }

  const handleDetail = (row: Api.Tenant.TenantDto) => {
    tenantDetailDrawerRef.value?.open(row.id)
  }

  // 3. “更多”菜单文案
  const getFreezeActionText = (status: number) => {
    return status === TenantStatus.Suspended
      ? t('tenant.action.unfreeze')
      : t('tenant.action.freeze')
  }

  const handleMoreCommand = (command: string, row: Api.Tenant.TenantDto) => {
    // 1. 根据指令分发
    switch (command) {
      case 'impersonate':
        tenantImpersonateRef.value?.open(row)
        break
      case 'quota':
        tenantQuotaDrawerRef.value?.open(row.id)
        break
      case 'freeze':
        tenantFreezeRef.value?.open(row)
        break
      case 'extend':
        tenantExtendSubscriptionRef.value?.open(row)
        break
      case 'resetAdmin':
        tenantResetAdminRef.value?.open(row)
        break
      default:
        break
    }
  }
</script>

<style scoped>
  .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>
