<script setup>
import { ref } from 'vue'
import { UpdateService } from '@/api/user'
const dialogVisible = ref(false)
const formModel = ref({
  id: '',
  username: '',
  phone: '',
  email: ''
})
const formRef = ref()
const rules = {
  username: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '电话不能为空', trigger: 'blur' }],
  email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }]
}

// 组件对外暴露一个方法 open ，基于 open 传来的参数，区分添加还是编辑
const open = (userInfo) => {
  formModel.value = {
    id: userInfo.id || '',
    username: userInfo.username || '',
    phone: userInfo.userPhone || '',
    email: userInfo.email || ''
  }
  dialogVisible.value = true
}
// 向外暴露
defineExpose({
  open
})
const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate()
  ElMessageBox.confirm('确认提交？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const {
        data: { message }
      } = await UpdateService(formModel.value)
      ElNotification({
        title: 'Success',
        message: message,
        type: 'success'
      })
      emit('success')
      onClose()
    })
    .catch(() => {
      // ElNotification({
      //   title: 'Warning',
      //   message: '服务错误，请稍后重试',
      //   type: 'warning'
      // })
    })
}

const onClose = () => {
  dialogVisible.value = false
  formRef.value.clearValidate()
  // 重置数据
  formModel.value = {
    id: '',
    username: '',
    phone: '',
    email: ''
  }
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="用户信息修改"
    width="20%"
    @close="onClose"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-position="left"
      label-width="120"
    >
      <el-form-item label="用户名（昵称）" prop="username">
        <el-input
          placeholder="请输入用户名（昵称）"
          v-model="formModel.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          placeholder="请输入联系电话"
          v-model="formModel.phone"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input placeholder="请输入邮箱" v-model="formModel.email"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
