<template>
  <ElDrawer
    v-model="visible"
    :title="$t('tenant.detail.title')"
    size="800px"
    direction="rtl"
    @closed="handleClosed"
  >
    <ElTabs v-model="activeTab" class="px-4">
      <!-- Tab 1: 基本信息 -->
      <ElTabPane :label="$t('tenant.tabs.basicInfo')" name="basic">
        <div class="py-3" v-loading="basicLoading">
          <ElAlert v-if="basicError" type="error" show-icon :title="basicError" class="mb-4" />

          <ElDescriptions :column="2" border>
            <ElDescriptionsItem :label="$t('tenant.detail.tenantId')">
              {{ tenantDetail?.tenant?.id || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.code')">
              {{ tenantDetail?.tenant?.code || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.name')">
              {{ tenantDetail?.tenant?.name || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.shortName')">
              {{ tenantDetail?.tenant?.shortName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.contactName')">
              {{ tenantDetail?.tenant?.contactName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.contactPhone')">
              {{ tenantDetail?.tenant?.contactPhone || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.contactEmail')">
              {{ tenantDetail?.tenant?.contactEmail || '-' }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </ElTabPane>

      <!-- Tab 2: 状态信息 -->
      <ElTabPane :label="$t('tenant.tabs.statusInfo')" name="status">
        <div class="py-3" v-loading="basicLoading">
          <ElAlert v-if="basicError" type="error" show-icon :title="basicError" class="mb-4" />

          <ElDescriptions :column="2" border>
            <ElDescriptionsItem :label="$t('tenant.detail.status')">
              <ElTag :type="getTenantStatusTagType(tenantDetail?.tenant?.status)">
                {{ getTenantStatusText(tenantDetail?.tenant?.status) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.verificationStatus')">
              <ElTag :type="getVerificationStatusTagType(tenantDetail?.tenant?.verificationStatus)">
                {{ getVerificationStatusText(tenantDetail?.tenant?.verificationStatus) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.autoRenew')">
              <ElTag :type="tenantDetail?.tenant?.autoRenew ? 'success' : 'info'">
                {{ tenantDetail?.tenant?.autoRenew ? $t('common.yes') : $t('common.no') }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.currentPackage')">
              {{ tenantDetail?.package?.name || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.effectiveFrom')">
              {{ formatDateTime(tenantDetail?.tenant?.effectiveFrom) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.effectiveTo')">
              {{ formatDateTime(tenantDetail?.tenant?.effectiveTo) }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </ElTabPane>

      <!-- Tab 3: 订阅信息 -->
      <ElTabPane :label="$t('tenant.tabs.subscription')" name="subscription">
        <div class="py-3" v-loading="basicLoading">
          <ElAlert v-if="basicError" type="error" show-icon :title="basicError" class="mb-4" />

          <ElDescriptions :column="2" border>
            <ElDescriptionsItem :label="$t('tenant.detail.currentPackage')">
              {{ tenantDetail?.package?.name || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.status')">
              <ElTag :type="getSubscriptionStatusTagType(displaySubscription?.status)">
                {{ getSubscriptionStatusText(displaySubscription?.status) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.autoRenew')">
              <ElTag :type="displaySubscription?.autoRenew ? 'success' : 'info'">
                {{ displaySubscription?.autoRenew ? $t('common.yes') : $t('common.no') }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.effectiveFrom')">
              {{ formatDateTime(displaySubscription?.effectiveFrom) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('tenant.detail.effectiveTo')">
              {{ formatDateTime(displaySubscription?.effectiveTo) }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </ElTabPane>

      <!-- Tab 4: 配额概览（简化版） -->
      <ElTabPane :label="$t('tenant.tabs.quotaOverview')" name="quota">
        <div class="py-3" v-loading="quotaLoading">
          <ElAlert v-if="quotaError" type="error" show-icon :title="quotaError" class="mb-4" />

          <ElEmpty v-if="!quotaUsageList.length" :description="$t('tenant.quota.usageSummary')" />

          <div v-else class="space-y-3">
            <div
              v-for="item in quotaUsageList"
              :key="item.quotaType"
              class="rounded-md border border-[var(--el-border-color-lighter)] p-3"
            >
              <div class="mb-2 flex items-center justify-between">
                <div class="font-semibold">{{ getQuotaTypeText(item.quotaType) }}</div>
                <div class="text-sm text-[var(--el-text-color-secondary)]">
                  {{ getQuotaPercentageText(item.usedValue, item.limitValue) }}
                </div>
              </div>

              <div class="mb-2 grid grid-cols-2 gap-2 text-sm">
                <div class="flex items-center justify-between">
                  <span class="text-[var(--el-text-color-secondary)]">
                    {{ $t('tenant.quota.usedValue') }}
                  </span>
                  <span>{{ formatQuotaValue(item.quotaType, item.usedValue) }}</span>
                </div>
                <div class="flex items-center justify-between">
                  <span class="text-[var(--el-text-color-secondary)]">
                    {{ $t('tenant.quota.limitValue') }}
                  </span>
                  <span>{{ formatQuotaValue(item.quotaType, item.limitValue) }}</span>
                </div>
              </div>

              <ElProgress
                :percentage="getQuotaPercentage(item.usedValue, item.limitValue)"
                :stroke-width="10"
                :color="getQuotaProgressColor(getQuotaPercentage(item.usedValue, item.limitValue))"
              />
            </div>
          </div>
        </div>
      </ElTabPane>

      <!-- Tab 5: 账单信息 -->
      <ElTabPane :label="$t('tenant.tabs.billing')" name="billing">
        <div class="py-3" v-loading="billingLoading">
          <ElAlert v-if="billingError" type="error" show-icon :title="billingError" class="mb-4" />

          <ElTable :data="billingList" border size="small">
            <ElTableColumn
              :label="$t('billing.field.statementNo')"
              prop="statementNo"
              min-width="160"
            />
            <ElTableColumn :label="$t('billing.field.status')" min-width="120">
              <template #default="{ row }">
                <ElTag :type="getBillingStatusTagType(row.status)">
                  {{ getBillingStatusText(row.status) }}
                </ElTag>
              </template>
            </ElTableColumn>
            <ElTableColumn :label="$t('billing.field.amountDue')" min-width="140" align="right">
              <template #default="{ row }">
                {{ formatAmount(row.amountDue, row.currency || 'CNY') }}
              </template>
            </ElTableColumn>
            <ElTableColumn :label="$t('billing.field.dueDate')" min-width="150">
              <template #default="{ row }">
                {{ formatDate(row.dueDate) }}
              </template>
            </ElTableColumn>
            <ElTableColumn :label="$t('billing.field.createdAt')" min-width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </ElTableColumn>
          </ElTable>
        </div>
      </ElTabPane>
    </ElTabs>
  </ElDrawer>
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import { TenantBillingStatus } from '@/enums/Billing'
  import { SubscriptionStatus } from '@/enums/SubscriptionStatus'
  import { TenantStatus } from '@/enums/TenantStatus'
  import { TenantVerificationStatus } from '@/enums/TenantVerificationStatus'
  import {
    fetchGetTenantBillings,
    fetchGetTenantDetail,
    fetchGetTenantQuotaUsage
  } from '@/api/tenant'
  import { formatAmount, formatDate, formatDateTime } from '@/utils/billing'

  defineOptions({ name: 'TenantDetailDrawer' })

  type TenantDetailTab = 'basic' | 'status' | 'subscription' | 'quota' | 'billing'

  const { t } = useI18n()

  const visible = ref(false)
  const activeTab = ref<TenantDetailTab>('basic')

  const tenantId = ref<string>('')
  const currentLoadToken = ref(0)

  const tenantDetail = ref<Api.Tenant.TenantDetailDto | null>(null)
  const quotaUsageList = ref<Api.QuotaPackage.TenantQuotaUsageDto[]>([])
  const billingList = ref<Api.Billing.BillingListDto[]>([])

  const basicLoading = ref(false)
  const quotaLoading = ref(false)
  const billingLoading = ref(false)

  const basicError = ref<string | null>(null)
  const quotaError = ref<string | null>(null)
  const billingError = ref<string | null>(null)

  const hasLoadedQuota = ref(false)
  const hasLoadedBilling = ref(false)

  // 直接使用 tenantDetail 中的 subscription 字段，避免调用 POST 接口
  const displaySubscription = computed(() => {
    return tenantDetail.value?.subscription || null
  })

  const getTenantStatusTagType = (status: number | undefined) => {
    switch (status) {
      case TenantStatus.Active:
        return 'success'
      case TenantStatus.PendingReview:
        return 'warning'
      case TenantStatus.Suspended:
        return 'danger'
      case TenantStatus.Expired:
        return 'info'
      case TenantStatus.Closed:
        return 'info'
      default:
        return 'info'
    }
  }

  // 1. 按后端 TenantStatus 枚举值渲染租户状态
  const getTenantStatusText = (status: number | undefined) => {
    switch (status) {
      case TenantStatus.Active:
        return t('tenant.status.active')
      case TenantStatus.PendingReview:
        return t('tenant.status.pendingReview')
      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 getVerificationStatusTagType = (status: number | undefined) => {
    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 | undefined) => {
    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 getSubscriptionStatusTagType = (status: number | undefined) => {
    switch (status) {
      case SubscriptionStatus.Active:
        return 'success'
      case SubscriptionStatus.Suspended:
        return 'danger'
      case SubscriptionStatus.Cancelled:
        return 'info'
      default:
        return 'info'
    }
  }

  // 3. 按后端 SubscriptionStatus 枚举值渲染订阅状态（租户 i18n 仅维护常用状态）
  const getSubscriptionStatusText = (status: number | undefined) => {
    switch (status) {
      case SubscriptionStatus.Active:
        return t('tenant.subscriptionStatus.active')
      case SubscriptionStatus.Suspended:
        return t('tenant.subscriptionStatus.suspended')
      case SubscriptionStatus.Cancelled:
        return t('tenant.subscriptionStatus.cancelled')
      default:
        return t('tenant.subscriptionStatus.unknown')
    }
  }

  const getQuotaTypeText = (quotaType: number) => {
    const map: Record<number, string> = {
      0: t('quotaPackage.quotaType.storeCount'),
      1: t('quotaPackage.quotaType.accountCount'),
      2: t('quotaPackage.quotaType.storage'),
      3: t('quotaPackage.quotaType.smsCredits'),
      4: t('quotaPackage.quotaType.deliveryOrders'),
      5: t('quotaPackage.quotaType.promotionSlots')
    }
    return map[quotaType] || '-'
  }

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

  const getQuotaPercentage = (usedValue: number, limitValue: number) => {
    if (!limitValue) return 0
    return Math.min(100, Math.round((usedValue / limitValue) * 100))
  }

  const getQuotaPercentageText = (usedValue: number, limitValue: number) => {
    return `${getQuotaPercentage(usedValue, limitValue)}%`
  }

  // 5. 进度条颜色：<50% 绿色、50-80% 黄色、>80% 红色
  const getQuotaProgressColor = (percentage: number) => {
    if (percentage >= 80) return 'var(--el-color-danger)'
    if (percentage >= 50) return 'var(--el-color-warning)'
    return 'var(--el-color-success)'
  }

  const getBillingStatusTagType = (status: number) => {
    switch (status) {
      case TenantBillingStatus.Pending:
        return 'warning'
      case TenantBillingStatus.Paid:
        return 'success'
      case TenantBillingStatus.Overdue:
        return 'danger'
      case TenantBillingStatus.Cancelled:
        return 'info'
      default:
        return 'info'
    }
  }

  // 6. 按后端 TenantBillingStatus 枚举值渲染账单状态
  const getBillingStatusText = (status: number) => {
    switch (status) {
      case TenantBillingStatus.Pending:
        return t('billing.status.pending')
      case TenantBillingStatus.Paid:
        return t('billing.status.paid')
      case TenantBillingStatus.Overdue:
        return t('billing.status.overdue')
      case TenantBillingStatus.Cancelled:
        return t('billing.status.cancelled')
      default:
        return '-'
    }
  }

  const loadTenantDetail = async (token: number) => {
    if (!tenantId.value) return

    basicLoading.value = true
    basicError.value = null
    try {
      // 1. 拉取租户详情（基础数据）
      const res = await fetchGetTenantDetail(tenantId.value, { showErrorMessage: false })
      if (token !== currentLoadToken.value) return
      tenantDetail.value = res
    } catch (error) {
      console.error(error)
      basicError.value = t('tenant.error.loadDetailFailed')
      ElMessage.error(basicError.value)
    } finally {
      basicLoading.value = false
    }
  }

  const loadQuotaUsage = async (token: number) => {
    if (!tenantId.value || hasLoadedQuota.value) return

    quotaLoading.value = true
    quotaError.value = null
    try {
      // 1. 懒加载配额使用情况
      const list = await fetchGetTenantQuotaUsage(tenantId.value, { showErrorMessage: false })
      if (token !== currentLoadToken.value) return
      quotaUsageList.value = list
      hasLoadedQuota.value = true
    } catch (error) {
      console.error(error)
      quotaError.value = t('tenant.error.loadQuotaFailed')
      ElMessage.error(quotaError.value)
    } finally {
      quotaLoading.value = false
    }
  }

  const loadBillings = async (token: number) => {
    if (!tenantId.value || hasLoadedBilling.value) return

    billingLoading.value = true
    billingError.value = null
    try {
      // 1. 懒加载账单信息（最近10条）
      const res = await fetchGetTenantBillings(
        tenantId.value,
        { Page: 1, PageSize: 10 },
        { showErrorMessage: false }
      )
      if (token !== currentLoadToken.value) return
      billingList.value = res.items || []
      hasLoadedBilling.value = true
    } catch (error) {
      console.error(error)
      billingError.value = t('tenant.error.loadBillingFailed')
      ElMessage.error(billingError.value)
    } finally {
      billingLoading.value = false
    }
  }

  const open = async (id: string) => {
    visible.value = true

    // 1. 初始化 Drawer 状态
    tenantId.value = id
    activeTab.value = 'basic'
    currentLoadToken.value += 1
    const token = currentLoadToken.value

    basicError.value = null
    quotaError.value = null
    billingError.value = null

    tenantDetail.value = null
    quotaUsageList.value = []
    billingList.value = []

    hasLoadedQuota.value = false
    hasLoadedBilling.value = false

    // 2. 拉取基础信息
    await loadTenantDetail(token)
  }

  // 2. Tab 懒加载：切到对应 Tab 时才拉取数据（订阅信息已包含在 tenantDetail 中，无需单独加载）
  watch(
    activeTab,
    async (tab) => {
      if (!visible.value || !tenantId.value) return

      const token = currentLoadToken.value
      switch (tab) {
        case 'quota':
          await loadQuotaUsage(token)
          break
        case 'billing':
          await loadBillings(token)
          break
        default:
          break
      }
    },
    { flush: 'post' }
  )

  const handleClosed = () => {
    // 1. 关闭时清理状态，防止并发请求回写
    currentLoadToken.value += 1
    tenantId.value = ''
    activeTab.value = 'basic'

    tenantDetail.value = null
    quotaUsageList.value = []
    billingList.value = []

    basicError.value = null
    quotaError.value = null
    billingError.value = null

    hasLoadedQuota.value = false
    hasLoadedBilling.value = false
  }

  defineExpose({ open })
</script>
