import Vue from 'vue'
import { login, logout, phoneLogin } from '@/api/services/login'
import {
  ACCESS_TOKEN,
  SYS_BUTTON_AUTH,
  USER_AUTH,
  USER_INFO,
  USER_NAME,
  CACHE_INCLUDED_ROUTES
} from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { queryPermissionsByUser } from '@/api/services/base'
import { getAction } from '@/api/manage'
import { loadWebsocket } from '@/utils/websocket'

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    mixMenuModeTitle: '',
    mixMenuModePath: '',
    mixMenuModeOrigin: '',
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_MIX_MENU_MODE_TITLE: (state, { title, path, origin }) => {
      state.mixMenuModeTitle = title
      state.mixMenuModePath = path
      state.mixMenuModeOrigin = origin
    },
    SET_PERMISSION_LIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getAction('/cas/client/validateLogin', userInfo)
          .then(response => {
            if (response.success) {
              const result = response.value
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              resolve(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            if (response.code === '200') {
              const result = response.value
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              loadWebsocket()
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    //手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo)
          .then(response => {
            if (response.code === '200') {
              const result = response.value
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        queryPermissionsByUser({ token: Vue.ls.get(ACCESS_TOKEN) })
          .then(response => {
            console.log('菜单: ', response.value.menu)
            const menuData = response.value.menu
            let isAuth = false
            for (let v of menuData) {
              if (v.meta.title === process.env.VUE_APP_PROJECT_NAME) {
                isAuth = true
              }
            }
            if (isAuth) {
              const authData = response.value.auth
              const allAuthData = response.value.allAuth
              //Vue.ls.set(USER_AUTH,authData);
              sessionStorage.setItem(USER_AUTH, JSON.stringify(authData))
              sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData))
              let routes = {}
              if (menuData && menuData.length > 0) {
                for (let v of menuData) {
                  if (v.meta.title === process.env.VUE_APP_PROJECT_NAME) {
                    routes = v
                  }
                }
                commit('SET_PERMISSION_LIST', routes.children)
              } else {
                reject('getPermissionList: permissions must be a non-null array !')
              }
              resolve(routes.children)
            } else {
              reject({ message: '您当前没有这个菜单的权限！！！' })
            }
          })
          .catch(error => {
            console.error(`%c获取用户信息失败了！！！`, 'color: #13c2c2')
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise(resolve => {
        let logoutToken = state.token
        commit('SET_TOKEN', '')
        commit('SET_PERMISSION_LIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(CACHE_INCLUDED_ROUTES)
        localStorage.clear()
        logout(logoutToken)
          .then(() => {
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    }
  }
}

export default user
