<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref, reactive } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
import { FormRules } from 'element-plus'
import { mapAddressData } from '@/api/system/admin/types'

const actionAddress = ref<mapAddressData>()
const { required } = useValidator()
const rules = reactive<FormRules>({
  brand_name: [required('请填写品牌名称')]
})

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

const formSchema = ref<FormSchema[]>([
  {
    field: 'brand_name',
    label: '品牌名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入品牌名称'
    }
  },
  {
    field: 'is_show',
    label: '是否显示',
    component: 'Switch',
    colProps: {
      span: 24
    }
  },
  {
    field: 'id',
    label: 'id',
    hidden: true,
    component: 'Input'
  }
])

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  console.log('触发')
  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)
    actionAddress.value = {
      adcode: currentRow.area,
      label: currentRow.detail_address,
      lng: currentRow.longitude,
      lat: currentRow.latitude
    }
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

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