import type { FormInstance, FormItemProp } from 'element-plus'
import { Arrayable } from 'element-plus/es/utils'

/**
 * 用于element表单校验
 * @returns formValidate: element-plus 校验表单
 * @returns resetForm: element-plus 重置表单
 * @returns clearValidateForm: element-plus 清理表单验证信息
 * @returns validateFieldForm: element-plus 验证具体的某个字段
 * }
 */
export function useEleFormValidate() {

    // element-plus 表单校验
    function formValidate(formEl: FormInstance | undefined) {
        if (!formEl) return
        return new Promise(async (resolve, reject) => {
            await formEl.validate((valid, fields) => {
                if (valid) {
                    resolve(true)
                } else {
                    resolve(false)
                    // console.log('error submit!', fields)
                }
            })
        })
    }

    // element-plus 重置表单
    function resetForm(formEl: FormInstance | undefined) {
        if (!formEl) return
        formEl.resetFields()
    }

    // element-plus 清理表单验证信息
    async function clearValidateForm(formEl: FormInstance | undefined, props?: Arrayable<FormItemProp> | undefined) {
        if (!formEl) return
        await formEl.clearValidate(props)
    }

    // element-plus	验证具体的某个字段
    async function validateFieldForm(formEl: FormInstance | undefined, list?: Arrayable<FormItemProp>) {
        if (!formEl) return
        return new Promise(async (resolve, reject) => {
            await formEl.validateField(list, (valid, fields) => {
                if (valid) {
                    resolve(true)
                } else {
                    resolve(false)
                    // console.log('error submit!', fields)
                }
            })
        })
    }

    return {
        formValidate,
        clearValidateForm,
        validateFieldForm,
        resetForm,
    }
}