<template>
  <Form ref="formRef" :labelWidth="200" :rules="rules" :schema="schema">
    <template #sex="form">
      <el-radio-group v-model="form['sex']">
        <el-radio :value="1">{{ t('index.user.man') }}</el-radio>
        <el-radio :value="2">{{ t('index.user.woman') }}</el-radio>
      </el-radio-group>
    </template>
  </Form>
  <div style="text-align: center">
    <XButton :title="t('common.save')" type="primary" @click="submit()" />
    <XButton :title="t('common.reset')" type="danger" @click="init()" />
  </div>
</template>

<script lang="ts" setup>
import type { FormRules } from 'element-plus'
import { FormSchema } from '@/types/form'
import type { FormExpose } from '@/components/Form'
import { useUserStore } from '@/store/modules/user'
import { 
  getDept,
  updateDept,
  DeptVO
} from '@/api/system/dept/index'
import { ref, reactive, onMounted, defineOptions, unref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'

defineOptions({ name: 'UserInfo' })

const { t } = useI18n()
const message = useMessage()
const userStore = useUserStore()

// const data = ref<DeptVO | null>(null)

const rules = reactive<FormRules>({
  nickname: [{ required: true, message: t('index.user.user.nickname'), trigger: 'blur' }],
  email: [
    { required: true, message: t('index.user.user.mail'), trigger: 'blur' },
    {
      type: 'email',
      message: t('index.user.user.truemail'),
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    { required: true, message: t('index.user.user.phone'), trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: t('index.user.user.truephone'),
      trigger: 'blur'
    }
  ]
})

const schema = reactive<FormSchema[]>([
  {
    field: 'user.nickname',
    label: t('res.user.nickname'),
    component: 'Input'
  },
  {
    field: 'user.mobile',
    label: t('index.user.user.mobile'),
    component: 'Input'
  },
  {
    field: 'email',
    label: t('index.user.user.email'),
    component: 'Input'
  },
  {
    field: 'sex',
    label: t('index.user.user.sex'),
    component: 'Radio'
  }
])

const formRef = ref<FormExpose>()

const submit = async () => {
  const elForm = unref(formRef)?.getElFormRef()
  if (!elForm) return
  elForm.validate(async (valid) => {
    if (valid) {
      const formData = unref(formRef)?.formModel as DeptVO
      console.log('提交的数据:', formData)
      await updateDept(formData)
      message.success(t('common.updateSuccess'))
      userStore.setUserNicknameAction(formData.user.nickname)
    }
  })
}

const init = async () => {
  const res = await getDept(114)
  console.log('获取的数据:', res)
  unref(formRef)?.setValues(res)
  return res
}

onMounted(async () => {
  await init()
})
</script>
