<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form v-if="formType === 'update'" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-form-item label="充值用户" prop="id">
        <el-input v-model="formData.id" placeholder="请输入充值用户" />
      </el-form-item>

      <el-form-item v-if="formType === 'update'" label="充值金额" prop="amount">
        <!-- 改为 el-input-number，仅允许数值输入，且最小 0 -->
        <el-input-number v-model.number="formData.amount" :min="0" controls-position="right" placeholder="请输入充值金额" />
      </el-form-item>

      <!-- 只有 transfer 类型时显示 -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>

    </el-form>


    <el-form v-if="formType === 'transfer'" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-form-item label="转账用户" prop="targetTenantId">
        <el-input v-model="formData.targetTenantId" placeholder="请输入转账用户" />
      </el-form-item>

      <el-form-item v-if="formType === 'transfer'" label="转账金额" prop="transferAmount">
        <!-- 改为 el-input-number，仅允许数值输入，且最小 0 -->
        <el-input-number v-model.number="formData.transferAmount" :min="0" controls-position="right"
          placeholder="请输入转账金额" />
      </el-form-item>

      <el-form-item v-if="formType === 'transfer'" label="登录密码" prop="password">
        <el-input v-model="formData.password" type="password" show-password placeholder="请输入登录密码" />
      </el-form-item>

      <!-- 只有 transfer 类型时显示 -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>

    </el-form>

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

<script setup lang="ts">
import { computed, ref, reactive } from 'vue'
import { TenantBalanceApi, TenantBalanceVO } from '@/api/system/tenantbalance'

/** 租户余额 表单 */
defineOptions({ name: 'TenantBalanceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；transfer - 转账等

const formData = ref({
  tenantId: undefined as number | undefined,
  id: undefined as number | undefined,
  amount: undefined as number | undefined,
  transferAmount: undefined as number | undefined,
  targetTenantId: undefined as number | undefined,
  remark: undefined as string | undefined, // 变动表述
  password: undefined as string | undefined // 登录密码
})

/** 校验规则：transfer 时才要求 remark 必填 */
const formRules = computed(() => {
  const baseRules: any = {
    id: [{ required: true, message: '用户不能为空', trigger: 'blur' }],
    amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }]
  }

  if (formType.value === 'transfer') {

    baseRules.password = [
      { required: true, message: '登录密码不能为空', trigger: 'blur' }
    ]
    baseRules.transferAmount = [
      { required: true, message: '转账金额不能为空', trigger: 'blur' }
    ]
  }

  return baseRules
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await TenantBalanceApi.getTenantBalance(id)
      // 保证有 remark 和 password 字段（接口没有的话就保持 undefined）
      formData.value = {
        tenantId: data.tenantId,
        id: data.id,
        amount: data.amount,
        targetTenantId: data.id,
        remark: undefined,
        password: undefined,
        transferAmount: undefined
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log(formData.value)
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TenantBalanceVO
    if (formType.value === 'create') {
      await TenantBalanceApi.createTenantBalance(data)
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'transfer') {
      await TenantBalanceApi.tenantTransfer(data)
      message.success(t('common.updateSuccess'))
    } else {
      await TenantBalanceApi.addAmount(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    tenantId: undefined,
    id: undefined,
    amount: undefined,
    transferAmount: undefined,
    remark: undefined,
    password: undefined
  }
  formRef.value?.resetFields()
}
</script>
