import router from './router/index'
import store from '@/store'
// import {validatenull} from '@/util/validate'
import { getParamsByUrl, removeUrlParam } from '@/util/index'
import { getOauth, getUserByToken } from '@/api/auth/auth'
import baseUrl from '@/util/baseUrl'
import { Toast } from 'mint-ui'
import { wxpermission } from '@/wxpermission'

const defaultUrl = baseUrl.authUrl
router.beforeEach((to, from, next) => {
  console.log('缓冲设置')
  console.log('code ===' + store.getters.code)

  // 判断链接是否被微信分享篡改,false需重定向
  if (redirectUrl()) {
    wxpermission(0, () => {})
    // store.dispatch('setToken', '')
    // store.dispatch('setUserId', '')
    // let accessToken = store.getters.access_token
    let storecode = store.getters.code
    if (!storecode || storecode === '') {
      let params = getParamsByUrl(window.location.href)
      if (params.code) {
        store.dispatch('setCode', params.code)
        getOauthFn(() => {
          next()
        })
      } else {
        getWXOauth()
      }
    } else {
      next()
    }
  }
  // store.dispatch('setToken', '490cd9b7-dca7-4cc3-87e9-5eacbb5a5d77')
})

let getWXOauth = () => {
  console.log()
  let url = removeUrlParam('code')
  // store.dispatch('setCode', '')
  let authId = ''
  if (getParamsByUrl(window.location.href).auth_id) {
    authId = '&auth_id=' + getParamsByUrl(window.location.href).auth_id
    store.dispatch('setAuthId', getParamsByUrl(window.location.href).auth_id)
  }
  window.location.href = defaultUrl + '/wxoauth/route?redirect_uri=' + encodeURIComponent(url) + authId + '&scoe=&auth_scene=voucher'
}

let getOauthFn = (callback) => {
  if (getParamsByUrl(window.location.href).auth_id) {
    store.dispatch('setAuthId', getParamsByUrl(window.location.href).auth_id)
  }
  let spoauthParams = {
    code: store.getters.code
  }
  getOauth(spoauthParams).then(function (res) {
    if (res.token && res.token !== '') {
      getUserByTokenFn(res.token, store.getters.code, callback)
    } else {
      store.dispatch('setCode', '')
      setTimeout(function () {
        getWXOauth()
      }, 3 * 1000)
      Toast({
        message: 'wx token已失效!',
        position: 'center',
        duration: 3 * 1000
      })
    }
  }).catch((error) => {
    console.log(error)
    Toast({
      message: '鉴权失败',
      position: 'center',
      duration: 3 * 1000
    })
    // setTimeout(function () {
    //   getWXOauth()
    // }, 3 * 1000)
  })
}

const getUserByTokenFn = (token, code, callback) => {
  let spoauthParams = {
    token: token
  }
  getUserByToken(spoauthParams).then(function (res) {
    let accessToken = ''
    let userId = ''
    let accountId = res.accountid
    if (accountId && accountId !== '') {
      store.dispatch('setAccountId', accountId)
    }
    if (res.ext && res.ext !== '') {
      let extOBJ = JSON.parse(res.ext)
      accessToken = extOBJ.access_token
      userId = extOBJ.user_id
    }
    if (accessToken !== '') {
      if (userId !== '') {
        store.dispatch('setToken', accessToken)
        store.dispatch('setUserId', userId)
        store.dispatch('setCode', code)
        callback()
      } else {
        setTimeout(function () {
          getWXOauth()
        }, 3 * 1000)
        Toast({
          message: 'user id不能为空!',
          position: 'center',
          duration: 3 * 1000
        })
      }
    } else {
      setTimeout(function () {
        getWXOauth()
      }, 3 * 1000)
      Toast({
        message: 'token不能为空!',
        position: 'center',
        duration: 3 * 1000
      })
    }
  }).catch((error) => {
    console.log(error)
    Toast({
      message: '鉴权失败',
      position: 'center',
      duration: 3 * 1000
    })
    setTimeout(function () {
      getWXOauth()
    }, 3 * 1000)
  })
}

// 判断链接是否被微信分享篡改
const redirectUrl = () => {
  const curUrl = window.location.href
  const curUrlArr = curUrl.split('?')
  // Toast({
  //   message: curUrl,
  //   position: 'center',
  //   duration: 2 * 1000
  // })
  // console.log(curUrlArr[1].indexOf('from=singlemessage'))
  if (curUrlArr.length === 3 && curUrlArr[1].indexOf('from=singlemessage') >= 0) {
    let newUrl = curUrlArr[0] + '#' + curUrlArr[1].split('#')[1] + '?' + curUrlArr[2]
    // Toast({
    //   message: curUrlArr[2],
    //   position: 'center',
    //   duration: 5 * 1000
    // })
    window.location.href = newUrl
    return false
  } else {
    return true
  }
}

// const nextToPath = (to, from, next) => {
//   let toquery = to.query
//   if (from.query.code) {
//     toquery.code = from.query.code
//   }
//   next({
//     path: to.path,
//     query: toquery
//   })
// }