<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 { ElSelect, ElOption } from 'element-plus'

const { required } = useValidator()

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

const formSchema = ref<FormSchema[]>([
  {
    field: 'status',
    label: '审核结果',
    component: 'Select',
    colProps: {
      span: 24
    },
    value: 1,
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <ElSelect
                v-model={data.status}
                onChange={(val: any) => {
                  selectStatus(val)
                }}
              >
                <ElOption label={'通过'} value={1}></ElOption>
                <ElOption label={'拒绝'} value={2}></ElOption>
              </ElSelect>
            </>
          )
        }
      }
    }
    // componentProps: {
    //   options: [
    //     {
    //       label: '通过',
    //       value: 1
    //     },
    //     {
    //       label: '拒绝',
    //       value: 2
    //     }
    //   ]
    // }
  },
  {
    field: 'reason',
    label: '原因',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '如拒绝请输入原因',
      type: 'textarea'
    }
  },
  {
    field: 'id',
    label: 'id',
    hidden: true,
    component: 'Input'
  }
])

const rules = ref({
  reason: [required('请输入拒绝原因')]
})

const selectStatus = (item: any) => {
  console.log(item)
  if (item == 2) {
    rules.value.reason = [required('请输入拒绝原因')]
  } else {
    rules.value.reason = [
      {
        required: false
      }
    ]
  }
}
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>
