<script setup lang="ts">
import { ElMessage } from 'element-plus'
import AppUpload from '@/components/base/AppUpload.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { updateUser } from '../api'
import { useUserStore } from '@/stores/user'
import { pick } from 'lodash-es'
const userStore = useUserStore()
const userInfo = userStore.user

const formRef = $ref<FormInstance>()
const form = reactive({
  real_name: '',
  avatar: '',
  gender: 1
})
const rules = ref<FormRules>({
  real_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
})
onMounted(() => {
  Object.assign(form, pick(userInfo, ['real_name', 'avatar', 'gender']))
})
// 提交
function handleSubmit() {
  formRef?.validate().then(update)
}
// 修改
const update = () => {
  updateUser(form).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
  })
}
</script>

<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    hide-required-asterisk
    label-width="60px"
    label-position="left"
    style="width: 360px"
  >
    <el-form-item label="昵称" prop="real_name">
      <el-input v-model="form.real_name" maxlength="10" />
    </el-form-item>
    <el-form-item label="头像" prop="avatar">
      <AppUpload v-model="form.avatar" accept="image/*">
        <template #tip>支持png，jpg，jpep图片格式，最大为2MB</template>
      </AppUpload>
    </el-form-item>
    <el-form-item label="性别" prop="gender">
      <el-radio-group v-model="form.gender" disabled>
        <el-radio :label="1" size="large">男</el-radio>
        <el-radio :label="2" size="large">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>
