import * as device from './device.js'
import querystring from './querystring/index.js'
import { getWxCodeUrl, setUrl } from './checkUrl.js'
import { setToken } from './auth.js'
import store from '@/store'
import { getUserToken } from '../api/user.js'
import useUserStore from '@/store/modules/user'
// import axios from '../plugin/axios'
// import tokenDate from './token'

// const axios = Vue.prototype.$axios
// 获取Token接口


const _search = querystring.parse(location.search)
// let _token = store.state.token


const setCookie = (token: string, id?: string) => {
  setToken(token)
  updateUser()
}
const updateUser = (token?: string) => {
  const userStore = useUserStore()
  userStore.updateToken(token || '')
}

const getShareScope = () => {
  // let _url = `${location.origin}${location.pathname}`
  // let _scope = _search.shareScope
  // _search = `?${querystring.stringify(_search)}`
  // _url = _url + _search
  location.replace(getWxCodeUrl())
}

const getShareScopeToken = () => {
  const userStore = useUserStore()
  if (userStore.token) {
    location.replace(setUrl())
    return
  }
  getUserToken(_search.code).then(res => {
    console.log(res.data)
    setCookie(res.data)
    location.replace(setUrl())
  })

}

export const checkToken = (): Promise<void> => {
  const userStore = useUserStore()
  return new Promise((resolve, reject) => {

    // 微信公众号环境
    if (device.isWechat) {
    // 分享入口
      if (_search && _search.shareScope && !_search.code) {
        getShareScope()
        reject()
        return
      }
      if (_search && _search.shareScope && _search.code) {
        getShareScopeToken()
        reject()
        return
      }
      // 正常入口
      if (!userStore.token) {
        if (_search && _search.code) {

          getUserToken(_search.code).then(res => {
            console.log(res.data)
            setCookie(res.data)
            console.log('没有token 没有rand setUrl', setUrl())
            location.replace(setUrl())
            reject()
          }).catch(err => {
            reject(err)
          })
          return
        }
        console.log('获取code')
        location.replace(getWxCodeUrl())
        reject()
        return
      }
      // 有token 没有rand
      if (_search && !_search.rand) {
        console.log('有token 没有rand setUrl', setUrl())
        location.replace(setUrl())
        reject()
        return
      }
      // 有token 有rand 都有了
      // console.log('rand: ', _search.rand)
      updateUser(userStore.token)
      resolve()
      return
    }
    location.href = getWxCodeUrl()
    console.log('不是微信环境')
    reject()
  })
}
