<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref, onMounted } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'

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

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: '等级名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入等级名称'
    }
  },
  {
    field: 'award_ratio',
    label: '分成百分比',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'number',
      placeholder: '请输入等级'
    }
  },
  {
    field: 'info',
    label: '分成说明',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea',
      placeholder: '请输入分成说明',
      row: 4
    }
  },
  {
    field: 'id',
    label: '',
    hidden: true,
    component: 'Input'
  }
])

const rules = ref({
  name: [required('请填写团队等级')],
  award_ratio: [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,
  async (value) => {
    if (!value) return
    const currentRow = cloneDeep(value)
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

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