<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: 'id',
    label: '主键',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'organId',
    label: '机构号',
    component: 'Input',
    // remove: true
    remove: () => actionType.value === 'update'
    // remove: (item) => {
    //   console.log(item)
    //   return actionType.value === 'update'
    // }
  },
  {
    field: 'name',
    label: '角色名称',
    component: 'Input'
  },
  {
    field: 'dataScope',
    label: '权限范围',
    component: 'Input'
  },
  {
    field: 'createBy',
    label: '创建人',
    component: 'Input'
  },
  {
    field: 'createDate',
    label: '创建时间',
    component: 'Input'
    // component: 'DatePicker',
    // componentProps: {
    //   style: {
    //     width: '100%'
    //   }
    // }
  },
  {
    field: 'updateBy',
    label: '最近修改人',
    component: 'Input'
  },
  {
    field: 'delFlag',
    label: '逻辑删除标记',
    component: 'Select',
    componentProps: {
      style: {
        width: '100%'
      },
      options: [
        {
          label: '正常',
          value: '0'
        },
        {
          label: '删除',
          value: '1'
        }
      ]
    }
  },
  {
    field: 'remarks',
    label: '描述',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea'
    }
  }
])

const rules = reactive({
  // id: [required()],
  // organId: [required()],
  // name: [required()],
  // dataScope: [required()],
  // createBy: [required()],
  // createDate: [required()],
  // updateBy: [required()],
  // updateDate: [required()],
  // remarks: [required()],
  delFlag: [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>
