<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" size="small">
    <el-form-item label="姓名" prop="fullName">
      <el-input v-model="form.fullName" />
    </el-form-item>
    <el-form-item label="手机号码" prop="mobile">
      <el-input v-model="form.mobile" />
    </el-form-item>
    <el-form-item label="电子邮箱" prop="email">
      <el-input v-model="form.email" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :loading="loading" @click="submitFn">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { updateSelfUserDetail } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { isMobile, isEmail } from '@/utils/validate'
import type { FormInstance, FormRules } from 'element-plus'

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive({
  fullName: userStore.userInfo?.fullName || '',
  mobile: userStore.userInfo?.mobile || '',
  email: userStore.userInfo?.email || ''
})

const rules: FormRules = {
  fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { validator: (_r, v, cb) => { if (!isMobile(v)) cb(new Error('请输入正确手机号')); else cb() }, trigger: 'blur' }
  ],
  email: [
    { validator: (_r, v, cb) => { if (v && !isEmail(v)) cb(new Error('请输入正确邮箱')); else cb() }, trigger: 'blur' }
  ]
}

const submitFn = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true
    await updateSelfUserDetail({ ...form })
    userStore.setUserInfo({ ...userStore.userInfo, ...form })
    ElMessage.success('保存成功')
  } catch (error: any) {
    ElMessage.error(error?.data?.msg || '保存失败')
  } finally {
    loading.value = false
  }
}
</script>
