<script setup lang="ts">
import type { IProp } from "@sud-web/vue-hooks/useModalForm"
import type { IPayItem } from "@/api/recharge/types/recharge"
import useModalForm, { emits, propsData } from "@sud-web/vue-hooks/useModalForm"
import { ElMessage } from "element-plus"
import { reactive } from "vue"
import { addPay, editPay } from "@/api/recharge"

defineOptions({ name: "DemoModal" })

// 父级透传 visible / mode / data / disabled（来自 useDialogOut）
const props = withDefaults(defineProps<IProp<Partial<IPayItem>>>(), propsData)
const emit = defineEmits(emits)

// 表单数据
const formData = reactive({
  txId: "",
  txType: "",
  amount: "",
  status: "READY"
})

const rules = {
  txType: [{ required: true, message: "请输入交易类型", trigger: "blur" }],
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }]
}

const { formRef, title, loading, submitForm, handleResSuccess, close } = useModalForm({
  props,
  emit,
  // 新增初始化：先清空校验再设默认值（resetForm 存在时 hook 不再自动 resetFields）
  resetForm() {
    formRef.value?.resetFields()
    Object.assign(formData, { txId: "", txType: "", amount: "", status: "READY" })
  },
  // 编辑 / 查看打开时回显
  setFormData() {
    Object.assign(formData, props.data)
  },
  // 校验通过后的提交逻辑
  async handleSubmit() {
    const api = props.mode === "add" ? addPay : editPay
    await api({ ...formData })
    handleResSuccess() // 成功提示 + 关闭弹窗 + emit('submit')
  },
  successTips() {
    ElMessage.success(props.mode === "add" ? "新增成功" : "编辑成功")
  }
})
</script>

<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    width="520px"
    @update:model-value="(val: boolean) => !val && close()"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :disabled="disabled"
      label-width="90px"
    >
      <el-form-item v-if="mode !== 'add'" label="交易号" prop="txId">
        <el-input v-model="formData.txId" disabled />
      </el-form-item>
      <el-form-item label="交易类型" prop="txType">
        <el-input v-model="formData.txType" placeholder="请输入交易类型" />
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input v-model="formData.amount" placeholder="请输入金额" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option label="成功" value="SUCCESS" />
          <el-option label="处理中" value="READY" />
          <el-option label="已关闭" value="CLOSED" />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 查看模式隐藏底部按钮 -->
    <template v-if="mode !== 'check'" #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>
