<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'

const { required } = useValidator()

const actionType = ref('add')

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

const formSchema = reactive<FormSchema[]>([
  {
    field: 'pkid',
    label: '会话id',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'userId',
    label: '登录号',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'userName',
    label: '用户名称',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'organCode',
    label: '机构',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'organName',
    label: '机构名称',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'parentOrgan',
    label: '上级机构',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'loginIp',
    label: '登录ip',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'loginTime',
    label: '登录时间',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'url',
    label: '登录URL',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'logoutTime',
    label: '退出时间',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  }
])

const rules = reactive({
  component: [required()],
  path: [required()],
  pkid: [required()],
  userId: [required()],
  userName: [required()],
  organCode: [required()],
  organName: [required()],
  parentOrgan: [required()],
  loginIp: [required()],
  loginTime: [required()],
  url: [required()],
  logoutTime: [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
  }
}

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

defineExpose({
  submit
})
</script>

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