var api = require('../config/api.js');


function formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()


    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

const gotoLogin = (function gotoLogin() {
    let time = Date.now()
    return () => {
        getApp().setLoginProps(false)

        // if (Date.now() - time > 1000) {
        //     let pages = getCurrentPages()
        //     if (pages[pages.length - 1].route === 'pages/auth/btnAuth/btnAuth') return;
        //     wx.setStorageSync('isLogin', false)
        //     wx.navigateTo({
        //         url: '/pages/auth/btnAuth/btnAuth',
        //     })
        // }
    }
})();

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "POST", header = "application/x-www-form-urlencoded") {
  
//   if (!~url.indexOf('/api/cart/update') && !~url.indexOf('/api/cart/index')){
//     wx.showLoading({
//       title: '加载中...',
//     });
//   }
    return new Promise(function (resolve, reject) {
        wx.request({
            url: url,
            data: data,
            method: method,
            header: {
                'Content-Type': header,
                'X-Nideshop-Token': wx.getStorageSync('token')
            },
            success: function (res) {
                // wx.hideLoading();
                if (res.statusCode == 200) {

                    let pages = getCurrentPages()
                    let currPage = pages[pages.length - 1].route
                    let notLogins = ['pages/index/index', 'pages/catalog/catalog', 'pages/category/category', 'pages/ucenter/index/index']
                    if (res.data.errno == 401 && !~notLogins.indexOf(currPage)) {
                        gotoLogin()
                    } else {
                        const jx = (data) => {
                            for (let key in data) {
                                if (data[key] instanceof Object) {
                                    jx(data[key])
                                } else if (key === 'list_pic_url') {
                                    data[key] = data[key] && data[key].split('#$#')[0]
                                    console.error(`${key}: ${data[key]}`, data)
                                }
                            }
                        }
                        jx(res.data)
                        resolve(res.data);
                    }

                    
                    if (url === api.UserInfo) {
                        let info = wx.getStorageSync('userInfo')
                        info.isAdmin = res.data.data.isAdmin
                        wx.setStorageSync('userInfo', info);
                    }
                    
                } else {
                    reject(res.errMsg);
                }

            },
            fail: function (err) {
                reject(err)
            },
            complete:function (res){
                wx.stopPullDownRefresh()
                wx.hideLoading();
            }
        })
    });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
    return new Promise(function (resolve, reject) {
        wx.checkSession({
            success: function () {
                resolve(true);
            },
            fail: function () {
                reject(false);
            }
        })
    });
}

/**
 * 调用微信登录
 */
function login() {
    return new Promise(function (resolve, reject) {
        wx.login({
            success: function (res) {
                if (res.code) {
                    resolve(res);
                } else {
                    reject(res);
                }
            },
            fail: function (err) {
                reject(err);
            }
        });
    });
}

function redirect(url) {

    //判断页面是否需要登录
    if (false) {
        wx.redirectTo({
            url: '/pages/auth/login/login'
        });
        return false;
    } else {
        wx.redirectTo({
            url: url
        });
    }
}

function showErrorToast(msg, cb) {
    wx.showToast({
        title: msg,
        image: '/static/images/icon_error.png',
        success: cb
    })
}

function showSuccessToast(msg) {
    wx.showToast({
        title: msg,
    })
}

const imgServer = 'https://4d-tjw.oss-cn-shenzhen.aliyuncs.com/wxmall/images'


function checkNetStatu() {
    var statu = true
    return new Promise(r => {
        wx.getNetworkType({
            success: function (res) {
                var networkType = res.networkType // 返回网络类型2g，3g，4g，wifi, none, unknown
                if (networkType == "none") {
                    //没有网络连接
                    statu = false
                } else if (networkType == "unknown") {
                    //未知的网络类型
                    statu = false
                }
                r(statu)
            }
        })
    })
  }

module.exports = {
    formatTime,
    request,
    redirect,
    showErrorToast,
    showSuccessToast,
    checkSession,
    login,
    imgServer,
    checkNetStatu
}


