<template>
  <ElDialog
    v-model="visible"
    :title="$t('tenant.review.dialogTitle')"
    width="1200px"
    top="4vh"
    class="tenant-review-dialog"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElSkeleton :loading="detailLoading" animated>
      <template #template>
        <div class="space-y-3">
          <div class="h-6 w-2/5 rounded bg-[var(--el-fill-color-light)]"></div>
          <div class="h-24 w-full rounded bg-[var(--el-fill-color-light)]"></div>
          <div class="h-24 w-full rounded bg-[var(--el-fill-color-light)]"></div>
        </div>
      </template>
      <template #default>
        <div class="grid grid-cols-12 gap-4">
          <div class="col-span-8">
            <ElDivider content-position="left" class="my-2">{{
              $t('tenant.review.section.basic')
            }}</ElDivider>
            <ElDescriptions :column="3" border>
              <ElDescriptionsItem :label="$t('tenant.review.field.name')">
                {{ tenantDetail?.tenant.name || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.code')">
                {{ tenantDetail?.tenant.code || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.effectiveFrom')">
                {{ formatDateTime(tenantDetail?.tenant.effectiveFrom) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.packageName')">
                {{ tenantDetail?.package?.name || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.packageType')">
                {{ getPackageTypeText(tenantDetail?.package?.packageType) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.contactName')">
                {{ tenantDetail?.tenant.contactName || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.contactPhone')">
                {{ tenantDetail?.tenant.contactPhone || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.contactEmail')" :span="2">
                {{ tenantDetail?.tenant.contactEmail || '-' }}
              </ElDescriptionsItem>
            </ElDescriptions>

            <ElDivider content-position="left" class="my-2">{{
              $t('tenant.review.section.package')
            }}</ElDivider>
            <ElDescriptions :column="3" border>
              <ElDescriptionsItem :label="$t('tenant.review.field.packageId')">
                {{ tenantDetail?.package?.id || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.packageName')">
                {{ tenantDetail?.package?.name || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.packageType')">
                {{ getPackageTypeText(tenantDetail?.package?.packageType) }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.packageDescription')" :span="3">
                {{ tenantDetail?.package?.description || '-' }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.monthlyPrice')">
                {{ renderPrice(tenantDetail?.package?.monthlyPrice) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.yearlyPrice')">
                {{ renderPrice(tenantDetail?.package?.yearlyPrice) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.packageActive')">
                {{ tenantDetail?.package ? renderBool(tenantDetail.package.isActive) : '-' }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.packageQuota')" :span="3">
                {{ renderPackageQuota(tenantDetail?.package) }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.featurePoliciesJson')" :span="3">
                <ElInput
                  v-if="tenantDetail?.package?.featurePoliciesJson"
                  :model-value="tenantDetail.package.featurePoliciesJson"
                  type="textarea"
                  :rows="2"
                  readonly
                />
                <span v-else>-</span>
              </ElDescriptionsItem>
            </ElDescriptions>

            <ElDivider content-position="left" class="my-2">{{
              $t('tenant.review.section.subscription')
            }}</ElDivider>
            <ElDescriptions :column="3" border>
              <ElDescriptionsItem :label="$t('tenant.review.field.subscriptionId')">
                {{ tenantDetail?.subscription?.id || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.subscriptionStatus')">
                {{ getSubscriptionStatusText(tenantDetail?.subscription?.status) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.autoRenew')">
                {{
                  tenantDetail?.subscription ? renderBool(tenantDetail.subscription.autoRenew) : '-'
                }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.subscriptionPackageId')">
                {{ tenantDetail?.subscription?.tenantPackageId || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.subscriptionEffectiveFrom')">
                {{ formatDateTime(tenantDetail?.subscription?.effectiveFrom) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.subscriptionEffectiveTo')">
                {{ formatDateTime(tenantDetail?.subscription?.effectiveTo) }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.nextBillingDate')" :span="3">
                {{ formatDateTime(tenantDetail?.subscription?.nextBillingDate) }}
              </ElDescriptionsItem>
            </ElDescriptions>

            <ElDivider content-position="left" class="my-2">{{
              $t('tenant.review.section.verification')
            }}</ElDivider>
            <ElDescriptions :column="3" border>
              <ElDescriptionsItem :label="$t('tenant.review.field.verificationStatus')">
                {{ getVerificationStatusText(tenantDetail?.verification.status) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.verificationSubmittedAt')">
                {{ formatDateTime(tenantDetail?.verification.submittedAt) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.businessLicenseNumber')">
                {{ tenantDetail?.verification.businessLicenseNumber || '-' }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.businessLicenseUrl')">
                <template v-if="tenantDetail?.verification.businessLicenseUrl">
                  <div class="flex items-center gap-2">
                    <ElLink
                      :href="tenantDetail.verification.businessLicenseUrl"
                      type="primary"
                      target="_blank"
                    >
                      {{ $t('tenant.review.openMaterial') }}
                    </ElLink>
                    <ElImage
                      :src="tenantDetail.verification.businessLicenseUrl"
                      fit="contain"
                      :preview-src-list="[tenantDetail.verification.businessLicenseUrl]"
                      preview-teleported
                      class="h-14 w-20 rounded border border-[var(--el-border-color-lighter)]"
                    />
                  </div>
                </template>
                <span v-else>-</span>
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.legalPersonIdFrontUrl')">
                <template v-if="tenantDetail?.verification.legalPersonIdFrontUrl">
                  <div class="flex items-center gap-2">
                    <ElLink
                      :href="tenantDetail.verification.legalPersonIdFrontUrl"
                      type="primary"
                      target="_blank"
                    >
                      {{ $t('tenant.review.openMaterial') }}
                    </ElLink>
                    <ElImage
                      :src="tenantDetail.verification.legalPersonIdFrontUrl"
                      fit="contain"
                      :preview-src-list="[tenantDetail.verification.legalPersonIdFrontUrl]"
                      preview-teleported
                      class="h-14 w-20 rounded border border-[var(--el-border-color-lighter)]"
                    />
                  </div>
                </template>
                <span v-else>-</span>
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.legalPersonIdBackUrl')">
                <template v-if="tenantDetail?.verification.legalPersonIdBackUrl">
                  <div class="flex items-center gap-2">
                    <ElLink
                      :href="tenantDetail.verification.legalPersonIdBackUrl"
                      type="primary"
                      target="_blank"
                    >
                      {{ $t('tenant.review.openMaterial') }}
                    </ElLink>
                    <ElImage
                      :src="tenantDetail.verification.legalPersonIdBackUrl"
                      fit="contain"
                      :preview-src-list="[tenantDetail.verification.legalPersonIdBackUrl]"
                      preview-teleported
                      class="h-14 w-20 rounded border border-[var(--el-border-color-lighter)]"
                    />
                  </div>
                </template>
                <span v-else>-</span>
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.legalPersonName')">
                {{ tenantDetail?.verification.legalPersonName || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.legalPersonIdNumber')">
                {{ maskIdNumber(tenantDetail?.verification.legalPersonIdNumber) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.bankAccountName')">
                {{ tenantDetail?.verification.bankAccountName || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.bankName')">
                {{ tenantDetail?.verification.bankName || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.bankAccountNumber')">
                {{ maskBankAccount(tenantDetail?.verification.bankAccountNumber) }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.reviewedByName')">
                {{ tenantDetail?.verification.reviewedByName || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.reviewedBy')">
                {{ tenantDetail?.verification.reviewedBy || '-' }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.reviewedAt')">
                {{ formatDateTime(tenantDetail?.verification.reviewedAt) }}
              </ElDescriptionsItem>

              <ElDescriptionsItem :label="$t('tenant.review.field.additionalDataJson')" :span="3">
                <ElInput
                  v-if="tenantDetail?.verification.additionalDataJson"
                  :model-value="tenantDetail.verification.additionalDataJson"
                  type="textarea"
                  :rows="2"
                  readonly
                />
                <span v-else>-</span>
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('tenant.review.field.reviewRemarks')" :span="3">
                <ElInput
                  v-if="tenantDetail?.verification.reviewRemarks"
                  :model-value="tenantDetail.verification.reviewRemarks"
                  type="textarea"
                  :rows="2"
                  readonly
                />
                <span v-else>-</span>
              </ElDescriptionsItem>
            </ElDescriptions>
          </div>

          <div class="col-span-4">
            <ElDivider content-position="left" class="my-2">{{
              $t('tenant.review.section.action')
            }}</ElDivider>
            <ElForm ref="formRef" :model="form" :rules="rules" label-width="80px">
              <ElFormItem :label="$t('tenant.review.tenantName')">
                <ElInput v-model="tenantName" disabled />
              </ElFormItem>
              <ElFormItem :label="$t('tenant.review.claim.label')">
                <div class="w-full space-y-2">
                  <div class="flex items-center justify-between gap-2">
                    <div class="flex items-center gap-2 text-sm">
                      <template v-if="reviewClaim">
                        <ElTag type="warning">{{ $t('tenant.review.claim.claimed') }}</ElTag>
                        <span>{{
                          $t('tenant.review.claim.claimedBy', { name: reviewClaim.claimedByName })
                        }}</span>
                      </template>
                      <template v-else>
                        <ElTag type="success">{{ $t('tenant.review.claim.unclaimed') }}</ElTag>
                      </template>
                    </div>
                    <div class="flex items-center gap-2">
                      <ElButton
                        v-if="!reviewClaim"
                        size="small"
                        type="primary"
                        :loading="claimLoading"
                        @click="handleClaim"
                      >
                        {{ $t('tenant.review.claim.claimButton') }}
                      </ElButton>
                      <ElButton
                        v-else-if="isClaimedByMe"
                        size="small"
                        :loading="claimLoading"
                        @click="handleReleaseClaim"
                      >
                        {{ $t('tenant.review.claim.releaseButton') }}
                      </ElButton>
                      <ElButton
                        v-else
                        size="small"
                        type="danger"
                        :disabled="!canForceClaim"
                        :loading="claimLoading"
                        @click="handleForceClaim"
                      >
                        {{ $t('tenant.review.claim.forceButton') }}
                      </ElButton>
                    </div>
                  </div>

                  <ElAlert
                    v-if="reviewClaim && !isClaimedByMe"
                    type="warning"
                    :closable="false"
                    :title="
                      $t('tenant.review.claim.readonlyTip', { name: reviewClaim.claimedByName })
                    "
                  />
                </div>
              </ElFormItem>
              <ElFormItem :label="$t('tenant.review.result')" prop="approve">
                <ElRadioGroup v-model="form.approve" :disabled="!canOperate">
                  <ElRadio :value="true">{{ $t('tenant.review.approve') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('tenant.review.reject') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
              <ElFormItem
                v-if="form.approve === true"
                :label="$t('tenant.review.renewMonths')"
                prop="renewMonths"
              >
                <div class="flex w-full items-center gap-2">
                  <ElInputNumber
                    v-model="form.renewMonths"
                    :disabled="!canOperate"
                    :min="1"
                    :precision="0"
                    :step="1"
                    controls-position="right"
                    class="w-full"
                  />
                  <span class="whitespace-nowrap text-sm text-[var(--el-text-color-secondary)]">
                    {{ $t('tenant.review.monthUnit') }}
                  </span>
                </div>
              </ElFormItem>
              <ElFormItem
                v-if="form.approve === true"
                :label="$t('tenant.review.operatingMode')"
                prop="operatingMode"
              >
                <ElRadioGroup v-model="form.operatingMode" :disabled="!canOperate">
                  <ElRadio :value="OperatingMode.SameEntity">
                    {{ $t('tenant.review.operatingModeOptions.same') }}
                  </ElRadio>
                  <ElRadio :value="OperatingMode.DifferentEntity">
                    {{ $t('tenant.review.operatingModeOptions.different') }}
                  </ElRadio>
                </ElRadioGroup>
              </ElFormItem>
              <ElFormItem
                :label="$t('tenant.review.rejectReason')"
                v-if="form.approve === false"
                prop="rejectReasonKey"
              >
                <div class="w-full space-y-2">
                  <ElSelect
                    v-model="form.rejectReasonKey"
                    :disabled="!canOperate"
                    :placeholder="$t('tenant.review.rejectReasonPlaceholder')"
                    class="w-full"
                  >
                    <ElOption
                      v-for="item in rejectReasonOptions"
                      :key="item"
                      :label="$t(`tenant.review.rejectReasons.${item}`)"
                      :value="item"
                    />
                  </ElSelect>

                  <div class="flex flex-wrap gap-2">
                    <ElTag
                      v-for="item in quickRejectReasonOptions"
                      :key="item"
                      class="cursor-pointer"
                      @click="handlePickRejectReason(item)"
                    >
                      {{ $t(`tenant.review.rejectReasons.${item}`) }}
                    </ElTag>
                  </div>
                </div>
              </ElFormItem>
              <ElFormItem
                v-if="form.approve === false && form.rejectReasonKey === RejectReasonKey.Other"
                :label="$t('tenant.review.rejectReasonCustom')"
                prop="customRejectReason"
              >
                <ElInput
                  v-model="form.customRejectReason"
                  :disabled="!canOperate"
                  type="textarea"
                  :rows="3"
                  :placeholder="$t('tenant.review.rejectReasonPlaceholder')"
                />
              </ElFormItem>
            </ElForm>

            <ElDivider content-position="left" class="my-2">{{
              $t('tenant.review.section.history')
            }}</ElDivider>
            <ElSkeleton :loading="auditLoading" animated>
              <template #template>
                <div class="space-y-2">
                  <div class="h-5 w-3/5 rounded bg-[var(--el-fill-color-light)]"></div>
                  <div class="h-5 w-4/5 rounded bg-[var(--el-fill-color-light)]"></div>
                  <div class="h-5 w-2/5 rounded bg-[var(--el-fill-color-light)]"></div>
                </div>
              </template>
              <template #default>
                <ElTimeline v-if="auditLogs.length">
                  <ElTimelineItem
                    v-for="log in auditLogs"
                    :key="log.id"
                    :timestamp="formatDateTime(log.createdAt)"
                    placement="top"
                  >
                    <div class="text-sm font-medium">{{ log.title }}</div>
                    <div class="text-xs text-[var(--el-text-color-secondary)]">
                      {{ log.operatorName || '-' }}
                    </div>
                    <div v-if="log.description" class="mt-1 text-sm">{{ log.description }}</div>
                  </ElTimelineItem>
                </ElTimeline>
                <ElEmpty v-else :description="$t('tenant.review.history.empty')" />
              </template>
            </ElSkeleton>
          </div>
        </div>
      </template>
    </ElSkeleton>
    <template #footer>
      <ElButton @click="visible = false">{{ $t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="loading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import {
    ElMessage,
    type FormInstance,
    type FormRules,
    ElDescriptions,
    ElDescriptionsItem,
    ElDivider,
    ElImage,
    ElInput,
    ElInputNumber,
    ElLink,
    ElSkeleton
  } from 'element-plus'
  import { useI18n } from 'vue-i18n'
  import {
    fetchClaimTenantReview,
    fetchForceClaimTenantReview,
    fetchGetTenantDetail,
    fetchGetTenantAuditLogs,
    fetchGetTenantReviewClaim,
    fetchReleaseTenantReviewClaim,
    fetchReviewTenant
  } from '@/api/tenant'
  import { SubscriptionStatus as SubscriptionStatusEnum } from '@/enums/SubscriptionStatus'
  import { TenantPackageTypeEnum } from '@/enums/TenantPackageType'
  import { TenantVerificationStatus } from '@/enums/TenantVerificationStatus'
  import { OperatingMode } from '@/enums/OperatingMode'
  import { useUserStore } from '@/store/modules/user'
  import { HttpError } from '@/utils/http/error'

  const { t } = useI18n()
  const visible = ref(false)
  const loading = ref(false)
  const detailLoading = ref(false)
  const claimLoading = ref(false)
  const auditLoading = ref(false)
  const tenantId = ref('')
  const tenantName = ref('')
  const formRef = ref<FormInstance>()
  const tenantDetail = ref<Api.Tenant.TenantDetailDto>()
  const reviewClaim = ref<Api.Tenant.TenantReviewClaimDto | null>(null)
  const auditLogs = ref<Api.Tenant.TenantAuditLogDto[]>([])

  enum RejectReasonKey {
    MaterialsIncomplete = 'materialsIncomplete',
    LicenseInvalid = 'licenseInvalid',
    IdentityMismatch = 'identityMismatch',
    ContactUnreachable = 'contactUnreachable',
    DuplicateRegistration = 'duplicateRegistration',
    Other = 'other'
  }

  const RejectReasonKeyValues = Object.values(RejectReasonKey) as RejectReasonKey[]
  const rejectReasonOptions = RejectReasonKeyValues
  const quickRejectReasonOptions = RejectReasonKeyValues.filter((x) => x !== RejectReasonKey.Other)

  const form = reactive({
    approve: true,
    rejectReasonKey: '' as RejectReasonKey | '',
    customRejectReason: '',
    renewMonths: 1 as number | null,
    operatingMode: OperatingMode.SameEntity as OperatingMode | undefined
  })

  const rules = computed<FormRules>(() => ({
    approve: [{ required: true, message: t('tenant.review.selectResult'), trigger: 'change' }],
    rejectReasonKey: [
      {
        validator: (_rule, value: unknown, callback) => {
          // 1. 仅当选择“驳回”时校验原因
          if (form.approve !== false) return callback()

          // 2. 必须选择原因
          if (!value) return callback(new Error(t('tenant.review.rejectReasonPlaceholder')))
          return callback()
        },
        trigger: 'change'
      }
    ],
    customRejectReason: [
      {
        validator: (_rule, value: unknown, callback) => {
          // 1. 仅当驳回且选择“其他”时要求填写自定义原因
          if (form.approve !== false || form.rejectReasonKey !== RejectReasonKey.Other)
            return callback()

          // 2. 自定义原因不能为空
          const text = typeof value === 'string' ? value.trim() : ''
          if (!text) return callback(new Error(t('tenant.review.rejectReasonPlaceholder')))
          return callback()
        },
        trigger: 'blur'
      }
    ],
    renewMonths: [
      {
        validator: (_rule, value: unknown, callback) => {
          // 1. 仅当选择“通过”时校验续费时长
          if (form.approve !== true) return callback()

          // 2. 必须为正整数
          const numberValue = typeof value === 'number' ? value : Number(value)
          if (!Number.isInteger(numberValue) || numberValue <= 0) {
            return callback(new Error(t('tenant.review.renewMonthsPlaceholder')))
          }
          return callback()
        },
        trigger: 'change'
      }
    ],
    operatingMode: [
      {
        validator: (_rule, value: unknown, callback) => {
          // 1. 仅当选择“通过”时校验经营模式
          if (form.approve !== true) return callback()

          // 2. 必须选择经营模式
          if (!value) return callback(new Error(t('tenant.review.operatingModePlaceholder')))
          return callback()
        },
        trigger: 'change'
      }
    ]
  }))

  const emit = defineEmits(['success'])
  const userStore = useUserStore()

  const currentUserId = computed(() => String(userStore.getUserInfo?.userId || ''))
  const canForceClaim = computed(() => userStore.permissions.includes('tenant:review:force-claim'))
  const isClaimedByMe = computed(
    () => !!reviewClaim.value && reviewClaim.value.claimedBy === currentUserId.value
  )
  const canOperate = computed(() => !!reviewClaim.value && isClaimedByMe.value)

  const open = async (row: Api.Tenant.TenantDto) => {
    // 1. 初始化基础状态
    tenantId.value = row.id
    tenantName.value = row.name
    form.approve = true
    form.rejectReasonKey = ''
    form.customRejectReason = ''
    form.renewMonths = 1
    form.operatingMode = OperatingMode.SameEntity
    visible.value = true

    // 2. 拉取详情（含认证信息）、领取信息与审核历史
    await Promise.all([fetchDetail(), fetchClaim(), fetchAuditLogs()])
  }

  const handleClosed = () => {
    // 1. 重置表单与数据
    formRef.value?.resetFields()
    tenantDetail.value = undefined
    reviewClaim.value = null
    auditLogs.value = []
  }

  watch(
    () => form.approve,
    (approve) => {
      // 1. 切换到“通过”时清理驳回原因
      if (approve === true) {
        form.rejectReasonKey = ''
        form.customRejectReason = ''
        form.renewMonths = form.renewMonths ?? 1
        form.operatingMode = form.operatingMode ?? OperatingMode.SameEntity
      } else {
        form.renewMonths = null
        form.operatingMode = undefined
      }

      // 2. 触发表单校验刷新
      void formRef.value?.validateField([
        'rejectReasonKey',
        'customRejectReason',
        'renewMonths',
        'operatingMode'
      ])
    }
  )

  const buildRejectReason = () => {
    // 1. 选择“其他”使用自定义原因
    if (form.rejectReasonKey === RejectReasonKey.Other) {
      return form.customRejectReason.trim()
    }

    // 2. 否则使用固定原因文案
    return form.rejectReasonKey ? t(`tenant.review.rejectReasons.${form.rejectReasonKey}`) : ''
  }

  const handlePickRejectReason = (key: RejectReasonKey) => {
    // 1. 快捷选择常用原因
    if (!canOperate.value) {
      return
    }

    form.rejectReasonKey = key
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    // 1. 领取前禁止提交审核（只读模式提示领取人）
    if (!reviewClaim.value) {
      ElMessage.warning(t('tenant.review.claim.needClaimFirst'))
      return
    }

    if (!isClaimedByMe.value) {
      ElMessage.warning(
        t('tenant.review.claim.claimedByTip', { name: reviewClaim.value.claimedByName })
      )
      return
    }

    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          loading.value = true
          await fetchReviewTenant(tenantId.value, {
            approve: form.approve,
            reason: form.approve ? undefined : buildRejectReason(),
            renewMonths: form.approve ? (form.renewMonths as number) : undefined,
            operatingMode: form.approve ? (form.operatingMode as OperatingMode) : undefined
          })
          ElMessage.success(t('tenant.review.success'))
          visible.value = false
          emit('success')
        } catch (error) {
          console.error(error)
        } finally {
          loading.value = false
        }
      }
    })
  }

  const fetchClaim = async () => {
    if (!tenantId.value) return

    try {
      claimLoading.value = true
      reviewClaim.value = await fetchGetTenantReviewClaim(tenantId.value)
    } catch (error) {
      console.error(error)
      reviewClaim.value = null
    } finally {
      claimLoading.value = false
    }
  }

  const handleClaim = async () => {
    if (!tenantId.value) return

    try {
      claimLoading.value = true
      reviewClaim.value = await fetchClaimTenantReview(tenantId.value)
      await fetchAuditLogs()
    } catch (error) {
      if (error instanceof HttpError) {
        ElMessage.warning(error.message)
      } else {
        console.error(error)
      }
    } finally {
      claimLoading.value = false
    }
  }

  const handleForceClaim = async () => {
    if (!tenantId.value) return

    if (!canForceClaim.value) {
      ElMessage.warning(t('tenant.review.claim.forceDenied'))
      return
    }

    try {
      claimLoading.value = true
      reviewClaim.value = await fetchForceClaimTenantReview(tenantId.value)
      await fetchAuditLogs()
    } catch (error) {
      if (error instanceof HttpError) {
        ElMessage.warning(error.message)
      } else {
        console.error(error)
      }
    } finally {
      claimLoading.value = false
    }
  }

  const handleReleaseClaim = async () => {
    if (!tenantId.value) return

    try {
      claimLoading.value = true
      reviewClaim.value = await fetchReleaseTenantReviewClaim(tenantId.value)
      await fetchAuditLogs()
    } catch (error) {
      if (error instanceof HttpError) {
        ElMessage.warning(error.message)
      } else {
        console.error(error)
      }
    } finally {
      claimLoading.value = false
    }
  }

  const fetchAuditLogs = async () => {
    if (!tenantId.value) return

    try {
      auditLoading.value = true
      const res = await fetchGetTenantAuditLogs(tenantId.value, { page: 1, pageSize: 20 })
      auditLogs.value = res.items || []
    } catch (error) {
      console.error(error)
      auditLogs.value = []
    } finally {
      auditLoading.value = false
    }
  }

  const fetchDetail = async () => {
    if (!tenantId.value) return

    try {
      detailLoading.value = true
      tenantDetail.value = await fetchGetTenantDetail(tenantId.value)
    } catch (error) {
      console.error(error)
    } finally {
      detailLoading.value = false
    }
  }

  const formatDateTime = (value?: string) => {
    if (!value) return '-'
    const date = new Date(value)
    return Number.isNaN(date.getTime()) ? value : date.toLocaleString()
  }

  const maskIdNumber = (value?: string) => {
    if (!value) return '-'
    if (value.length <= 8) return value
    return `${value.slice(0, 4)}****${value.slice(-4)}`
  }

  const maskBankAccount = (value?: string) => {
    if (!value) return '-'
    if (value.length <= 8) return value
    return `${value.slice(0, 4)}****${value.slice(-4)}`
  }

  // 3. 页面展示辅助（套餐/订阅）
  const renderBool = (value: boolean) => (value ? t('common.yes') : t('common.no'))

  const renderPrice = (value?: number) => {
    if (value === null || value === undefined) return '--'
    return `￥${Number(value).toFixed(2)}`
  }

  const renderPackageQuota = (pkg?: Api.Tenant.TenantPackageDto) => {
    if (!pkg) return '-'

    const fields = [
      { label: t('tenantPackage.form.maxStoreCount'), value: pkg.maxStoreCount },
      { label: t('tenantPackage.form.maxAccountCount'), value: pkg.maxAccountCount },
      { label: t('tenantPackage.form.maxStorageGb'), value: pkg.maxStorageGb },
      { label: t('tenantPackage.form.maxSmsCredits'), value: pkg.maxSmsCredits },
      { label: t('tenantPackage.form.maxDeliveryOrders'), value: pkg.maxDeliveryOrders }
    ].filter((item) => item.value !== null && item.value !== undefined)

    if (!fields.length) return t('tenantPackage.table.quotaEmpty')
    return fields.map((item) => `${item.label}: ${item.value}`).join(' / ')
  }

  const getPackageTypeText = (value?: number) => {
    if (value === null || value === undefined) return '-'

    switch (value) {
      case TenantPackageTypeEnum.Free:
        return t('tenantPackage.type.free')
      case TenantPackageTypeEnum.Standard:
        return t('tenantPackage.type.standard')
      case TenantPackageTypeEnum.Professional:
        return t('tenantPackage.type.professional')
      case TenantPackageTypeEnum.Enterprise:
        return t('tenantPackage.type.enterprise')
      default:
        return t('tenantPackage.type.unknown')
    }
  }

  const getSubscriptionStatusText = (status?: number) => {
    switch (status) {
      case SubscriptionStatusEnum.Pending:
        return t('tenant.subscriptionStatus.pending')
      case SubscriptionStatusEnum.Active:
        return t('tenant.subscriptionStatus.active')
      case SubscriptionStatusEnum.GracePeriod:
        return t('tenant.subscriptionStatus.gracePeriod')
      case SubscriptionStatusEnum.Cancelled:
        return t('tenant.subscriptionStatus.cancelled')
      case SubscriptionStatusEnum.Suspended:
        return t('tenant.subscriptionStatus.suspended')
      default:
        return t('tenant.subscriptionStatus.unknown')
    }
  }

  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')
    }
  }

  defineExpose({ open })
</script>

<style scoped>
  /* 1. 适度放大弹窗内信息密度，提升可读性 */
  .tenant-review-dialog :deep(.el-descriptions__label),
  .tenant-review-dialog :deep(.el-descriptions__content) {
    font-size: 14px;
  }

  .tenant-review-dialog :deep(.el-divider__text) {
    font-size: 14px;
  }
</style>
