import http from './interface'
import { platform } from '../utils/index'
import { webLogin, mini_env, replaceStringInObject } from '@/common/utils/util'
import store from '@/store/index.js'

import { goLoginPage } from '@/mixins/index.js'

import { setStorage, getStorage, removeStorage } from '@/common/utils/storage.js'
import { navToPage } from 'common/utils/navPag'
// #ifdef H5
// 解析地址栏参数
function getQueryVariable(variable) {
  // 从?开始获取后面的所有数据
  var query = window.location.search.substring(1)
  // 从字符串&开始分隔成数组split
  var vars = query.split('&')
  // 遍历该数组
  for (var i = 0; i < vars.length; i++) {
    // 从等号部分分割成字符
    var pair = vars[i].split('=')
    // 如果第一个元素等于 传进来的参的话 就输出第二个元素
    if (pair[0] == variable) {
      return pair[1]
    }
  }
  return undefined
}
// #endif

const program = {
  H5: 'wap',
  APP: 'app',
  APPNVUE: 'app',
  WEIXIN: 'miniProgram'
}
const whiteCodes = [200, 201]

function removeQueryParams(params) {
  var url = new URL(window.location.href) // 获取当前 URL

  // 遍历每个参数并删除
  params.forEach(function (param) {
    url.searchParams.delete(param)
  })

  // 使用新的 URL 更新地址栏，且不刷新页面
  window.history.pushState({}, '', url)
  location.reload() // 刷新页面，重新加载
}

export const $http = (url, method, data, json, loadingBool = false, isExecute = true, isForm = false) => {
  //设置请求前拦截器
  http.interceptor.request = config => {
    return new Promise(r => {
      mini_env(bool => {
        if (loadingBool && url !== '/homepage/study') {
          uni.showLoading({
            title: '加载中...'
          })
        }

        config.header = {
          'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
          // "x-token": getStorage('token'),
          'x-token': store.getters.token,
          APPID: store.getters.appId,
          Program: program[platform()],
          source: bool ? 'A' : 'B',
          miniOpenId: store.getters.miniOpenId,
          sharerOpenId: store.getters.sharerOpenId
        }
        r(true)
      })
    })
  }
  //设置请求结束后拦截器
  http.interceptor.response = async response => {
    //判断返回状态 执行相应操作
    if (loadingBool) {
      uni.hideLoading()
    }
    const res = replaceStringInObject(
      response.data || {},
      ['https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/', 'https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/'],
      process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/img/get?key='
    )
    if (!isExecute) {
      return res
    }
    if (whiteCodes.indexOf(res.code) < 0) {
      if (~res.message.indexOf('USERPAYING')) {
        return Promise.reject(new Error(res.message || 'Error'))
      }
      if (res.code === 4444) {
        // #ifdef H5
        uni.removeStorageSync(`APPID${getQueryVariable('appid')}_token`)
        // #endif
        webLogin(true)
        return {}
      }
      if ([1001].includes(res.code)) {
        webLogin(true)
        return {}
      } else if (res.code === 4001) {
        uni.showModal({
          title: '提示',
          content: '你尚未绑定手机号，无法下单！',
          confirmText: '立即绑定',
          success: function (res) {
            if (res.confirm) {
              navToPage({
                url: '/packageMine/pages/phone'
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        if (isForm) {
          uni.showModal({
            title: '温馨提示',
            content: res.message || 'Error',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              } else if (res.cancel) {
              }
            }
          })
        } else {
          uni.showModal({
            title: '温馨提示',
            content: res.message || 'Error',
            showCancel: false,
            confirmText: '知道了',
            success: function (res) {
              if (res.confirm) {
              } else if (res.cancel) {
              }
            }
          })
        }
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  }

  if (store.getters.token) {
    return http.request({
      method: method,
      url: url,
      dataType: 'json',
      data
    })
  } else if (!!~['/user/auth2', '/goods/detail', '/user/jsapi/sign'].indexOf(url)) {
    return http.request({
      method: method,
      url: url,
      dataType: 'json',
      data
    })
  } else {
    return new Promise((resolve, reject) => {
      var digui = function () {
        if (store?.getters?.token && store?.getters?.userId) {
          http
            .request({
              method: method,
              url: url,
              dataType: 'json',
              data: {
                ...data,
                userId: store.getters.userId
              }
            })
            .then(resolve)
            .catch(reject)
        } else {
          setTimeout(digui, 100)
        }
      }
      digui()
    })
  }
}

async function login() {
  //返回环宇token所需的login code
  return new Promise(resolve => {
    uni.login({
      provider: 'weixin',
      success(loginRes) {
        resolve(loginRes.code)
      },
      fail() {}
    })
  })
}

async function doRequest(response, url) {
  var code = await login()
  var res = await get('/v1/oauth/refreshToken/code/' + code, {})
  if (res && res.data.data.token) {
    let config = response.config
    setStorage('token', res.data.data.token)
    config.header['Authorization'] = res.data.data.token
    let json = config.header['Content-Type'] === 'application/json'
    const resold = await $http(
      url,
      config.method,
      {
        ...config.data
      },
      json
    )
    return resold
  } else {
    uni.clearStorage()
    uni.showToast({
      title: '授权失效，请重新登录',
      duration: 1000
    })
    this.$navToPage({
      url: '/pages/login/auth'
    })
    return false
  }
}

function postJson(url, data, loadingBool, isExecute, isForm) {
  return $http(url, 'POST', data, true, loadingBool, isExecute, isForm)
}

function post(url, data, loadingBool, isExecute, isForm) {
  return $http(url, 'POST', data, false, loadingBool, isExecute, isForm)
}

function get(url, data, loadingBool) {
  return $http(url, 'GET', data, false, loadingBool)
}

function put(url, data, loadingBool) {
  return $http(url, 'PUT', data, true, loadingBool)
}

function del(url, data, loadingBool) {
  return $http(url, 'DELETE', data, true, loadingBool)
}

//封装的通用请求方法
export const axios = function (obj = {}) {
  if (typeof obj !== 'object') {
    throw new Error('arguments must be object')
  }
  if (!obj.url) {
    throw new Error('url not defined')
  }
  return new Promise((resolve, reject) => {
    if (obj.isLoading) {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
    }
    let _url = process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + obj.url
    let isGet = obj.method && obj.method.toLowerCase() == 'get'
    let isQuery = obj.isQuery
    if (isGet || isQuery) {
      _url +=
        '?' +
        Object.entries(obj.params || {})
          .map(item => item.join('='))
          .join('&')
    }
    let _type = 'application/x-www-form-urlencoded'
    if (obj.type == 'json') {
      _type = 'application/json'
    }
    uni.request({
      url: _url,
      data: isGet || isQuery ? '' : obj.params || '',
      header: {
        'content-type': _type,
        'x-token': store.getters.token
      },
      method: obj.method ? obj.method : 'POST',
      success: function (ress) {
        if (obj.isLoading) {
          uni.hideLoading()
        }
        const res = replaceStringInObject(
          ress.data,
          ['https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/', 'https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/'],
          process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/img/get?key='
        )
        if (whiteCodes.indexOf(res.code) < 0) {
          if (res.code === 1001) {
            webLogin(true)
            reject(new Error(res.message || 'Error'))
            return {}
          }

          if (res.code === 4444) {
            // #ifdef H5
            uni.removeStorageSync(`APPID${getQueryVariable('appid')}_token`)
            // #endif
            webLogin(true)
            reject(new Error(res.message || 'Error'))
            return {}
          }

          if (res.message || res.code) {
            uni.showToast({
              title: res.message || 'Error',
              icon: 'none',
              duration: 1500
            })
          }

          reject(new Error(res.message || 'Error'))
        } else {
          resolve(res)
        }
      },
      fail: function (err) {
        uni.hideLoading()
        uni.showModal({
          title: '提示',
          content: '网络连接失败' + JSON.stringify(err)
        })
        reject(err)
      }
    })
  })
}

export default {
  postJson,
  get,
  post,
  put,
  del
}
