<template>
  <Dialog :title="'租户续费'" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <!-- id：选中租户的 id，只读展示 -->
      <el-form-item label="租户 ID" prop="id">
        <el-input v-model="formData.id" disabled />
      </el-form-item>

      <!-- packageId：套餐选择框 -->
      <el-form-item label="续费套餐" prop="packageId">
        <el-select v-model="formData.packageId" placeholder="请选择套餐" class="w-240px">
          <el-option v-for="pkg in packageList" :key="pkg.id" :label="pkg.name" :value="pkg.id" />
        </el-select>
      </el-form-item>

      <!-- remark：备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" :rows="3" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" :loading="formLoading" @click="submitForm">
        确 定
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import * as TenantApi from '@/api/system/tenant'
import * as TenantPackageApi from '@/api/system/tenantPackage'

const message = useMessage()
const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)

// 表单数据：id / packageId / remark
const formData = reactive<{
  id: number | null
  packageId: number | null
  remark: string
}>({
  id: null,
  packageId: null,
  remark: ''
})

const formRules = {
  packageId: [{ required: true, message: '请选择续费套餐', trigger: 'change' }],
  // 如果备注必填就放开下面这一条
  // remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
}

// 套餐列表
const packageList = ref<TenantPackageApi.TenantPackageVO[]>([])

// 对外暴露的 open 方法：传入租户 id
const open = async (id: number) => {
  // 重置表单
  formData.id = id
  formData.packageId = null
  formData.remark = ''
  dialogVisible.value = true

  // 需要时再加载套餐列表
  if (!packageList.value.length) {
    packageList.value = await TenantPackageApi.getTenantPackageList()
  }
}

defineExpose({ open })

// 提交
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    formLoading.value = true
    try {
      // 🔴 根据你原来续费的接口改这里的调用
      // 假设后端有一个 TenantApi.renewTenant
      await TenantApi.renewal({
        id: formData.id,
        packageId: formData.packageId,
        remark: formData.remark
      })

      message.success('续费成功')
      dialogVisible.value = false
      emit('success') // 通知父组件刷新列表
    } catch (e) {
      console.error(e)
    } finally {
      formLoading.value = false
    }
  })
}
</script>
