import {string} from "@/uni_modules/uv-ui-tools/libs/function/test";

export const fnPlaceholder = () => {
}

export const confirmAsync = async (msgOrOptions) => {
    return new Promise((resolve, reject) => {
        const inputOptions = string(msgOrOptions) ? {content: msgOrOptions} : msgOrOptions
        const defaultOptions = {
            success: res => {
                if (res.confirm) resolve()
                else reject('user cancelled')
            }
        }
        const options = Object.assign({}, defaultOptions, inputOptions)
        uni.showModal(options)
    })
}

export const alertAsync = async (msgOrOptions) => {
    const options = string(msgOrOptions) ? {content: msgOrOptions} : msgOrOptions
    options.showCancel = false
    return confirmAsync(options)
}

export const autoFormValidate = function (instance, event) {
    // $uv.formValidate 在vue3并不能正常运行，setup与options不通用。
    const formItem = findAncestorComponentByName(instance, 'uv-form-item')
    const form = findAncestorComponentByName(formItem, 'uv-form')
    if (formItem && form) {
        // TODO: 现在只让它支持error-change，其它保持原逻辑。
        // 原change逻辑触发过余频繁，可以将trigger: ['change', 'error-change'] 保持原样
        if (event == 'change' && formItem.message) event = 'error-' + event
        form.validateField(formItem.prop, fnPlaceholder, event)
    }
}

export const findAncestorComponentByName = function (instance, name) {
    let parent = instance?.parent; // 获取父组件实例
    while (parent) {
        // 判断父组件的名称是否匹配
        if (parent.type?.name === name) return parent.proxy; // 找到匹配的祖先组件
        parent = parent.parent; // 向上查找父组件
    }
    return null; // 如果未找到匹配的祖先组件，返回 null
}