import BasePlatform from './BasePlatform';
import RequestManager from '@/common/request.js'
import { navigateTo } from '@/common/router'
import {
    sleep,
    parseQueryString
} from '@/common/util.js';
import {
    getOrderStatus
} from '@/common/server/order.js';
import {
    getPlatform
} from '../server/config';

class AppPlatform extends BasePlatform {
    constructor() {
        super();
        this.code = 'APP_ANDROID';
        this.env = 'app';
    }
    getPayData(url, data) {
        return data;
    }
    AppLaunch(options) {
        console.log("AppLaunch", options);

    }
    async appData() {
        this.getConfig().then(res => {
            console.log("AppLaunch", res);
            if (res.isCheck) {
                console.log("开启审核模式开启审核模式开启审核模式开启审核模式开启审核模式开启审核模式开启审核模式");
                uni.setTabBarItem({
                    index: 0,
                    visible: false,
                });
                uni.setTabBarItem({
                    index: 2,
                    text: "购物车"
                    // visible:false,
                });
                uni.setTabBarItem({
                    index: 3,
                    visible: false,
                });
                // uni.showTabBar({})
                uni.switchTab({
                    url: '/pages/mall/index'
                });
                // uni.tos
            } else {
                uni.setTabBarItem({
                    index: 0,
                    visible: true,
                });
                uni.setTabBarItem({
                    index: 3,
                    visible: true,
                });
                uni.switchTab({
                    url: '/pages/shouye/index'
                });
            }
        })
    }

    getOrderNo(event) {
        return new Promise((resolve, reject) => {
            resolve(null);
        });
    }

    pay({
        data
    }, event) {
        console.log(this, event);

        return new Promise(async (resolve, reject) => {
            let config = await this.getConfig();
            if (config.isWebPay) {

                console.log(data);
                let fullPath = event.$scope.$page.fullPath;
                //页面路径
                console.log(fullPath, "fullPath");

                let url = data.requestPay;
                let payPostData = data.data;
                payPostData['return_url'] = fullPath;
                let respay = await RequestManager.post(url, payPostData);
                if (respay.status === 1) {
                    console.log(respay);
                    plus.runtime.openURL(respay.data);
                    event.$refs.payDialog.showDialogHand("支付提示",
                        "支付成功后，请点击「支付已完成」按钮查看所购商品。如支付完成1分钟后仍显示异常，请关闭当前窗口，前往「我的」-「消费记录」查看订单状态。",
                        "支付已完成", "关闭", async () => {
                            let resPayStatus = await getOrderStatus(data.data['order_num']);
                            if (resPayStatus.data == 1) {
                                event.$refs.payDialog.closeHand();
                                resolve('success');
                            } else {
                                uni.showToast({
                                    title: resPayStatus.msg,
                                    icon: 'none',
                                    duration: 1000
                                });
                            }
                        });

                }
                return;
            }
            let orderInfo = data;
            console.log('orderInfo orderInfo orderInfo orderInfo ', orderInfo);
            let provider = "alipay";
            uni.requestPayment({
                provider,
                "orderInfo": orderInfo,
                success: res => {
                    // console.log(res)
                },
                fail: err => {

                },
                complete: res => {
                    console.log('complete (res)', res)
                    if (res.errMsg == 'requestPayment:fail cancel') {
                        uni.showToast({
                            title: '取消支付',
                            icon: 'none',
                            duration: 500,
                            success: () => {
                                /* 取消订单 */
                                resolve('cancel')
                            }
                        })


                    }
                    if (res.errMsg == 'requestPayment:ok') {
                        uni.showToast({
                            title: '支付成功',
                            icon: 'success',
                            duration: 500,
                            success: () => {
                                resolve('success')
                            }
                        })
                    }
                }
            })
        })
    }
    /**
     * 选择地址
     * @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'
                    })
                }
            })
        });
    }
    share({
        title,
        desc,
        image,
        url
    }) {
        console.log(`H5分享：${title} - ${desc}`);
        // 调用浏览器原生分享（如果可用）
        if (navigator.share) {
            return navigator.share({
                title,
                text: desc,
                url
            });
        }
        // 降级方案
        alert(`请手动分享：${url}`);
    }

    /**
     * 重写获取用户中心菜单列表，处理App特有的菜单需求
     * @returns {Array} 菜单项数组
     */
    getUserMenuList() {
        // 获取基础菜单列表
        const baseMenuList = super.getUserMenuList();
        let menuList = [];
        const customServiceMenu = {
            id: 13,
            show: true,
            title: '商品退换货',
            icon: 'my/huan.svg',
            path: '/pages/shouye/danye?advert=29',
            handler: this.navigateToPath.bind(this)
        };
        for (let i = 0; i < baseMenuList.length; i++) {
            let menu = baseMenuList[i];
            if (menu.id == 3) {
                if (!this.getIsCheck("user_menu_3")) {
                    menuList.push(menu);
                }
            } if (menu.id == 5) {
                if (!this.getIsCheck("user_menu_5")) {
                    menuList.push(menu);
                }
            } else {
                menuList.push(menu);
            }
            if (menu.title == "用户协议") {
                menuList.push(customServiceMenu);
            }
        }
        // 添加App特有的菜单项
        const appSpecificMenus = [{
            id: 12,
            show: true,
            title: '检查更新',
            icon: 'my/s11.png',
            path: '',
            handler: this.handleCheckUpdate.bind(this)
        }];
        // 返回合并后的菜单列表
        return menuList;
    }

    /**
     * 处理清除缓存
     */
    handleClearCache() {
        uni.showModal({
            title: '提示',
            content: '确定要清除缓存吗？',
            success: (res) => {
                if (res.confirm) {
                    // 清除除了登录信息外的缓存
                    const token = uni.getStorageSync('token');
                    const userinfo = uni.getStorageSync('userinfo');
                    uni.clearStorageSync();
                    uni.setStorageSync('token', token);
                    uni.setStorageSync('userinfo', userinfo);

                    uni.showToast({
                        title: '缓存已清除',
                        icon: 'success'
                    });
                }
            }
        });
    }

    /**
     * 处理检查更新
     */
    handleCheckUpdate() {
        // App特有的更新检查逻辑
        // #ifdef APP-PLUS
        plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
            const version = widgetInfo.version;

            uni.request({
                url: 'https://your-api-url/check-update',
                data: {
                    version: version,
                    platform: uni.getSystemInfoSync().platform
                },
                success: (res) => {
                    if (res.data && res.data.hasUpdate) {
                        uni.showModal({
                            title: '发现新版本',
                            content: res.data.updateDesc || '有新版本可用，是否立即更新？',
                            success: (modalRes) => {
                                if (modalRes.confirm) {
                                    // 打开下载页面或应用商店
                                    plus.runtime.openURL(res.data.downloadUrl);
                                }
                            }
                        });
                    } else {
                        uni.showToast({
                            title: '已是最新版本',
                            icon: 'none'
                        });
                    }
                }
            });
        });
        // #endif

        // 非APP环境下的处理
        // #ifndef APP-PLUS
        uni.showToast({
            title: '当前已是最新版本',
            icon: 'none'
        });
        // #endif
    }
    handleLogout() {
        var that = this;
        uni.showModal({
            title: '提示',
            content: '确定要退出登录吗？',
            success: (res) => {
                if (res.confirm) {
                    uni.removeStorageSync('token');
                    uni.removeStorageSync('userinfo');
                    that.getConfig().then(res => {
                        console.log("AppLaunch", res);
                        if (!res.isCheck) {
                            uni.switchTab({
                                url: '/pages/shouye/index'
                            });
                        } else {
                            uni.switchTab({
                                url: '/pages/mall/index'
                            });
                        }
                    });
                    // window.location.href = window.location.href;
                }
            }
        });
    }
    getUserAgreement() {
        navigateTo('/pages/guize/guize', { type: 30 })
    }
    getPrivacyAgreement() {
        navigateTo('/pages/guize/guize', { type: 31 })
    }
}
export default AppPlatform;