import config from './config.js'

let util = {
  formatTime(times = new Date().getTime() / 1000, format = 'yyyy/MM/dd hh:mm:ss') {
    const date = new Date(times * 1000)
    const reg = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    const year = date.getFullYear()
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, `${year}`.substr(4 - RegExp.$1.length))
    }
    for (let k in reg) {
      if (new RegExp(`(${k})`).test(format)) {
        format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? reg[k] : (`00${reg[k]}`.substr(`${reg[k]}`.length)))
      }
    }

    return format
  },

  fastClickTips () {
    wx.showToast({
      title: '不要频繁操作,请稍后再试',
      icon: 'none'
    })
    // setTimeout(() => {
    //   wx.hideToast()
    // }, 500)
  },

  routeTo(url) {
    wx.navigateTo({
      url: url,
      success: function() {},
      fail: function() {}
    })
  },

  ajax(options) {
    if (options.data && options.data.HideLoading) {
      delete options.data.HideLoading
    } else if (options.url !== '/mp/wx/getuserinfo') {
      wx.showLoading({
        mask: true,
        title: '加载中',
      })
    }

    let hideToast = false
    if (options.data && options.data.HideToast) {
      hideToast = true
      delete options.data.HideToast
    }

    options.data = {
      ...options.data,
      app_id: config.baseParams.app_id,
      client_id: '',
      format: 'json',
      ...config.gameParams,
      ...config.agentParams,
      ...config.deviceParams,
      ts: parseInt(new Date().getTime() / 1000),
      token: wx.getStorageSync('userInfo').user_token || '',
      sign: ''
    }
    options.header = {
      'BOX_USER_AGENT': 'miniProgram'
    }
    if (options.method) {
      options.method = options.method.toUpperCase()
      if (options.method === 'POST') {
        options.header['Content-Type'] = 'application/x-www-form-urlencoded'
      }
    }
    if (options.mini) {
      options.url = config.miniUrl + options.url
      delete options.mini
    } else {
      options.url = config.baseUrl + options.url
    }

    return new Promise((resolve, reject) => {
      wx.request({
        ...options,
        success(res) {
          console.log(options.url, options.data, res)
          wx.hideLoading()
          if (res.statusCode === 200) {
            if (res.data.code === undefined || res.data.code === 200) {
              resolve(res.data)
            } else {
              if (options.url !== '/mp/wx/getuserinfo' &&
                 res.data.code !== 1002 && 
                options.url.indexOf('/favorite/reward/get') == -1 && !hideToast) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
              if (res.data.code === 1002) {
                // console.log('登陆过期正在重新登陆...')
                getApp().againLogin()
                getApp().globalData.againLogin = true
              } else {
                console.log(`${options.url} 请求出错,错误码${res.data.code}`)
              }
              reject(res)
            }
          } else {
            if (!hideToast) {
              wx.showToast({
                title: '网络异常,请重试',
                icon: 'none'
              })
            }
            reject(res)
          }
        },
        fail(res) {
          console.log(options.url, options.data, res)
          wx.hideLoading()
          if (!hideToast) {
            wx.showToast({
              title: '网络异常,请重试',
              icon: 'none'
            })
          }
          reject(res)
        }
      })
    })
  },

  getImageInfo(url) {
    return new Promise((resolve, reject) => {
      if (!url) {
        resolve({
          path: '/image/img_avatar_default.png'
        })
      } else {
        wx.getImageInfo({
          src: url,
          success: function (res) {
            resolve(res)
          },
          fail: function (res) {
            resolve({
              path: '/image/img_avatar_default.png'
            })
          }
        })
      }
    })
  }
}

module.exports = util