export let api_url = null
export function get(url, params, success = noop, fail = noop) {
  return http(url, 'GET', params, success, fail)
}

export function post(url, params, success = noop, fail = noop) {
  return http(url, 'POST', params, success, fail)
}

function noop() {}

function http(url, method, params, success, fail) {
  // const type = wx.getStorageSync('env') || 'dev' // 测试环境
  const type = wx.getStorageSync('env') || 'ijolijoli' // 正式环境
  switch (type) {
    case 'dev':
      api_url = 'https://test-api.ijolijoli.com/'
      break
    default:
      api_url = 'https://api.ijolijoli.com/'
      break
  }
  return new Promise ((resolve, reject) => {
    wx.request({
      url: `${api_url}${url}`,
      method: method,
      data: params,
      header: {
        token: wx.getStorageSync('token') || ''
      },
      success: ({ data, statusCode, header }) => {
        console.log(`==============${url}`, data)
        resolve(data)
        if (data.code == 200) {
          success(data, header)
        } else if (data.code == 201) {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
          fail(data, header)
        } else if (data.code == 400) {
          console.log('登录失败')
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
          let pages = getCurrentPages()
          // if (pages.length == 0) {
          //   wx.reLaunch({
          //     url: '/pages/login/login'
          //   })
          //   return
          // }
          if (pages[pages.length - 1].route == 'pages/deviceLogin/deviceLogin') {
            // wx.navigateTo({
            //   url: '/pages/login/login?prePage=1'
            // })
          } else {
            // wx.reLaunch({
            //   url: '/pages/login/login'
            // })
          }
          // wx.reLaunch({
          //   url: '/pages/login/login',
          // })
          // login()
        }
      },
      fail(error) {
        reject(error)
        wx.showToast({
          title: '服务器异常 请稍后再试',
          icon: 'none'
        })
      }
    })
  })
}

export function login(opts) {
  return new Promise((resolve, reject) => {
    // wx.login({
    //   success: (res) => {
    getWxLoginCode().then((wxCode) => {
      post(
        'api/login',
        {
          js_code: wxCode,
        },
        (res) => {
          clearWxLoginCode()
          getWxLoginCode()
          if (res.code == 200) {
            wx.setStorageSync('ticket', res.data.ticket)
            resolve(res.data)
            if (res.data.status == 1) {
              // wx.setStorageSync('userInfo', {
              //   avatar_url: res.data.avatar_url,
              //   mobile: res.data.mobile,
              //   nickname: res.data.nickname,
              //   uid: res.data.uid,
              // });
              wx.setStorageSync('token', res.data.token)
              // 查询是否首次购买
              get('api/order/check_first', {}, (res) => {
                if (res.data.order_status == 1) {
                  wx.setStorageSync('agree', true)
                }
              })
              getUser()
            }
            return
            // 此处不用再跳转登录页面
            if (res.data.status == 0) {
              let pages = getCurrentPages()
              if (
                pages[pages.length - 1].route == 'pages/deviceLogin/deviceLogin'
              ) {
                wx.navigateTo({
                  url: '/pages/login/login?prePage=1'
                })
              } else {
                wx.reLaunch({
                  url: '/pages/login/login'
                })
              }
              // if(opts && opts.path == 'pages/deviceLogin/deviceLogin') {
              //   wx.navigateTo({
              //     url: '/pages/login/login',
              //   })
              // } else {
              //   wx.reLaunch({
              //     url: '/pages/login/login',
              //   })
              // }
              return
            }
          }
        },
        () => {
          clearWxLoginCode()
          getWxLoginCode()
        }
      )
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      // }
    })
  })
}

/**
 * 获取用户信息
 * api/user
 */
function getUser() {
  get('api/user', {}, (res) => {
    if (res.data) {
      wx.setStorageSync('userInfo', res.data)
    }
    console.log(res)
  })
}

export function getWxLoginCode() {
  let loginConfig = getApp().loginConfig
  let refreshCode = function (resolve, reject) {
    wx.login({
      success: (res) => {
        loginConfig.code = res.code
        loginConfig.codeTime = new Date().getTime()
        resolve && resolve(res.code)
      },
      fail: (res) => {
        reject && reject(res)
      }
    })
  }
  //code的有效期不能超过1个小时
  if (
    !loginConfig.code ||
    new Date().getTime() - loginConfig.codeTime > 50 * 60 * 60 * 1000
  ) {
    return new Promise((resolve, reject) => {
      refreshCode(resolve, reject)
    })
  } else {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: function () {
          resolve(getApp().loginConfig.code)
        },
        fail: function () {
          // session_key 已经失效，需要重新执行登录流程
          refreshCode(resolve, reject)
        }
      })
    })
  }
}

// 清理code
export function clearWxLoginCode() {
  getApp().loginConfig = {
    code: '',
    codeTime: ''
  }
}
