import {
  login,
  register,
  Profile,
  GetMyPermission
} from '@/api/user'
import router from '@/router'
import { setToken, getToken, getUUID, matchRouters } from '@/libs/util'
import { asynRouters, permission_page } from '@/router/aysnRouters.js'
import Cookies from 'js-cookie'
export default {
  state: {
    username: '',
    userId: '',
    avatarImgPath: '',
    a_levelname: '',
    token: getToken(),
    uuid: getUUID(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    permission: []
  },
  mutations: {
    setPermission (state, permission) {
      state.permission = permission
    },
    setLevelName (state, name) {
      state.a_levelname = name
    },
    setAvatar (state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUsername (state, name) {
      state.username = name
    },
    setUserRole (state, role) {
      state.userRole = role
    },

    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 获取基本信息
    getIndexInfo ({ state, commit }) {
      let formdata = new FormData()
      formdata.append('access_token', state.token)
      Profile(formdata).then(res => {
        let a_levelname = res.data.profile.member_level_name
        let a_username = res.data.profile.username
        commit('setLevelName', a_levelname)
        commit('setUsername', a_username)
      })
    },
    // 获取用户权限
    getPermission ({ state, commit }) {
      let formdata = new FormData()
      formdata.append('access_token', state.token)

      return GetMyPermission(formdata).then(res => {
        // console.log(res)
        if (res.data.level === 255) {
          let routes = asynRouters.concat(permission_page)
          // 从普通管理员切换到超管时会出现路由子集为空，出现时强刷页面
          if (!routes[0].children.length || routes[0].children.length === 0) {
            window.location.reload()
          }
          commit('setPermission', routes)
          router.addRoutes(routes)
        } else {
          let permission = res.data.paths
          const routes = matchRouters(asynRouters, permission)
          commit('setPermission', routes)
          router.addRoutes(routes)
        }
      })
    },
    // 注册
    handleRegister ({ commit }, { username, password }) {
      username = username.trim()
      let formdata = new FormData()
      formdata.append('username', username)
      formdata.append('password', password)
      return new Promise((resolve, reject) => {
        register(formdata).then(res => {
          const data = res.data
          commit('setToken', data.access_token) // token?   //todo 解决undefined变成字符串
          // Cookies.set('name', '');
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 登录
    handleLogin ({ commit, dispatch }, { username, password, captcha, cookiesExp }) {
      username = username.trim()
      const formdata = new FormData()
      formdata.append('username', username)
      formdata.append('password', password)
      formdata.append('captcha', captcha)
      formdata.append('is_admin_login', 1) // 管理员登录
      return new Promise((resolve, reject) => {
        login(formdata).then(res => {
          const data = res.data
          setToken(data.access_token, cookiesExp)
          commit('setToken', data.access_token) // token?   //todo 解决undefined变成字符串
          commit('setUserRole', data.role)
          dispatch('getIndexInfo')
          resolve(res)
        })
      })
    },
    // 退出登录
    handleLogOut ({ commit }) {
      return new Promise((resolve, reject) => {
        commit('setToken', '')
        commit('setAccess', [])
        commit('removePermission')
        Cookies.remove('token', { name: 'login' })
        Cookies.remove('username', { name: 'login' })
        Cookies.remove('a_member_level_name', { name: 'login' })
        Cookies.remove('admin_code')
        resolve()
      })
    }
  }
}
