<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
// import { useI18n } from '@/hooks/web/useI18n'
import { getInfoApi } from '@/api/user'
import { getRoleOptionsApi } from '@/api/role'

// const { t } = useI18n()

const { required, isMobilePhone } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: '用户名',
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'gender',
    label: '性别',
    component: 'RadioGroup',
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 0
        }
      ]
    }
  },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'mobile',
    label: '手机号',
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'password',
    label: '密码',
    component: 'Input',
    componentProps: {
      type: 'password'
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'avatar',
    label: '密码',
    component: 'Input',
    componentProps: {
      type: 'password'
    },
    hidden: true,
    value: '1',
    colProps: {
      span: 24
    }
  },

  {
    field: 'roles',
    label: '角色配置',
    component: 'Select',
    colProps: {
      span: 24
    },
    componentProps: {
      options: [],
      multiple: true
    },
    // 远程加载option
    optionApi: async () => {
      const res = await getRoleOptionsApi()
      return res.data.map((e: any) => {
        return {
          label: e.name,
          value: e.id
        }
      })
    }
  }
])

const rules = reactive({
  name: [required()],
  password: [required()],
  mobile: [required(), isMobilePhone()],
  roles: [required()]
})

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

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()

    return formData
  }
}

const initValue = () => {
  getInfoApi({
    id: props.currentRow.id
  }).then((res) => {
    setValues(res.data)
  })
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) {
      return
    }
    initValue()
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
