<template>
  <ElDialog
    v-model="visible"
    :title="$t('quotaPackage.purchase.title')"
    width="560px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="110px" v-loading="loading">
      <!-- 1. 租户信息 -->
      <ElFormItem :label="$t('quotaPackage.purchase.tenant')">
        <div class="tenant-info">{{ tenantName }}</div>
      </ElFormItem>

      <!-- 2. 选择配额包 -->
      <ElFormItem :label="$t('quotaPackage.purchase.quotaPackage')" prop="quotaPackageId">
        <ElSelect
          v-model="formModel.quotaPackageId"
          :placeholder="$t('quotaPackage.purchase.quotaPackagePlaceholder')"
          style="width: 100%"
          @change="handlePackageChange"
        >
          <ElOption
            v-for="pkg in packageOptions"
            :key="pkg.id"
            :label="`${pkg.name} - ${getQuotaTypeText(pkg.quotaType)} (${formatQuotaValue(pkg.quotaType, pkg.quotaValue)})`"
            :value="pkg.id"
          />
        </ElSelect>
      </ElFormItem>

      <!-- 3. 价格展示 -->
      <ElFormItem :label="$t('quotaPackage.purchase.price')">
        <div class="price-display">
          <span class="price-value">¥{{ selectedPackage?.price || 0 }}</span>
        </div>
      </ElFormItem>

      <!-- 4. 备注 -->
      <ElFormItem :label="$t('quotaPackage.purchase.notes')" prop="notes">
        <ElInput
          v-model="formModel.notes"
          :placeholder="$t('quotaPackage.purchase.notesPlaceholder')"
          type="textarea"
          :rows="3"
          maxlength="256"
          show-word-limit
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="visible = false">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">
          {{ $t('quotaPackage.purchase.confirm') }}
        </ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { fetchQuotaPackageList, fetchPurchaseQuotaPackage } from '@/api/quotaPackage'

  defineOptions({ name: 'PurchaseQuotaDialog' })

  const { t } = useI18n()

  const emit = defineEmits<{
    (e: 'success'): void
  }>()

  // 1. 响应式变量
  const visible = ref(false)
  const loading = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()
  const tenantId = ref<string>('')
  const tenantName = ref<string>('')

  const packageOptions = ref<Api.QuotaPackage.QuotaPackageListDto[]>([])
  const selectedPackage = ref<Api.QuotaPackage.QuotaPackageListDto | null>(null)

  const formModel = reactive({
    quotaPackageId: '',
    notes: ''
  })

  // 2. 表单校验规则
  const rules = computed<FormRules>(() => ({
    quotaPackageId: [
      { required: true, message: t('quotaPackage.validation.packageRequired'), trigger: 'change' }
    ]
  }))

  // 3. 配额类型文本
  const getQuotaTypeText = (quotaType: number) => {
    const texts: 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 texts[quotaType] || '-'
  }

  // 4. 格式化配额值
  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()
    }
  }

  // 5. 加载配额包列表
  const loadPackageOptions = async () => {
    try {
      loading.value = true
      const response = await fetchQuotaPackageList({ isActive: true, pageSize: 100 })
      packageOptions.value = response.items
    } catch (error) {
      console.error('Failed to load package options:', error)
    } finally {
      loading.value = false
    }
  }

  // 6. 选择配额包变化
  const handlePackageChange = (id: string) => {
    selectedPackage.value = packageOptions.value.find((pkg) => pkg.id === id) || null
  }

  // 7. 打开弹窗
  const open = (tenant: { id: string; name: string }) => {
    visible.value = true
    tenantId.value = tenant.id
    tenantName.value = tenant.name

    // 重置表单
    formModel.quotaPackageId = ''
    formModel.notes = ''
    selectedPackage.value = null

    formRef.value?.clearValidate()
  }

  // 8. 关闭处理
  const handleClosed = () => {
    tenantId.value = ''
    tenantName.value = ''
    formRef.value?.resetFields()
  }

  // 9. 提交处理
  const handleSubmit = async () => {
    if (!formRef.value || !tenantId.value) return

    await formRef.value.validate(async (valid) => {
      if (!valid) return

      submitting.value = true
      try {
        await fetchPurchaseQuotaPackage(tenantId.value, {
          quotaPackageId: formModel.quotaPackageId,
          notes: formModel.notes || undefined
        })

        ElMessage.success(t('quotaPackage.purchase.success'))
        emit('success')
        visible.value = false
      } catch (error) {
        console.error(error)
      } finally {
        submitting.value = false
      }
    })
  }

  // 10. 生命周期
  onMounted(() => {
    void loadPackageOptions()
  })

  defineExpose({ open })
</script>

<style scoped>
  .tenant-info {
    font-weight: 600;
    color: var(--el-color-primary);
  }

  .price-display {
    display: flex;
    align-items: center;
  }

  .price-value {
    font-size: 20px;
    font-weight: 700;
    color: var(--el-color-danger);
  }
</style>
