import Taro from '@tarojs/taro'
import { API_UPLOAD_IMAGE } from '@constants/api'
import login from '@utils/login'
const CODE_SUCCESS = 1000
const CODE_UNLOGIN = 1001
const CODE_AUTH_EXPIRED = 1002
const accountInfo = wx.getAccountInfoSync();
const appId = accountInfo.miniProgram.appId

export const getStorage = function (key) {
  return Taro.getStorage({ key }).then(res => res.data).catch(() => '')
}

export const setStorage = function (key, data) {
  return Taro.setStorage({ key, data })
}

// function updateToken(data = {}) {
//   return Promise.all([
//     Taro.setStorage({ key: 'token', data: data['token'] || '' })
//   ])
// }

/**
 * 简易封装网络请求
 * // NOTE 需要注意 RN 不支持 *StorageSync，此处用 async/await 解决
 * @param {*} options
 */
export const fetch = async (options) => {
  const { url, payload, method = 'GET', showToast = true, autoLogin = true } = options

  return Taro.request({
    url,
    method,
    data: payload,
    header: {
      'content-type': 'application/json',
      'authorization': `Bearer ${Taro.getStorageSync('token')}`,
      'appId': appId,
      'x-action':'miniapp'
    }
  }).then(async (res) => {
    if(res.statusCode === 500){
      Taro.showToast({
        title: "请检查网络",
        icon: 'none'
      })
      return Promise.reject({ message: "请检查网络" })
    }
    const { data, code } = res.data
    if (code !== CODE_SUCCESS) {
      return Promise.reject(res.data)
    }

    // if (url.split('?')[0] === API_USER_LOGIN) {
    //   await updateToken(data.miniApp)
    // }
    return data
  }).catch((err) => {
    const isExpired = (err.code === CODE_AUTH_EXPIRED || err.code === CODE_UNLOGIN)
    const defaultMsg = isExpired ? '登录失效' : (err.message || '请求异常')
    if (isExpired && autoLogin) {
      // token失效，重新登录后，跳转到首页
      login({}, () => {
        Taro.switchTab({
          url: '/pages/project/index'
        })
      })
    } else {
      if (showToast) {
        Taro.showToast({
          title: err && err.msg || defaultMsg,
          icon: 'none'
        })
      }
    }
    return Promise.reject({ message: defaultMsg, ...err })
  })
}

export const uploadFiles = async (files) => {
  const uploads = []
  const token = await getStorage('token')
  const authHeader = token ? { 'authorization': `Bearer ${token}` } : {}
  for (var i = 0; i < files.length; i++) {
    uploads[i] = new Promise((resolve, reject) => {
      wx.uploadFile({
        url: API_UPLOAD_IMAGE,
        filePath: files[i],
        header: {
          ...authHeader,
          'appId': appId,
          'x-action':'miniapp'
        },
        name: 'file',
        success: function (res) {
          // debugger
          const _data = JSON.parse(res.data)
          if (_data.code !== CODE_SUCCESS) {
            reject(new Error(_data.message))
          }

          resolve(_data.data)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }

  return Promise.all(uploads)
}
