import Taro from '@tarojs/taro'
import { noEmpty } from '@utils'
const HLKEY = '654mca0l38b489d9'
const CJ = require('crypto-js')
const Http = (options = { data: {} }) => {
  return new Promise((resolve, reject) => {
    if (options.loadingStr === 'loading') {
      Taro.showLoading({
        mask: true,
        title: '加载中..'
      })
    }
    Taro.getEnv() === Taro.ENV_TYPE.WEAPP && Taro.showNavigationBarLoading()
    let header = {
      // 'Content-Type': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    let params = {...options.data}
    if (Taro.getStorageSync('APP_token')) params.token = Taro.getStorageSync('APP_token')
    for (let key in options.data) {
      if (options.data[key] === undefined || options.data[key] === 'undefined') {
        params[key] = ''
      }
    }
    try {
      // let baseUrl = 'http://api.kaolanet.com'
      let baseUrl = 'https://api.honglouplus.com'
      // let baseUrl = 'https://api.honglounews.com'
      const resX = Taro.request({
        url: baseUrl + options.url,
        data: {
          ...params
        },
        header,
        method: options.method || 'POST',
        complete: res => {
          if (options.loadingStr === 'loading') {
            Taro.hideLoading()
          }
          Taro.getEnv() === Taro.ENV_TYPE.WEAPP && Taro.hideNavigationBarLoading()
        }
      })
      resX.then(res => {
        const { statusCode } = res
        if (statusCode === 200) {
          const msg = res.data || ''
          const key = CJ.enc.Utf8.parse(HLKEY)
          const bytes = CJ.AES.decrypt(msg, key, {
            mode: CJ.mode.ECB,
            padding: CJ.pad.Pkcs7
          })
          const originalText = bytes.toString(CJ.enc.Utf8)
          const data = JSON.parse(originalText)
          // console.log(data)
          // const data = res.data
          const { errno } = data
          switch (errno) {
            case 0:
              return resolve(noEmpty(data.data) ? data.data : data)
              break
            case 401:
            case 402:
            case 403:
            case 404:
            case 405:
              if (Taro.getStorageSync('APP_token')) {
                Taro.login({
                  success: function (res) {
                    if (res.code) {
                      Taro.api.base.apiwxautologin({code: res.code}).then(cData => {
                        if (cData.token === 'error') {
                          Taro.removeStorageSync('APP_token')
                        } else {
                          const userInfo = {
                            nickName: cData.nickname,
                            avatarUrl: cData.avatar,
                            phone: cData.phone,
                          }
                          Taro.setStorageSync('APP_userInfo', userInfo)
                          Taro.setStorageSync('APP_token', cData.token)
                        }
                      })
                    }
                  }
                })
              }
              break
            default:
              Taro.showModal({
                title: '提示',
                content: `${data.errmsg}，错误码：${errno}`,
              })
              return reject(data)
          }
        } else {
          // Taro.reLaunch({
          //   url: '/pages/login/index?backType=error'
          // })
          Taro.showToast({
            title: `网络请求错误，状态码${statusCode}`,
            icon: 'none',
            mask: true,
          })
          reject(data)
          throw new Error(`网络请求错误，状态码${statusCode}`)
        }
      })
    } catch (err) {
      Taro.getEnv() === Taro.ENV_TYPE.WEAPP && Taro.hideNavigationBarLoading()
      reject(new Error('网络请求出错~'))
    }
  })
}
// export default Http

function request (url, data, loadingStr) {
  let pages = getCurrentPages()
  if (pages.length > 8) {
    Taro.reLaunch({
      url: '/pages/index/index'
    })
  }
  return Http({
    url,
    data,
    loadingStr
  })
}
function requestNoErrorTip (url, data) {
  return Http({
    url,
    data,
    noErrorTip: true
  })
}
export {
  request,
  requestNoErrorTip
}
