<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import dayjs from 'dayjs'
import { useValidator } from '@/hooks/web/useValidator'
import { getLoginNameByUserInfo } from '@/utils/auth'

const { required } = useValidator()
const session_loginName = getLoginNameByUserInfo();
const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  },
  actionType: {
    type: String,
    default: 'add'
  }
})
const formSchema = reactive<FormSchema[]>([
  {
    field: 'systemCode',
    label: '系统编码',
    component: 'Input',
    componentProps: {
      disabled: props.actionType === 'edit'
    },
  },
  {
    field: 'systemName',
    label: '系统名称',
    component: 'Input',
    componentProps: {

    },
  },
  {
    field: 'systemVersion',
    label: '系统版本号',
    component: 'Input',
    componentProps: {
      disabled: props.actionType === 'edit'
    },
  },
  {
    field: 'createUser',
    label: '创建人',
    component: 'Input',
    componentProps: {
      disabled: props.actionType === 'edit'
    },
    value:session_loginName,
    hidden:true
  },
  {
    field: 'createTime',
    label: '创建时间',
    component: 'DatePicker',
    componentProps: {
      disabled: props.actionType === 'edit'
    },
    remove: props.actionType === 'add'
  },
  {
    field: 'startTime',
    label: '开始时间',
    component: 'DatePicker',
    componentProps: {

    },
  },
  {
    field: 'endTime',
    label: '结束时间',
    component: 'DatePicker',
    componentProps: {

    },
  }
])

const rules = reactive({
  systemCode: [required()],
  systemName: [required()],
  systemVersion: [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()
    const { startTime, endTime } = formData;
    Object.assign(formData, { startTime: dayjs(startTime).format('YYYY-MM-DD') })
    Object.assign(formData, { endTime: dayjs(endTime).format('YYYY-MM-DD') })
    return formData
  }
}

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

defineExpose({
  submit
})
</script>

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

