<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 { getUserDictApi, getRoleListParamsApi, checkUserNameApi } from '@/api/auth/user'
import { DepartmentUserItem } from '@/api/dict/types'
import { useI18n } from '@/hooks/web/useI18n'
import { transfDictList } from '@/utils'
import type { ListItem } from '@/api/dict/types'

const { t } = useI18n()

const { required, phone, email } = useValidator()

const actionType = ref('add')

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

const SEX_DICT_LIST: ListItem[] = [
  { label: '男', value: '0' },
  { label: '女', value: '1' }
]

const formSchema = reactive<FormSchema[]>([
  {
    field: 'username',
    label: t('userDemo.username'),
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'name',
    label: t('userDemo.name'),
    component: 'Input'
  },
  {
    field: 'password',
    label: t('userDemo.password'),
    component: 'InputPassword',
    componentProps: {
      style: {
        width: '100%'
      }
    },
    hidden: actionType.value === 'update'
  },
  {
    field: 'repassword',
    label: t('userDemo.repassword'),
    component: 'InputPassword',
    componentProps: {
      style: {
        width: '100%'
      }
    },
    hidden: actionType.value === 'update'
  },
  {
    field: 'organId',
    label: t('userDemo.organId'),
    component: 'Select',
    componentProps: {
      style: {
        width: '100%'
      },
      options: []
    }
  },
  {
    field: 'sex',
    label: t('userDemo.sex'),
    component: 'RadioGroup',
    componentProps: {
      options: SEX_DICT_LIST
    },
    value: '0'
  },
  {
    field: 'mobile',
    label: t('userDemo.mobile'),
    component: 'Input'
  },
  {
    field: 'email',
    label: t('userDemo.email'),
    component: 'Input'
  },
  {
    field: 'roleIds',
    label: t('userDemo.roleIds'),
    component: 'Transfer',
    colProps: {
      span: 24
    },
    componentProps: {
      props: {
        key: 'id',
        label: 'name',
        disabled: 'disabled'
      },
      titles: [t('userDemo.roleIds'), t('userDemo.selected')],
      data: [],
      renderContent: (h, option) => {
        return h('span', null, `${option.name}`)
      }
    },
    value: []
  }
])

const rules = reactive({
  username: [
    required(),
    {
      trigger: 'blur',
      asyncValidator: async (_, val, callback) => {
        if (actionType.value !== 'add') {
          callback()
        }
        const res = await checkUserNameApi(val)
        if (!res.data) {
          callback(new Error(t('userDemo.userNameExist')))
        } else {
          callback()
        }
      }
    }
  ],
  name: [required()],
  password: [required()],
  repassword: [
    required(),
    {
      asyncValidator: async (_, val, callback) => {
        const formData = await getFormData()
        const { password } = formData
        if (val !== password) {
          callback(new Error(t('inputPassword.passwordDiff')))
        } else {
          callback()
        }
      }
    }
  ],
  mobile: [phone()],
  email: [email()]
})

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

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const { roleIds } = formData
    return {
      ...formData,
      type: actionType.value,
      roleIds: roleIds.join(',')
    }
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    actionType.value = 'update'
    delSchema('password')
    delSchema('repassword')
    setSchema([
      {
        field: 'username',
        path: 'componentProps.disabled',
        value: true
      }
    ])
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

const getRoleListParams = async () => {
  const res = await getRoleListParamsApi()
  if (res) {
    const data: {
      id: number
      name: string
      disabled: boolean
    }[] = res.data.data.roles
    setSchema([
      {
        field: 'roleIds',
        path: 'componentProps.data',
        value: data
      }
    ])
  }
}

const getUserDict = async () => {
  const res = await getUserDictApi()
  if (res) {
    const ORGAN_LIST = transfDictList(res.data.data.ORGAN_LIST)
    setSchema([
      {
        field: 'organId',
        path: 'componentProps.options',
        value: ORGAN_LIST
      }
    ])
  }
}

const initParams = async () => {
  await getRoleListParams()
  await getUserDict()
}
initParams()

defineExpose({
  submit
})
</script>

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