//app.js
App({
    onShow() {
        console.log('app-onshow');
        const self = this;
        // 查看是否授权
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userInfo']) {
                    console.log('授权过到首页');
                    self.globalData.isLogin = true;
                    wx.setStorageSync('isLogin', true)
                    // wx.redirectTo({
                    // url: '/pages/index/index', //跳转到首页
                    // });
                } else {
                    console.log('授权失效到授权页');
                    self.globalData.isLogin = false;
                    wx.navigateTo({
                        url: '/pages/my/my', //跳转到授权页面
                    })
                }
            }
        })
    },
    onLaunch: function () {
        console.log('app-onLaunch');
        // 展示本地存储能力
        // var logs = wx.getStorageSync('logs') || []
        // logs.unshift(Date.now())
        // wx.setStorageSync('logs', logs)


        // 获取用户信息
    },
    getLogin() {
        const self = this;

        return new Promise(function (resolve, reject) {
            wx.getUserInfo({
                success: function (user) {
                    // console.log(user);
                    // 登录
                    let url = '/portal/Login/getToken';
                    wx.login({
                        success: function (res) {
                            if (self.loginCallback) {
                                console.log('onlaunch-callback');
                                self.loginCallback(user)
                            }
                            console.log('获取code', res);
                            self.post(url, {
                                code: res.code,
                                user_nickname: user.userInfo.nickName,
                                avatar: user.userInfo.avatarUrl
                            }, {}).then((ret) => {
                                console.log('获取token', ret);
                                wx.setStorageSync('token', ret.data.token);
                                self.globalData.userInfo = user.userInfo;
                                resolve(ret.data);
                                // setTimeout(function () {
                                //     wx.navigateBack({delta: 1})
                                // }, 200)
                            })
                        },
                        fail: function (res) {
                        },
                        complete: function (res) {
                        },
                    });
                }
            });

        })
    },
    post: function (url, data, headerParams) {
        /**
         * 自定义post函数,返回Promise
         * +-------------------
         * @param {String}      url 接口网址
         * @param {arrayObject} data 要传的数组对象 like: {name: 'name', age: 32}
         * +-------------------
         * @return {Promise}    promise 返回promise供后续操作
         */
        // wx.showLoading({
        //   title: '加载中',
        // })
        wx.showNavigationBarLoading()
        // wx.showToast({
        //     title: '加载中',
        //     icon:'none',
        // })
        var promise = new Promise((resolve, reject) => {
            //init
            let that = this;
            let postData = data;
            let baseUrl = 'http://wmatchrd.com/api';
            //网络请求
            let header = {
                'content-type': 'application/x-www-form-urlencoded'
            }
            header = Object.assign(header, headerParams)
            wx.request({
                url: baseUrl + url,
                data: postData,
                method: 'POST',
                header: header,
                success: function (res) {//返回取得的数据
                    // console.log('返回取得的数据res', res);
                    if (+res.data.code == 1) {
                        resolve(res.data);
                    } else if (res.data.code == '20000') {
                        console.log('20000');
                        resolve(res.data.data);
                    } else if (res.data.data.code == '10001') {  //未获取授权
                        console.log('10001');
                        wx.showModal({
                            title: '提示',
                            content: res.data.data.msg,
                            showCancel: false,
                            success: function (res) {
                                if (res.confirm) {
                                    // wx.removeStorageSync('token');
                                    wx.navigateTo({
                                        url: '/pages/index/index',
                                    })
                                }
                            }
                        });
                        resolve(res.data.data);
                    } else if (+res.data.code === 0) {
                        console.log('code=0');
                        console.log(res.data);
                        wx.showModal({
                            title: '提示',
                            content: res.data.message,
                            showCancel: false,
                        });
                        resolve(res.data);
                        reject(res.data)
                    }
                    setTimeout(function () {
                        // wx.hideLoading()
                        // wx.hideToast()
                        wx.hideNavigationBarLoading()
                    }, 500)
                },
                error: function (e) {
                    reject('网络出错');
                    // wx.hideLoading()
                    wx.hideNavigationBarLoading()
                }
            })
        });
        return promise;
    },
    //获取当前日期
    nowDate() {
        let date = new Date();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        // let hours = date.getHours();
        // let minutes = date.getMinutes();
        let Y = date.getFullYear() + '-' + (month > 9 ? month : ('0' + month)) + '-' + (day > 9 ? day : ('0' + day));
        // let H = (hours>9?hours:('0'+hours)) + ':' +(minutes>9?minutes:('0'+minutes));
        let time = [];
        time.push(Y);
        // let new_time = time.join(' ');
        return time;
    },
    //获取当前时间(时分)
    nowTime() {
        let date = new Date();
        let hours = date.getHours();
        let minutes = date.getMinutes();
        let H = (hours > 9 ? hours : ('0' + hours)) + ':' + (minutes > 9 ? minutes : ('0' + minutes));
        // let time = [];
        // time.push(H);
        console.log('time', H);
        // let new_time = time.join(' ');
        return H;
    },
    //获取截止时间的前几个小时
    preTime(over_time,n) {
        var nowDate = new Date(over_time),
            nowDate = nowDate.setHours(nowDate.getHours() - n),
            nowDate = new Date(nowDate),
            y = nowDate.getFullYear(),
            m = nowDate.getMonth() + 1,
            d = nowDate.getDate(),
            h = nowDate.getHours(),
            mi = nowDate.getMinutes();
        console.log('nowDate',nowDate,new Date(over_time))
        m = m < 10 ? '0' + m : m;
        d = d < 10 ? '0' + d : d;
        h = h < 10 ? '0' + h : h;
        mi = mi < 10 ? '0' + mi : mi;
        console.log('截止时间',y,over_time, m, d, h,mi);
        // return y + over_time + m + over_time + d + ' ' + h + ':' + mi;
        return y + '-' + m + '-' + d + ' ' + h + ':' + mi;
    },
    timeFormat(param) { //小于10的格式化函数
        return param < 10 ? '0' + param : param;
    },
    //秒数转成天时分秒
    initTime(value) {
        let secondTime = value;// 秒
        let minuteTime = 0;// 分
        let hourTime = 0;// 小时
        let dayTime = 0;// 天
        if (secondTime > 60) {  //如果秒数大于60,将秒数转换成整数
            //获取分钟,除以60取整数,得到整数分钟
            minuteTime = parseInt(secondTime / 60);
            //获取秒数,秒数取佘,得到整数秒数
            secondTime = parseInt(secondTime % 60);
            //如果分钟大于60,将分钟转换成小时
            if (minuteTime > 60) {
                //获取小时,获取分钟除以60,得到整数小时
                hourTime = parseInt(minuteTime / 60);
                //获取小时后取佘的分,获取分钟除以60取佘的分
                minuteTime = parseInt(minuteTime % 60);
                //如果小时大于24,将小时转换成天
                if (hourTime > 24) {
                    dayTime = parseInt(hourTime / 24);
                    hourTime = parseInt(hourTime % 24); //算出有多分钟
                }
            }
        }
        let result = [];
        let obj = null;
        obj = {
            day: this.timeFormat(dayTime),
            hou: this.timeFormat(hourTime),
            min: this.timeFormat(minuteTime),
            sec: this.timeFormat(secondTime)
        };
        result.push(obj);
        // console.log('result', result);
        return result;
    },
    globalData: {
        userInfo: null,
        isLogin: null
    }
});