//app.js
const ald = require('./utils/ald-stat.js')
import WxAuthor from './utils/WxAuthor'
require('./utils/push_sdk.js')

App({
    onLaunch: function () {
        // if (__devtoolsConfig.network.request.indexOf('https://plog.xiaoshentui.com') !== -1) {
        //   wx.showModal({
        //     title: '小神推提示',
        //     content: '配置成功,请进行下一步',
        //   })
        // } else {
        //   wx.showModal({
        //     title: '小神推提示',
        //     content: '配置失败,请核查',
        //   })
        // }
        
        // 用户版本更新
        if (wx.canIUse("getUpdateManager")) {
            let updateManager = wx.getUpdateManager();
            updateManager.onCheckForUpdate((res) => {
                // 请求完新版本信息的回调
                console.log(res.hasUpdate);
            })
            updateManager.onUpdateReady(() => {
                wx.showModal({
                    title: '更新提示',
                    content: '新版本已经准备好，是否重启应用？',
                    success: (res) => {
                        if (res.confirm) {
                            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                            updateManager.applyUpdate();
                        } else if (res.cancel) {
                            return false;
                        }
                    }
                })
            })
            updateManager.onUpdateFailed(() => {
                // 新的版本下载失败
                wx.hideLoading();
                wx.showModal({
                    title: '升级失败',
                    content: '新版本下载失败，请检查网络！',
                    showCancel: false
                });
            });
        }

        // 登录
        let self = this;
        this.mWxAuthor = new WxAuthor(self, true)
        const dirs = ['addAddress', 'address', 'myhome', 'confirmOrder', 'confirmVOrder',
            'order_tabs', 'orderPaySn', 'person', 'postageDetail', 'postageManage', 'shopCart'
        ];

        let pages = new Set()
        dirs.forEach(dir => {
            let page = `/pages/${dir}/${dir}`
            pages.add(page)
        });
        this.globalData.authPages = pages
    },
    globalData: {
        fMinistart: false,
        userId: {
            openid: '',
            unionid: '',
            timeStamp: 0
        },
        userInfo: null,
        defaultAddress: null,
        fcodeErr: '',
        backLogin: false,
        arrayTree: [],
        fromSource: '',
        channel: '欧耶商城',
        record: null,
        card_type: '',
        authPages: null,
        mWxAuthor: null,
        member_id: 0,
        hasmobile: false,
        relay_id: 0,
        channel_num: 0,
        share_title:'',
        share_image:''
    },

    setFromSource(fromSource) {
        this.globalData.fromSource = fromSource
    },
    checkDefaultAddress(address) {
        this.globalData.defaultAddress = address
    },
    clearAddress() {
        this.globalData.defaultAddress = null
    },
    setArrayTree(tree) {
        this.globalData.arrayTree = tree
    },
    setCardType(card_type) {
        this.globalData.card_type = card_type
    },
    showToast(title, icon, duration) {
        wx.showToast({
            icon: icon || 'none',
            title,
            duration: 2000 || duration
        })
    },
    trim(str) {
        str = str.replace(/\s+/g, "")
        return str
    },
    checkCurrentRecord(record) {
        this.globalData.record = record
    },
    clearRecord() {
        this.globalData.record = null
    },
    navigateback() {
        if (getCurrentPages().length <= 1) {
            wx.reLaunch({ url: "/pages/home/home" })
        }
        else {
            wx.navigateBack()
        }
    },
    navigateto(page) {
        if (!this.globalData.userInfo) {
            this.globalData.authPages.forEach(prefix => {
                if (page.indexOf(prefix) == 0) {
                    wx.navigateTo({
                        url: '/pages/auth/auth',
                    })
                    return;
                }
            });
        }

        wx.navigateTo({
            url: page,
        })
    },
    switchtab(page) {
        if (!this.globalData.userInfo) {
            this.globalData.authPages.forEach(prefix => {
                if (page.indexOf(prefix) == 0) {
                    wx.navigateTo({
                        url: '/pages/auth/auth',
                    })
                    return;
                }
            });
        }

        wx.switchTab({
            url: page,
        })
    },
    getValueByKey(key = '', data = []) {
        if (!data.length) return {}
        return data.filter(val => val.card_type === key)[0] || {}
    },
    relogin() {
        this.mWxAuthor.init(true);
    },
    cardShareInfo() {
        console.log('index cardShareInfo')
        let userid = this.globalData.member_id
        let imageUrl = this.globalData.share_image ? this.globalData.share_image : '/image/xyzshare.png'

        let share_path = `/pages/index/index?relay_id=${userid}`
        console.log('share path:', share_path)

        let def = '我正在充值，麻烦帮我授权一下，100元能省5元哦！拜托拜托~'
        let title = this.globalData.share_title ? this.globalData.share_title : def
        console.log('share_title', title, this.globalData.share_title, 'share_image', imageUrl, this.globalData.share_image)
        
        return {
            title: title,
            path: share_path,
            imageUrl: imageUrl,
        }
    },
    isNullObject(obj) {
        return (Object.keys(obj).length === 0);
    },
    writePhotosAlbum(callback) {
        wx.showLoading({
            title: '加载中'
        });
        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success() {
                            wx.hideLoading();
                            if (callback) callback();
                        }
                    })
                }
                else {
                    wx.hideLoading();
                    if (callback) callback();
                }
            }
        })
    },
    randint(low, high) {
        let result = low + Math.round(Math.random() * (high - low));
        return result;
    },
    getUrl() {
        let len = getCurrentPages().length
        if (len < 1) return ''

        let currentPage = getCurrentPages()[len - 1]
        let params = ''
        if (currentPage.options) {
            for (let k in currentPage.options) {
                params = params + k + '=' + currentPage.options[k] + '&'
            }
            params = params.slice(0, params.length - 1)
        }
        let current_url = "/" + currentPage['route']
        if (params) {
            current_url = current_url + '?' + params
        }
        return current_url
    },
    genMsgs() {
        let length = 200;
        let numset = new Set();
        for (let index = 0; index < length; index++) {
            let num = this.randint(0, 9999);
            numset.add(num);
        }

        let dis_phone = [5, 10, 15, 20, 25];
        let dis_oil = [5, 10, 25, 30, 45, 50];
        let msgs = new Array();

        let nums = Array.from(numset)
        for (let index in nums) {
            let num = nums[index];
            let str = '' + num;
            if (str.length == 3) {
                str = '0' + str;
            }
            else if (str.length == 2) {
                str = '00' + str;
            }
            else if (str.length == 1) {
                str = '000' + str;
            }
            else if (str.length == 4) {
                str = str;
            }
            else {
                continue;
            }

            let stype = '';
            let discount = 0;
            let type = this.randint(0, 1);
            if (type == 0) {
                stype = "油卡充值";
                let dis = this.randint(0, dis_oil.length - 1);
                discount = dis_oil[dis];
            }
            else {
                stype = "话费充值";
                let dis = this.randint(0, dis_phone.length - 1);
                discount = dis_phone[dis];
            }
            msgs.push({ phone: str, type: stype, discount: discount });
        }
        return msgs;
    },
    showLoading() {
        wx.showLoading({
            title: '加载中'
        });
    },
    hideLoading() {
        wx.hideLoading();
    }
})