<script lang="ts" setup>
import {
  ElMessage,
  type FormInstance,
  type FormRules,
} from 'element-plus'
import Uploader from '@/components/uploader/Uploader.vue'
import Strings from '@/common/utils/strings.ts'
import UserApi from '@/pages/sys/user/user-api.ts'
import { reloadUserInfo } from '@/common/app'

const userInfoFormIns = ref<FormInstance>()

interface UserInfoForm {
  avatar?: string,
  nickname?: string,
  phone?: string,
}

const userInfoForm = reactive<UserInfoForm>({
  avatar: undefined,
  nickname: undefined,
  phone: undefined,
})

const rules = reactive<FormRules<UserInfoForm>>({
  nickname: [
    {
      validator(_, value, callback) {
        if (Strings.isBlank(value)) {
          callback(new Error('姓名不能为空'))
        } else {
          callback()
        }
      }, trigger: 'blur',
    },
  ],
  phone: [
    {
      validator(_, value, callback) {
        if (Strings.isBlank(value)) {
          callback(new Error('联系方式不能为空'))
        } else {
          callback()
        }
      }, trigger: 'blur',
    },
  ],
})
const loading = ref<boolean>(false)

function submitHandler() {
  loading.value = true

  userInfoFormIns.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error('请填写完信息')
      loading.value = false
      return
    }
    UserApi.modifyInfo(userInfoForm)
      .then(reloadUserInfo)
      .finally(() => {
        loading.value = false
      })
  })
}

defineExpose({
  reset() {
    userInfoFormIns.value?.resetFields()
  },
})
</script>

<template>
  <ElForm ref="userInfoFormIns"
    :model="userInfoForm"
    :rules="rules"
    class="user-info-form"
    status-icon
    @submit.prevent="submitHandler"
  >
    <ElFormItem prop="nickname">
      <ElInput v-model="userInfoForm.nickname" placeholder="姓名"/>
    </ElFormItem>
    <ElFormItem prop="phone">
      <ElInput v-model="userInfoForm.phone" placeholder="联系方式"/>
    </ElFormItem>
    <ElFormItem prop="avatar">
      <Uploader
        v-model:file="userInfoForm.avatar"
      />
    </ElFormItem>
    <ElFormItem class="submit-btn">
      <ElButton :loading="loading" native-type="submit" type="primary">提交</ElButton>
    </ElFormItem>
  </ElForm>
</template>

<style lang="stylus" scoped>
.user-info-form {
  :deep(.el-form-item):nth-child(3) {
    .el-form-item__content {
      width 100%;
      justify-content center
    }
  }

  .submit-btn {
    :deep(.el-form-item__content) {
      & > button {
        width 100%;
      }
    }
  }
}
</style>
