import BasePlatform from './BasePlatform';
import eruda from 'eruda';
import { parseQueryString } from '@/common/util';



class H5Platform extends BasePlatform {
    constructor() {
        super();
        this.code = 'WEB_H5';
        this.env = 'h5';
        // 简单初始化
        let erudaInstance = uni.getStorageSync("erudaInstance");
        if (erudaInstance != null && erudaInstance != "") {
            this.startDeb();
        }

        // eruda.init();
    }
    getPayData(url, data) {
        data['quitUrl'] = escape(window.location.href);
        data['returnUrl'] = escape(window.location.href);
        console.log('处理数据', data);
        return data;
    }
    pay({
        data
    }, event) {
        console.log('支付1111');

        return new Promise((resolve) => {
            console.log(data);
            // 检查是否已存在同ID的表单，如果存在则先删除
            const existingForm = document.getElementById('alipaysubmit');
            if (existingForm) {
                existingForm.parentNode.removeChild(existingForm);
            }

            // 创建一个临时div元素
            const tempDiv = document.createElement('div');
            // 将data作为HTML插入到div中（假设data是表单的HTML字符串）
            tempDiv.innerHTML = data;
            // 将表单添加到body中
            document.body.appendChild(tempDiv.firstChild);
            // 获取表单并提交
            const form = document.getElementById('alipaysubmit');
            if (form) {
                form.submit();
                resolve({
                    success: true
                });
            } else {
                resolve({
                    success: false,
                    message: '表单创建失败'
                });
            }
        });
    }

    share({
        title,
        desc,
        image,
        url
    }) {
        console.log(`H5分享：${title} - ${desc}`);
        // 调用浏览器原生分享（如果可用）
        if (navigator.share) {
            return navigator.share({
                title,
                text: desc,
                url
            });
        }
        // 降级方案
        alert(`请手动分享：${url}`);
    }

    /**
     * 选择地址
     * @returns 
     */
    chooseAddress() {
        return new Promise((resolve, reject) => {
            uni.navigateTo({
                url: '/pages/other/choose_address',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    selectAddress: function (data) {
                        console.log(data, {
                            userName: data.address.receiver_name,
                            telNumber: data.address.receiver_phone,
                            detailed_address: data.address.detailed_address
                        })
                        resolve({
                            userName: data.address.receiver_name,
                            telNumber: data.address.receiver_phone,
                            detailed_address: data.address.detailed_address
                        });
                    },
                    someEvent: function (data) {
                        console.log(data)
                    }

                },
                success: function (res) {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        data: 'data from starter page'
                    })
                }
            })
        });
    }
    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
                });
            }
        });
    }
    AppLaunch(options) {
        console.log("AppLaunch", options);
        if (options.query) {
            let query = options.query;
            if (query['version'] != null) {
                uni.setStorageSync('version', query['version']);
            }
            if (query['method'] != null && query['method'] == "alipay.trade.wap.pay.return" && query[
                'out_trade_no'] != null) {
                //支付宝跳转过来的
                //重定向url
                let url = window.location.origin + window.location.pathname;
                let out_trade_no = query['out_trade_no'];
                uni.setStorageSync('pay_order_num', out_trade_no);
                // alert('存入订单编号' + out_trade_no)
                const delKey = ['charset', 'out_trade_no', 'method', 'total_amount', 'sign', 'trade_no',
                    'auth_app_id', 'version', 'app_id', 'sign_type', 'seller_id', 'timestamp'
                ];
                for (const key of delKey) {
                    delete query[key];
                }
                let str = Object.entries(query)
                    .map(([key, value]) => `${key}=${value}`)
                    .join('&')
                if (str != '') {
                    url += "?" + str;
                }
                console.log('支付成功，重定向页面。', url);
                window.location.href = url;
            }
        }
      
        // if (window.location.pathname == "/" || window.location.pathname == "/pages/index/index") {
        //     uni.switchTab({
        //         url: '/pages/shouye/index'
        //     });
        // }
    }
    getOrderNo(event) {
        return new Promise((resolve, reject) => {
            //window.location.search
            let query = parseQueryString(window.location.search);
            if (query['method'] != null && query['method'] == "alipay.trade.wap.pay.return" && query[
                'out_trade_no'] != null) {
                //表示还在支付请求中，还未开始重定向
                console.log('window.location.search', window.location.search);

                resolve(null);
                return;
            }
            let pay_order_num = uni.getStorageSync('pay_order_num');
            // alert("获取订单编号"+pay_order_num)
            setTimeout(() => {
                uni.removeStorageSync('pay_order_num');
            }, 2000)
            resolve(pay_order_num);
        });
    }

    /**
     * 重写获取用户中心菜单列表，处理H5特有的菜单需求
     * @returns {Array} 菜单项数组
     */
    getUserMenuList() {
        // 获取基础菜单列表
        const baseMenuList = super.getUserMenuList();

        // H5环境下可能需要修改某些菜单项的行为
        return baseMenuList.map(item => {
            // 示例：在H5环境下可能需要特殊处理某些菜单项
            if (item.id === 6) { // 加入福利群菜单
                return {
                    ...item,
                    // 重新绑定处理函数，可能需要增加H5特有的逻辑
                    handler: (menuItem, context) => {
                        this.handleJoinGroup(menuItem, context);
                        // 在H5环境下可能需要额外的处理，比如尝试复制群号等
                    }
                };
            }
            return item;
        });
    }

    /**
     * 开启调试
     */
    startDeb() {
        // 简单初始化
        window.erudaInstance = eruda.init();
        uni.setStorageSync("erudaInstance", true);
    }
    /**
     * 关闭调试
     */
    closeDeb() {
        if (window.erudaInstance) {
            // 完全销毁Eruda实例（从DOM中移除）
            window.erudaInstance.destroy();
        }
        uni.removeStorageSync("erudaInstance")
    }
    getVersion() {
        return '1.0.0';
    }
}
export default H5Platform;