<template>
  <div>
    <!-- 1. 筛选区 -->
    <ElCard class="art-search-card" shadow="never">
      <ElForm :model="formFilters" label-width="100px">
        <ElRow :gutter="16">
          <ElCol :span="8">
            <ElFormItem :label="$t('quotaPackage.dashboard.search.tenant')">
              <ElSelect
                v-model="formFilters.tenantId"
                :placeholder="$t('quotaPackage.dashboard.search.tenantPlaceholder')"
                filterable
                remote
                clearable
                :remote-method="handleSearchTenant"
                :loading="tenantLoading"
                style="width: 100%"
                @change="handleTenantChange"
              >
                <ElOption
                  v-for="tenant in tenantOptions"
                  :key="tenant.id"
                  :label="tenant.name"
                  :value="tenant.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="16" class="text-right">
            <ElButton @click="handleReset">{{ $t('table.searchBar.reset') }}</ElButton>
            <ElButton type="primary" :loading="loading" @click="handleRefresh" v-ripple>
              {{ $t('table.searchBar.search') }}
            </ElButton>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElCard>

    <!-- 2. 仪表盘区 -->
    <ElCard class="art-table-card" shadow="never" v-loading="loading">
      <ElEmpty
        v-if="!formFilters.tenantId"
        :description="$t('quotaPackage.dashboard.empty.selectTenant')"
      />

      <ElRow v-else :gutter="16">
        <ElCol v-for="item in dashboardItems" :key="item.quotaType" :span="6">
          <div class="quota-item">
            <div class="quota-title">
              <span class="title">{{ item.label }}</span>
              <ElTag v-if="item.isOverThreshold" type="warning" effect="plain">
                {{ $t('quotaPackage.dashboard.threshold.reached', { threshold: item.threshold }) }}
              </ElTag>
            </div>

            <div class="quota-progress">
              <ElProgress
                type="dashboard"
                :percentage="item.percentage"
                :status="item.progressStatus"
              />
            </div>

            <div class="quota-meta">
              <div class="meta-line">
                <span class="label">{{ $t('quotaPackage.dashboard.meta.used') }}</span>
                <span class="value">{{ item.usedText }}</span>
              </div>
              <div class="meta-line">
                <span class="label">{{ $t('quotaPackage.dashboard.meta.total') }}</span>
                <span class="value">{{ item.totalText }}</span>
              </div>
            </div>
          </div>
        </ElCol>
      </ElRow>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import { fetchGetTenantList } from '@/api/tenant'
  import { fetchTenantQuotaUsage } from '@/api/quotaPackage'
  import { useQuotaAlertStore } from '@/store/modules/quota-alert'
  import {
    ElButton,
    ElCard,
    ElCol,
    ElEmpty,
    ElForm,
    ElFormItem,
    ElOption,
    ElProgress,
    ElRow,
    ElSelect,
    ElTag
  } from 'element-plus'

  defineOptions({ name: 'TenantQuotaUsageDashboard' })

  const { t } = useI18n()
  const quotaAlertStore = useQuotaAlertStore()

  // 1. 状态
  const loading = ref(false)
  const tenantLoading = ref(false)
  const tenantOptions = ref<Api.Tenant.TenantDto[]>([])
  const usageList = ref<Api.QuotaPackage.TenantQuotaUsageDto[]>([])

  const formFilters = ref({
    tenantId: '' as string
  })

  // 2. 配额类型文本
  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] || '-'
  }

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

  // 4. 搜索租户（远程）
  const handleSearchTenant = async (query: string) => {
    if (!query) return

    tenantLoading.value = true
    try {
      const res = await fetchGetTenantList({
        Keyword: query,
        Page: 1,
        PageSize: 20
      })
      tenantOptions.value = res.items || []
    } catch (error) {
      console.error('Search tenant error:', error)
    } finally {
      tenantLoading.value = false
    }
  }

  const handleTenantChange = (tenantId: string) => {
    if (!tenantId) return
    void loadUsage()
  }

  // 5. 加载配额使用情况
  const loadUsage = async () => {
    if (!formFilters.value.tenantId) return

    loading.value = true
    try {
      usageList.value = await fetchTenantQuotaUsage(formFilters.value.tenantId)
    } catch (error) {
      console.error('Load tenant quota usage error:', error)
    } finally {
      loading.value = false
    }
  }

  // 6. 仪表盘数据（补全常见配额类型）
  const allQuotaTypes = [0, 1, 2, 3, 4, 5]

  const dashboardItems = computed(() => {
    const map = new Map<number, Api.QuotaPackage.TenantQuotaUsageDto>()
    for (const item of usageList.value) {
      map.set(item.quotaType, item)
    }

    return allQuotaTypes.map((quotaType) => {
      const usage = map.get(quotaType)
      const usedValue = usage?.usedValue ?? 0
      const limitValue = usage?.limitValue ?? 0
      const percentage =
        limitValue > 0 ? Math.min(100, Math.round((usedValue / limitValue) * 100)) : 0
      const threshold = quotaAlertStore.getThreshold(quotaType)
      const isOverThreshold = percentage >= threshold && limitValue > 0

      return {
        quotaType,
        label: getQuotaTypeText(quotaType),
        usedText: formatQuotaValue(quotaType, usedValue),
        totalText: formatQuotaValue(quotaType, limitValue),
        percentage,
        threshold,
        isOverThreshold,
        progressStatus: isOverThreshold ? ('exception' as const) : ('success' as const)
      }
    })
  })

  // 7. 操作
  const handleRefresh = async () => {
    if (!formFilters.value.tenantId) {
      ElMessage.warning(t('quotaPackage.dashboard.message.selectTenantFirst'))
      usageList.value = []
      return
    }

    await loadUsage()
  }

  const handleReset = () => {
    formFilters.value.tenantId = ''
    usageList.value = []
  }
</script>

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

  .quota-item {
    padding: 12px;
    background: var(--el-fill-color-lighter);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
  }

  .quota-title {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
  }

  .quota-title .title {
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .quota-progress {
    display: flex;
    justify-content: center;
    margin: 8px 0;
  }

  .quota-meta {
    display: grid;
    gap: 6px;
  }

  .meta-line {
    display: flex;
    justify-content: space-between;
    color: var(--el-text-color-regular);
  }

  .meta-line .value {
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
</style>
