<template>
  <ElDialog
    v-model="visible"
    :title="$t('subscription.changePlan.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('subscription.changePlan.currentPackage')">
        <div class="current-package">{{ currentPackageName }}</div>
      </ElFormItem>

      <!-- 2. 新套餐 -->
      <ElFormItem :label="$t('subscription.changePlan.newPackage')" prop="newPackageId">
        <ElSelect
          v-model="formModel.newPackageId"
          :placeholder="$t('subscription.changePlan.newPackagePlaceholder')"
          style="width: 100%"
        >
          <ElOption
            v-for="pkg in packageOptions"
            :key="pkg.id"
            :label="`${pkg.name} - ${formatPrice(pkg)}`"
            :value="pkg.id"
            :disabled="pkg.id === currentPackageId"
          />
        </ElSelect>
      </ElFormItem>

      <!-- 3. 生效时间 -->
      <ElFormItem :label="$t('subscription.changePlan.effectiveTime')" prop="effectiveTime">
        <ElRadioGroup v-model="formModel.effectiveTime">
          <ElRadio value="now">{{ $t('subscription.changePlan.effectiveNow') }}</ElRadio>
          <ElRadio value="nextCycle">{{
            $t('subscription.changePlan.effectiveNextCycle')
          }}</ElRadio>
        </ElRadioGroup>
      </ElFormItem>

      <!-- 4. 备注 -->
      <ElFormItem :label="$t('subscription.changePlan.notes')" prop="notes">
        <ElInput
          v-model="formModel.notes"
          :placeholder="$t('subscription.changePlan.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('common.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 { changeSubscriptionPlan } from '@/api/subscription'
  import { fetchTenantPackageList } from '@/api/tenant-package'

  defineOptions({ name: 'ChangePlanDialog' })

  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 currentSubscriptionId = ref<string>('')
  const currentPackageId = ref<string>('')
  const currentPackageName = ref<string>('')

  const packageOptions = ref<Api.Tenant.TenantPackageDto[]>([])

  const formModel = reactive({
    newPackageId: '',
    effectiveTime: 'now' as 'now' | 'nextCycle',
    notes: ''
  })

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

  // 3. 加载套餐列表
  const loadPackageOptions = async () => {
    try {
      loading.value = true
      const response = await fetchTenantPackageList({
        PageSize: 100,
        IsActive: true
      })
      packageOptions.value = response.items
    } catch (error) {
      console.error('Failed to load package options:', error)
    } finally {
      loading.value = false
    }
  }

  // 4. 格式化价格
  const formatPrice = (pkg: Api.Tenant.TenantPackageDto) => {
    if (pkg.monthlyPrice && pkg.monthlyPrice > 0) {
      return `¥${pkg.monthlyPrice}/月`
    }
    if (pkg.yearlyPrice && pkg.yearlyPrice > 0) {
      return `¥${pkg.yearlyPrice}/年`
    }
    return '免费'
  }

  // 5. 打开弹窗
  const open = (row: Api.Subscription.SubscriptionDto) => {
    visible.value = true

    // 记录当前订阅信息
    currentSubscriptionId.value = row.id
    currentPackageId.value = row.tenantPackageId
    currentPackageName.value = row.packageName || row.tenantPackageName || '-'

    // 初始化表单
    formModel.newPackageId = ''
    formModel.effectiveTime = 'now'
    formModel.notes = ''
    formRef.value?.clearValidate()
  }

  // 6. 关闭处理
  const handleClosed = () => {
    currentSubscriptionId.value = ''
    currentPackageId.value = ''
    currentPackageName.value = ''
    formRef.value?.resetFields()
  }

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

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

      submitting.value = true
      try {
        await changeSubscriptionPlan(currentSubscriptionId.value, {
          targetPackageId: formModel.newPackageId,
          immediate: formModel.effectiveTime === 'now',
          notes: formModel.notes || undefined
        })

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

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

  defineExpose({ open })
</script>

<style scoped>
  .current-package {
    font-weight: 600;
    color: var(--el-color-primary);
  }
</style>
