//app.js
import WxAuthor from './utils/WxAuthor'

App({
    onLaunch: function() {

        // 用户版本更新
      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
    },

    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
    },
    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 = '/image/xyzshare.png'
        let share_path = `/pages/index/index?relay_id=${userid}`
        console.log('share path:', share_path)
        
        return {
            title: '移动、联通、电信、中石油、中石化，首充95折，即刻到账',
            path: share_path,
            imageUrl: imageUrl,
        }
    },
    isNullObject(obj) {
        return (Object.keys(obj).length === 0);
    }
})