import BasePlatform from './BasePlatform';
import H5Platform from './H5Platform';
import { webAppPay, webAppShare } from '@/common/webapp.js'
import { parseQueryString } from '@/common/util'

function versionToNumber(versionString) {
    // 移除所有点号并转换为数字
    return parseInt(versionString.split('.').join(''), 10);
}
class NewWebAppPlatform extends H5Platform {
    constructor() {
        super();
        this.code = 'WEB_APP_ANDROID';
        this.env = 'web_app';
        this.app_version = 100;
        this.app_os = null;

        let location = window.location.href;
        const params = parseQueryString(location);
        if (params['version'] != null) {
            uni.setStorageSync('app_version', params['version']);
            let _appversion = params['version'] ?? "1.0.0";
            if (_appversion.indexOf(".") > -1) {
                _appversion = versionToNumber(_appversion);
                this.app_version = _appversion;
            }

        }
        if (params['os'] != null) {
            let app_os = params['os'];
            uni.setStorageSync('app_os', app_os);
            this.app_os = app_os;
        }
        if (this.app_os == null) {


            if (uni.getStorageSync('app_version') != null) {
                let _appversion = uni.getStorageSync('app_version') ?? "1.0.0";
                if (_appversion.indexOf(".") > -1) {
                    _appversion = versionToNumber(_appversion);
                    this.app_version = _appversion;
                }

            }
            if (uni.getStorageSync('app_os') != null) {
                this.app_os = uni.getStorageSync('app_os');
            }
            console.log('加载数据', uni.getStorageSync('app_version'), uni.getStorageSync('app_os'));
        }

    }
    share({ title, desc, image, url }) {
        console.log(`APP分享：${title} - ${desc} - ${image} - ${url}`);
        if (this.app_version == 100) {
            uni.setClipboardData({
                data: url
            });
            this.$c.msg("链接已复制，快去分享吧~");
            return;
        }
        return webAppShare(title, desc, image, url);
        // 降级方案
        // alert(`请手动分享：${url}`);
    }
    pay({
        data
    }, event) {
        console.log(this, event);
        return new Promise(async (resolve, reject) => {
            const res = await webAppPay(data);
            if (!res) {
                uni.showToast({
                    title: '取消支付',
                    icon: 'none',
                    duration: 500,
                    success: () => {
                        /* 取消订单 */
                        resolve('cancel')
                    }
                });
                return;
            }
            uni.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 500,
                success: () => {
                    resolve('success')
                }
            })
        });
    }
    downloadFile(url) {
        return new Promise((resolve, reject) => {
            try {
                // 创建一个隐藏的a标签
                const a = document.createElement('a');
                a.href = url;
                a.download = url.split('/').pop() || 'download'; // 使用URL中的文件名或默认名称
                a.style.display = 'none';
                document.body.appendChild(a);
                a.click(); // 触发下载
                document.body.removeChild(a); // 清理DOM
                resolve({ success: true });
            } catch (error) {
                console.error('下载失败:', error);
                // 降级方案，直接打开
                window.location.href = url;
                resolve({ success: false, error: error.message });
            }
        });
    }
    /**
     * 重写获取用户中心菜单列表，添加微信小程序特有菜单
     * @returns {Array} 菜单项数组
     */
    getUserMenuList() {
        // 获取基础菜单列表
        const baseMenuList = super.getUserMenuList();

        // 添加客服菜单项（仅微信小程序）


        // 将客服菜单插入到第二个位置
        return [...baseMenuList.slice(0, baseMenuList.length - 1), ...baseMenuList.slice(baseMenuList.length - 1)];
    }
    getVersion() {
        return uni.getStorageSync('version') == '' ? '1.0.0' : uni.getStorageSync('version');
    }

    /**
 * 获取功能权限
 */
    getPermission(functionName) {
        const appPermission = {
            wxLogin: 101
        };
        let _functionVersion = appPermission[functionName];
        if (_functionVersion != null) {
            //如果当前app权限大于等于功能权限版本，则返回true
            console.log('验证功能权限' + functionName, "功能要求版本：" + _functionVersion, "当前app版本：" + this.app_version, "当前功能是否满足：" + (this.app_version >= _functionVersion));
            return this.app_version >= _functionVersion;
        }
        return false;
    }
}
export default NewWebAppPlatform;