<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 res = await getProductCategory({ pid: 0, limit: 9999, page: 1 })
      let data = res.data.list
      const list = [
        {
          label: '顶级',
          value: 0
        },
        ...data.map((data) => {
          return {
            value: data.id,
            label: data.cate_name
          }
        })
      ]
      return list
    }
  },
  {
    field: 'cate_name',
    label: '分类名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入分类名称'
    }
  },
  {
    field: 'pic',
    label: '图标',
    value: [],
    colProps: {
      span: 24
    },
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return <UpImgButtom v-model={data.pic} />
        }
      }
    }
  },
{
    field: 'big_pic',
    label: '大图标',
    value: [],
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return <UpImgButtom v-model={data.big_pic} />
        }
      }
    }
  },
  {
    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({
  cate_name: [required('请填写分类名称')],
  pic: [required('请选择图标')],
  big_pic: [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>
