import {BASEURL} from "./request.js";
import {useUserStore} from "../pinia/UserStore/index.js";

export const showToast = (options) => {
    if (typeof options === 'string') {
        uni.showToast({
            title: options, icon: 'none',
        }).then();
    } else {
        uni.showToast(options).then();
    }
}

export const isWXWeb = () => {
    const userAgent = navigator.userAgent;
    return userAgent.includes('MicroMessenger');
}

export const toPage = async (url) => {
    try {
        await uni.navigateTo({
            url: url,
        })
    } catch (e) {
        await uni.reLaunch({
            url: url,
        })
    }
}

export const clearObject = (obj) => {
    Object.keys(obj).forEach(key => {
        delete obj[key];
    });
};

export const backPage = (delta) => {
    uni.navigateBack({
        delta: delta || 1
    }).then();
}

export const copy = (context) => {
    // #ifndef APP-PLUS || MP-WEIXIN
    try {
        navigator.clipboard.writeText(context)
            .then(() => {
                showToast('已复制');
            })
            .catch((e) => {
                console.error(e);
                showToast('复制失败');
            });
    } catch (e) {
        showToast('复制失败');
    }
    // #endif
    // #ifdef APP-PLUS || MP-WEIXIN
    uni.setClipboardData({
        data: context, success: () => {
            showToast('已复制');
        }, fail: () => {
            showToast('复制失败');
        }
    })
    // #endif
}

export const isVideoFile = (filename) => {
    const videoExtensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm', '.mpeg', '.mpg', '.3gp'];
    const fileExtension = filename.slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2).toLowerCase();
    return videoExtensions.includes(`.${fileExtension}`);
}

export const download = (urls) => {
    uni.showLoading({
        title: '下载中'
    });
    // #ifndef APP-PLUS || MP-WEIXIN
    const promises1 = urls.map(url => new Promise((resolve, reject) => {
        const iframe = document.createElement('iframe');
        iframe.src = url;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        resolve(true);
    }));
    Promise.all(promises1).then(() => {
        showToast('保存成功');
        setTimeout(() => {
            uni.hideLoading();
        }, 1000);
    }).catch(() => {
        showToast('保存失败');
        setTimeout(() => {
            uni.hideLoading();
        }, 1000);
    });
    // #endif

    // #ifdef APP-PLUS
    const promises2 = urls.map(v => new Promise((resolve, reject) => {
        uni.downloadFile({
            url: v,
            success: () => {
                resolve(true);
            },
            fail: () => {
                reject(false);
            }
        })
    }));
    Promise.all(promises2).then(() => {
        showToast('保存成功');
        setTimeout(() => {
            uni.hideLoading();
        }, 1000);
    }).catch(() => {
        showToast('保存失败');
        setTimeout(() => {
            uni.hideLoading();
        }, 1000);
    });
    // #endif

    // #ifdef MP-WEIXIN
    const promises3 = urls.map(v => new Promise((resolve, reject) => {
        uni.downloadFile({
            url: v,
            success: ({tempFilePath}) => {
                const api = isVideoFile(tempFilePath) ? 'saveVideoToPhotosAlbum' : 'saveImageToPhotosAlbum';
                uni[api]({
                    filePath: tempFilePath,
                    success: () => {
                        resolve(true);
                    },
                    fail: (err) => {
                        console.log(err);
                        reject(false);
                    }
                })
            },
            fail: (err) => {
                console.log(err);
                reject(false);
            }
        })
    }));
    Promise.all(promises3).then(() => {
        showToast('保存成功');
        setTimeout(() => {
            uni.hideLoading();
        }, 1000);
    }).catch(() => {
        showToast('保存失败');
        setTimeout(() => {
            uni.hideLoading();
        }, 1000);
    });
    // #endif
}

export const numberToCharacter = (number) => {
    return ['一', '二', '三', '四', '五'][number];
}

export const toWXMiniApp = (id, task_children_id) => {
    const {token} = useUserStore();
    window.open(`weixin://dl/business/?appid=${import.meta.env.VITE_APP_ID}&path=pages/index/index&env_version=${import.meta.env.VITE_APP_VERSION}&query=${encodeURIComponent(`id=${id}&task_children_id=${task_children_id}&token=${token}`)}`);
}

export const uploadFile = ({count}) => {
    const UserStore = useUserStore();
    return new Promise((resolve, reject) => {
        uni.chooseFile({
            count: count,
            success: ({tempFilePaths}) => {
                const all = tempFilePaths.map(v => new Promise((res, rej) => {
                    uni.uploadFile({
                        url: BASEURL + '/upload/upload',
                        filePath: v,
                        name: "file",
                        header: {
                            token: UserStore.token
                        },
                        success: ({data}) => {
                            res(JSON.parse(data));
                        },
                        fail: (err) => {
                            showToast(err.errMsg);
                            rej(err);
                        }
                    });
                }));
                Promise.all(all).then((res) => {
                    resolve(res);
                }).catch(err => {
                    reject(err);
                })
            },
            fail: (err) => {
                showToast(err.errMsg);
                reject(err);
            }
        });
    });
}

export const verifyForm = (model, rules) => {
    Object.entries(model).forEach(([key, value]) => {
        console.log(rules[key], key, value)
        if (rules[key]) {
            if (rules[key].required && !value) {
                showToast({
                    icon: 'error',
                    mask: true,
                    title: `${rules[key].title}不能为空`,
                });
                throw new Error(rules[key].msg);
            }
            if (rules[key].reg) {
                if (!rules[key].reg.test(value)) {
                    showToast({
                        icon: 'error',
                        mask: true,
                        title: rules[key].msg,
                    });
                    throw new Error(rules[key].msg);
                }
            }
        }
    });
}
