<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { SEX_DICT_LIST, STATUS_DICT_LIST } from '../constants'
import { organTreeApi, getRoleListParamsApi } from '@/api/system/SysUser'

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

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

const formSchema = reactive<FormSchema[]>([
  {
    field: 'id',
    label: '主键',
    component: 'Input',
    hidden: true
  },
  {
    field: 'username',
    label: '登录号',
    component: 'Input',
    componentProps: {
      disabled: props.actionType === 'edit'
    }
  },
  {
    field: 'name',
    label: '用户姓名',
    component: 'Input',
    componentProps: {
      disabled: props.actionType === 'edit'
    }
  },
  {
    field: 'password',
    label: '登录密码',
    component: 'Input',
    componentProps: {
      type: 'password'
    },
    remove: props.actionType === 'edit'
  },
  {
    field: 'repassword',
    label: '确认密码',
    component: 'Input',
    componentProps: {
      type: 'password'
    },
    remove: props.actionType === 'edit'
  },
  {
    field: 'organId',
    label: '机构',
    component: 'TreeSelect',
    optionApi: async () => {
      const res = await organTreeApi({
        treeid: '1',
        systemCode: 'portal'
      })
      return res.body.result
    },
    componentProps: {
      filterable: true,
      checkStrictly: true,
      nodeKey: 'id',
      props: { children: 'childs', label: 'nodeName' }
    }
  },
  {
    field: 'deptId',
    label: '所属部门',
    component: 'Input',
    componentProps: {}
  },
  {
    field: 'sex',
    label: '性别',
    component: 'RadioGroup',
    componentProps: {
      options: SEX_DICT_LIST
    }
  },
  {
    field: 'card',
    label: '证件号码',
    component: 'Input',
    componentProps: {}
  },
  {
    field: 'birthday',
    label: '出生日期',
    component: 'DatePicker',
    componentProps: {}
  },
  {
    field: 'phone',
    label: '固定电话',
    component: 'Input',
    componentProps: {}
  },
  {
    field: 'mobile',
    label: '移动电话',
    component: 'Input',
    componentProps: {}
  },
  {
    field: 'email',
    label: '邮箱地址',
    component: 'Input',
    componentProps: {}
  },
  {
    field: 'address',
    label: '地址',
    component: 'Input',
    componentProps: {}
  },
  // {
  //   field: 'no',
  //   label: '工号',
  //   component: 'Input',
  //   componentProps: {}
  // },
  {
    field: 'status',
    label: '状态',
    component: 'RadioGroup',
    componentProps: {
      options: STATUS_DICT_LIST
    },
    value: '0'
  },
  {
    field: 'roleIds',
    label: '用户角色',
    component: 'Transfer',
    colProps: {
      span: 24
    },
    componentProps: {
      props: {
        key: 'id',
        label: 'name',
        disabled: 'disabled'
      },
      titles: ['角色', '已选'],
      data: [],
      renderContent: (h, option) => {
        return h('span', null, `${option.roleName}`)
      }
    },
    value: []
  },
  {
    field: 'remarks',
    label: '描述',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: { type: 'textarea' }
  }
])

const rules = reactive({
  username: [required(), lengthRange({ min: 0, max: 50, message: '长度不能超过50' })],
  name: [required()],
  // deptId: [required()],
  organId: [required()],
  password: [required()],
  repassword: [
    required(),
    {
      validator: async (_, value, callback) => {
        const formData = await getFormData()
        if (value !== formData.password) {
          callback('您两次输入的密码不一致！')
        }
        callback()
      }
    }
  ],
  email: [email('请正确填写您的邮箱地址')],
  phone: [
    {
      pattern: /(^0[1-9]{2,3}-\d{7,9}$)/,
      message: '固定电话号码格式：区号（3-4位）-固定号码（7-9位）'
    }
  ],
  mobile: [
    {
      len: 11,
      message: '请填写11位长度的手机号码'
    },
    {
      pattern: /^1((3\d)|(4[578])|(5[0-3,5-9])|(6[67])|(7[1-3,5-8])|(8\d)|(9[013,5-9])|(44))\d{8}$/,
      message: '请正确填写您的手机号码'
    }
  ],
  card: [
    {
      pattern:
        /(^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$|^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)/,
      message: '请正确填写身份证号码'
    }
  ]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = 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
  }
}

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

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

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

defineExpose({
  submit
})
</script>

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