<script setup>
import { ref } from 'vue'
import { adminAddService } from '@/api/user'
import { User } from '@element-plus/icons-vue'
const dialogTableVisible = ref(false)
const form = ref()
const formModel = ref({
  username: '',
  phone: '',
  email: ''
})
// 整个表单的校验规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
}
// 组件对外暴露一个方法 open ，基于 open 传来的参数，区分添加还是编辑
const open = () => {
  dialogTableVisible.value = true
}
const addAdmin = async () => {
  await form.value.validate()

  ElMessageBox.confirm('确认添加?', '提示', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning'
  })
    .then(async () => {
      await adminAddService(formModel.value)
      ElMessage.success('操作成功')
      emit('success')
      close()
    })
    .catch(() => {})
}

// 向外暴露
defineExpose({
  open
})

const emit = defineEmits(['success'])

const close = () => {
  dialogTableVisible.value = false
  form.value.clearValidate()
  // 重置数据
  formModel.value = {
    username: '',
    phone: '',
    email: ''
  }
}
</script>
<template>
  <el-dialog
    v-model="dialogTableVisible"
    title="管理员信息添加"
    width="500"
    @close="close"
  >
    <el-form
      :model="formModel"
      :rules="rules"
      ref="form"
      size="large"
      autocomplete="off"
    >
      <el-form-item prop="username">
        <el-input
          v-model="formModel.username"
          :prefix-icon="User"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="phone">
        <el-input
          :prefix-icon="User"
          placeholder="请输入电话号码"
          v-model="formModel.phone"
        ></el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input
          v-model="formModel.email"
          :prefix-icon="User"
          placeholder="请输入邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="button"
          type="success"
          auto-insert-space
          @click="addAdmin"
          >点击添加</el-button
        >
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
