<template>
  <a-dialog v-model="dialogVisible" title="个人信息" @submit="formSubmit" @closed="formClosed">
    <a-form ref="formRef" v-model="formData" :config="formConfig" :span="24"> </a-form>
  </a-dialog>
</template>

<script setup lang="ts">
import { FormConfigType } from '@/components/AForm/type'
import { getUserInfoApi, editUserInfoApi } from '@/api/system/auth'
import { StrAnyObj } from '@/typings'
import { useUserStore } from '@/stores/modules/user'

const userStore = useUserStore()

const dialogVisible = ref(false)
const formRef = ref()
const formData = ref<StrAnyObj>({})

const formConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'nickname',
    label: '昵称',
    rule: [{ required: true, message: '昵称不能为空', trigger: 'blur' }]
  },
  {
    type: 'radio',
    prop: 'sex',
    label: '性别',
    dict: 'user_sex',
    rule: [{ required: true, message: '性别不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'phoneNumber',
    label: '手机号'
  },
  {
    type: 'input',
    prop: 'email',
    label: '邮箱'
  }
]

defineExpose({ openDialog })

function openDialog() {
  dialogVisible.value = true
  getUserInfo()
}

function getUserInfo() {
  getUserInfoApi().then((resp) => {
    formData.value = resp
  })
}

function formSubmit() {
  formRef.value.validate(() => {
    editUserInfoApi(formData.value).then(() => {
      ElMessage.success('修改个人信息成功')
      userStore.setNickname(formData.value.nickname)
      dialogVisible.value = false
    })
  })
}

function formClosed() {
  formRef.value.resetFields()
}
</script>
