//确认框
export const showModal = async ({title, content, confirmText, cancelText}) => {
    return new Promise((resolve) => {
        uni.showModal({
            title: title,
            content: content,
            confirmText: confirmText ?? '确定',
            cancelText: cancelText ?? '取消',
            success: function (res) {
                if (res.confirm) {
                    resolve(true)
                } else if (res.cancel) {
                    resolve(false)
                }
            }
        });
    })
}

//成功提示
export const successToast = (title = '成功', duration= 2000) => {
    uni.showToast({
        title: title,
        duration: duration,
        mask: true
    });
}

//失败提示
export const errorToast = (title = '失败', duration= 1500) => {
    uni.showToast({
        title: title,
        duration: duration,
        icon: 'none'
    });
}

//获取元素信息
export const querySelect = async (_this, name) => {
    return new Promise((resolve) => {
        const query = uni.createSelectorQuery().in(_this);
        query.select(`#${name}`).boundingClientRect(data => {
            resolve(data)
        }).exec();
    })
}

//表单验证
export const formValidate = async (formRef) => {
    return new Promise( (resolve) => {
        formRef.validate().then((res) => {
            resolve(true)
        }).catch(err => {
            resolve(false)
        })
    });
}

//pdf文件预览
export const toPdfPreview = async (url) => {
    // #ifdef H5
    window.open(url, '_blank')
    // #endif
    // #ifdef APP-PLUS
    const res = await showModal({
        title: '提示',
        content: '请选择一种预览pdf的方式',
        confirmText: '系统级预览',
        cancelText: '应用内预览',
    })
    if (res) {
        openDocFile(url)
    } else {
        uni.navigateTo({
            url: '/pages/index/preview?url=' + encodeURIComponent(url)
        });
    }
    // #endif
}

//预览文件
export const openDocFile = (url, fileType='pdf') => {
    uni.showLoading({title: '加载中...', mask: true})
    uni.downloadFile({
        url: url,
        success: function (res) {
            uni.openDocument({
                filePath: res.tempFilePath,
                fileType: fileType,
                showMenu: true,
            })
        },
        complete: function () {
            uni.hideLoading()
        }
    });
}
