import { getToken } from './auth';

// 定义类型接口
interface VipOptions {
    vipReviewStatus: string;
    vipEndDate: string;
    vipLevelName: string;
    vipLevel: number;
}

interface VipResult {
    isVip: boolean;
    text: string;
    level?: number;
}

interface StoreModule {
    dispatch: (action: string, payload?: any) => Promise<any>;
    state: any;
}

interface LocationResult {
    name: string;
    address: string;
    latitude: number;
    longitude: number;
}

/**
 * 显示消息提示框
 * @param content 提示的标题
 */
export function toast(content: string): void {
    uni.showToast({
        icon: 'none',
        title: content
    });
}

export function isChinese(text: string): boolean {
    const pattern = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
    return pattern.test(text);
}

/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content: string): Promise<UniApp.ShowModalRes> {
    return new Promise((resolve, reject) => {
        uni.showModal({
            title: '提示',
            content: content,
            cancelText: '取消',
            confirmText: '确定',
            success: function (res) {
                resolve(res);
            }
        });
    });
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params: Record<string, any>): string {
    let result = '';
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        const part = encodeURIComponent(propName) + '=';
        if (value !== null && value !== '' && typeof value !== 'undefined') {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
                        const params = propName + '[' + key + ']';
                        const subPart = encodeURIComponent(params) + '=';
                        result += subPart + encodeURIComponent(value[key]) + '&';
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + '&';
            }
        }
    }
    return result;
}

/**
 * 更新当前用户信息
 */
export const updateUserInfo = async (
    store: StoreModule, 
    storeType: string[] = ['user', 'cpy', 'cpyLi', 'vip', 'card']
): Promise<void> => {
    let res: any = null;
    if (storeType.includes('user')) {
        res = await store.dispatch('getUserInfoBytoken');
    }
    if (storeType.includes('cpy')) {
        res?.data?.currentCpyid && (await store.dispatch('cpyDetail', res?.data?.currentCpyid));

        res?.data?.currentCpyid && (await store.dispatch('memberAuditCount', res?.data?.currentCpyid));
    }
    if (storeType.includes('cpyLi')) {
        await store.dispatch('getMyCpyList');
    }
    if (storeType.includes('vip')) {
        // 判断是否申请过会员
        +store.state.cpy?.cpyInfo?.extraInfo?.vipApply && (await store.dispatch('vip/vipDetail'));
    }
    if (storeType.includes('card')) {
        // 获取当前名片信息
        await store.dispatch('getCurrentCard');
        
    }
};

// 判断是否是会员并且会员是否过期
export function isVip(options: VipOptions | null): VipResult {
    if (!options) {
        return {
            isVip: false,
            text: '非会员单位'
        };
    }
    const { vipReviewStatus, vipEndDate, vipLevelName, vipLevel } = options;
    if (vipReviewStatus !== '1') {
        return {
            isVip: false,
            text: '非会员单位'
        };
    } else {
        const now = new Date().getTime();
        const end = new Date(vipEndDate).getTime();
        if (now > end) {
            return {
                isVip: false,
                text: '非会员单位',
                level: vipLevel
            };
        } else {
            return {
                isVip: true,
                text: vipLevelName,
                level: vipLevel
            };
        }
    }
}

// 返回上一页失败返回首页
export function navigateBackOrHome(): void {
    const pages = getCurrentPages();
    if (pages.length === 1) {
        uni.switchTab({
            url: '/pages/plant/base/index'
        });
    } else {
        uni.navigateBack();
    }
}

// 提示uni.showToast
export function showToast(title: string): void {
    uni.showToast({
        icon: 'none',
        title
    });
}

// 保存图片临时路径
export function saveImagePath(url: string): void {
    uni.saveImageToPhotosAlbum({
        filePath: url,
        success: function () {
            uni.showToast({
                title: '保存成功',
                icon: 'success'
            });
        },
        fail: function () {
            uni.showToast({
                title: '保存失败',
                icon: 'none'
            });
        }
    });
}

// 分享图片临时路径
export function shareImagePath(url: string): void {
    uni.saveImageToPhotosAlbum({
        filePath: url,
        success: function () {
            uni.showToast({
                title: '分享成功',
                icon: 'success'
            });
        },
        fail: function () {
            uni.showToast({
                title: '分享失败',
                icon: 'none'
            });
        }
    });
}

// 根据截止时间计算剩余多少天 如果为负数则返回0
export function getRemainingDays(endTime: string | Date): number {
    const now = new Date().getTime();
    const end = new Date(endTime).getTime();
    const remainingTime = end - now;
    if (remainingTime < 0) {
        return 0;
    } else {
        return Math.floor(remainingTime / (1000 * 60 * 60 * 24));
    }
}

// 图片预览
export function uniPreviewImage(url: string): void {
    uni.previewImage({
        urls: [url],
        current: url
    });
}

export const emitBus = (bus: string, data: any = null): void => {
    uni.$emit(bus, data);
};

// 播放语音
export function playVoice(url: string): UniApp.InnerAudioContext {
    const audio = uni.createInnerAudioContext();
    audio.src = url;
    audio.onPlay(() => {
        console.log('开始播放');
    });
    audio.onError((res) => {
        console.log('播放失败', res);
    });
    return audio;
}

// 选择地址判断是否授权，如果授权则返回地址信息，否则引导授权	uni.chooseLocation
export function chooseAddress(): Promise<LocationResult> {
    return new Promise((resolve, reject) => {
        uni.chooseLocation({
            success: (res) => {
                resolve(res as LocationResult);
            },
            fail: (err) => {
                if (err.errMsg.includes('chooseLocation:fail auth deny')) {
                    uni.showModal({
                        title: '提示',
                        content: '请授权地理位置权限后再试',
                        showCancel: false,
                        success: () => {
                            // 引导用户去设置页面开启权限
                            uni.openSetting({
                                success: (settingRes) => {
                                    if (settingRes.authSetting['scope.userLocation']) {
                                        // 用户授权成功后再次调用选择地址
                                        uni.chooseLocation({
                                            success: (res) => {
                                                resolve(res as LocationResult);
                                            },
                                            fail: (err) => {
                                                reject(err);
                                            }
                                        });
                                    } else {
                                        reject(new Error('用户未授权地理位置权限'));
                                    }
                                }
                            });
                        }
                    });
                } else {
                    reject(err);
                }
            }
        });
    });
}

// 需要token跳转页面
export function navigateToWithToken(url: string): void {
    if (!getToken()) {
        uni.$u.route({
            type: 'reLaunch',
            url: '/pages/login/login',
            params: {
                redirect: encodeURIComponent(url)
            }
        });
        return;
    }
	uni.$u.route({
		type: 'navigateTo',
		url: url
	});
}
// 判断开启微信小程序权限功能，如果开启则返回true，否则先引导开启
export const isOpenSetting = async (scope?: string): Promise<boolean> => {
    // #ifdef MP-WEIXIN
    try {
        if (!scope || typeof scope !== 'string') {
            return true;
        }

        const hasAuth = await new Promise<boolean>((resolve) => {
            uni.getSetting({
                success: (res) => {
                    console.log(res, 'getSetting res');
                    resolve(!!(res.authSetting && (res.authSetting as any)[scope as string]));
                },
                fail: () => resolve(false)
            });
        });
        console.log(hasAuth, 'hasAuth');
        if (hasAuth) return true;

        const authorized = await new Promise<boolean>((resolve) => {
            uni.authorize({
                scope,
                success: () => resolve(true),
                fail: (res) => {
                    console.log(res);
                    
                    resolve(false)
                }
            });
        });
        console.log(authorized, 'authorized');
        
        if (authorized) return true;

        const goSetting = await new Promise<boolean>((resolve) => {
            uni.showModal({
                title: '提示',
                content: '请打开手机自身定位并且点击右上角三个点，进入设置，允许小程序获取定位,并选择您的位置。',
                confirmText: '去设置',
                success: (mRes: UniApp.ShowModalRes) => resolve(!!mRes.confirm),
                fail: () => resolve(false)
            });
        });
        if (!goSetting) return false;

        const finalAuth = await new Promise<boolean>((resolve) => {
            uni.openSetting({
                success: (setRes) => {
                    resolve(!!(setRes.authSetting && (setRes.authSetting as any)[scope as string]));
                },
                fail: () => resolve(false)
            });
        });
        return !!finalAuth;
    } catch (e) {
        return false;
    }
    // #endif

    // 非微信小程序平台默认返回可用
    return true;
}
// 根据传入url获取文件后缀名，根据文件后缀名返回相应的图片icon
export const getFileIconByUrl = (url: string) => {
    const fileExtension = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    const iconMap = {
        jpg: 'jpg',
        jpeg: 'jpg',
        png: 'png',
        gif: 'jpg',
        pdf: 'pdf',
        doc: 'doc',
        docx: 'doc',
        xls: 'xlsx',
        xlsx: 'xlsx',
        txt: 'txt',
        // 大写后缀映射
        JPG: 'jpg',
        JPEG: 'jpg',
        PNG: 'png',
        GIF: 'jpg',
        PDF: 'pdf',
        DOC: 'doc',
        DOCX: 'doc',
        XLS: 'xlsx',
        XLSX: 'xlsx',
        TXT: 'txt'
    };
    return `https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/file-type-sub/${iconMap?.[fileExtension] || 'def'}.png`; // 默认图标
};
// 获取节点信息方法
export const getRect = (selector: string, all: boolean = false): Promise<UniApp.NodesRef | UniApp.NodesRef[]> => {
    return new Promise((resolve, reject) => {
        const instance = getCurrentInstance();
        const query = uni.createSelectorQuery().in(instance);
        if (all) {
            query.selectAll(selector).boundingClientRect((res: any) => {
                if (res) {
                    resolve(res);
                } else {
                    reject('未找到节点信息');
                }
            }).exec();
        } else {
            query.select(selector).boundingClientRect((res: any) => {
                if (res) {
                    resolve(res);
                } else {
                    reject('未找到节点信息');
                }
            }).exec();
        }
    });
};

// 根据传入存放库房数组返回文字
export const getStorageRoomNames = (rooms: Array<{ warehouseName?: string, shelvesName?: string, shelfId?: string, warehouseId?: string }>): string => {
    if (!rooms || rooms.length === 0) {
        return '';
    }
    return rooms.map(room => (room.warehouseName || '') +  (room.shelvesName ? '-' : '') + (room.shelvesName || '')).join('，');
}