<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
import { UpImgButtom } from '@/components/UpFile'
import { getProductCategory } from '@/api/goods'
const { required } = useValidator()

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

const formSchema = ref<FormSchema[]>([
  {
    field: 'pid',
    label: '父级',
    component: 'Select',
    colProps: {
      span: 24
    },
    value: 0,
    optionApi: async () => {
      const { data } = await getProductCategory({ pid: -1, limit: 9999, page: 1 })
      const list = [
        {
          label: '顶级',
          value: 0
        },
        ...data.map((data) => {
          return {
            value: data.id,
            label: data.name
          }
        })
      ]
      return list
    }
  },
  {
    field: 'name',
    label: '分类名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入分类名称'
    }
  },
  {
    field: 'image',
    label: '图标',
    value: [],
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return <UpImgButtom v-model={data.image} />
        }
      }
    }
  },
  {
    field: 'sort',
    label: '排序',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'number',
      placeholder: '请输入排序'
    }
  },
  {
    field: 'is_show',
    value: true,
    colProps: {
      span: 24
    },
    label: '是否显示',
    component: 'Switch'
  },
  {
    field: 'id',
    label: 'id',
    hidden: true,
    component: 'Input'
  }
])

const rules = ref({
  name: [required('请填写分类名称')],
  default_price: [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>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
