<script lang="ts" setup>
import { FormSchema, Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateAdmin } from '@/api/system/admin'

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({})
  }
})

const { required, lengthRange } = useValidator()

const formSchema = reactive<FormSchema[]>([
  {
    field: 'realName',
    label: '昵称',
    component: 'Input',
    colProps: {
      span: 24
    }
  }
])

const rules = reactive({
  realName: [
    required(),
    lengthRange({
      min: 4,
      max: 64,
      message: '请输入4-64个字符'
    })
  ]
})

const { formRegister, formMethods } = useForm()
const { setValues, getElFormExpose, getFormData } = formMethods

watch(
  () => props.userInfo,
  (value) => {
    setValues(value)
  },
  {
    immediate: true,
    deep: true
  }
)
const emit = defineEmits(['success'])
const saveLoading = ref(false)
const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    ElMessageBox.confirm('是否确认修改?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          saveLoading.value = true
          const upData = await getFormData()
          await updateAdmin({
            real_name: upData.realName
          })
          emit('success')
          // 这里可以调用修改用户信息接口
          ElMessage.success('修改成功')
        } catch (error) {
          console.log(error)
        } finally {
          saveLoading.value = false
        }
      })
      .catch(() => {})
  }
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <BaseButton type="primary" @click="save">保存</BaseButton>
</template>
