import { login, logout, getInfo, getAccountMenus, getButtonPermissions } from '@/api/ops-system'

import { addDashboardPreviews } from '@/api/ops-system'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, defaultRoutes, endRouter } from '@/router'
import { menuToRouter } from '@/utils/menu'
import { sysOriginPlatforms } from '@/constant/origin'
import { getDashboard } from '@/api/ops-system'
import { setTheme, checkSwitchTheme } from '@/utils/theme'

const getDefaultState = () => {
  return {
    token: getToken(),
    uid: '',
    name: '',
    loginName: '',
    avatar: '',
    routers: defaultRoutes,
    menus: [],
    permissions: {
      // 权限菜单第一个元素
      firstSysOrigin: '',
      // 拥有的系统权限
      sysOriginPlatforms: [],
      // 拥有的系统权限-根结点
      sysOriginPlatformRoots: [],
      // 是否拥有所有系统权限
      allSysOriginPermissions: false,
      // 拥有按钮权限
      buttonPermissions: []
    },
    dashboard: {
      theme: 'auto',
      recentPreviews: [],
      customNavigations: []
    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_LOGIN_NAME: (state, loginName) => {
    state.loginName = loginName
  },
  SET_UID: (state, uid) => {
    state.uid = uid
  },
  SET_ROUTERS: (state, routers) => {
    state.routers = defaultRoutes.concat(routers)
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_BUTTON_PERMISSIONS: (state, buttonPermissions) => {
    state.permissions.buttonPermissions = buttonPermissions || []
  },
  SET_PERMISSIONS_SYS_ORIGIN_PLATFIRMS(state, buttonPermissions) {
    if (!buttonPermissions || buttonPermissions.length <= 0) {
      return
    }
    const permissionsSysOriginPlatforms = sysOriginPlatforms.filter(item => buttonPermissions.includes(item.permission))
    if (!permissionsSysOriginPlatforms || permissionsSysOriginPlatforms.length <= 0) {
      return
    }
    const permissions = state.permissions
    permissions.sysOriginPlatforms = permissionsSysOriginPlatforms
    permissions.firstSysOrigin = permissionsSysOriginPlatforms[0]
    permissions.allSysOriginPermissions = permissionsSysOriginPlatforms.length === sysOriginPlatforms.length
    permissions.sysOriginPlatformRoots = permissionsSysOriginPlatforms.filter(item => !item.parentValue || item.parentValue.length <= 0)
  },
  SET_DASHBOARD(state, dashboard) {
    state.dashboard = dashboard || {
      theme: 'auto',
      recentPreviews: [],
      customNavigations: []
    }
    setTheme(state.dashboard.theme)
    checkSwitchTheme()
  }
}

const actions = {
  getUserDashboard({ commit }) {
    return new Promise((resolve, reject) => {
      getDashboard().then(response => {
        const { body } = response
        commit('SET_DASHBOARD', body)
        resolve(body)
      }).catch(error => {
        reject(error)
      })
    })
  },
  buttonPermissions({ commit }) {
    return new Promise((resolve, reject) => {
      getButtonPermissions().then(response => {
        const { body } = response
        commit('SET_BUTTON_PERMISSIONS', body)
        commit('SET_PERMISSIONS_SYS_ORIGIN_PLATFIRMS', body)
        resolve(body)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user login
  login({ commit }, { username, password }) {
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { body } = response
        commit('SET_TOKEN', body.token)
        commit('SET_UID', body.uid)
        setToken(body.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { body } = response

        if (!body) {
          reject('Verification failed, please Login again.')
        }

        const { nickname, id, loginName } = body

        commit('SET_NAME', nickname)
        commit('SET_AVATAR', '')
        commit('SET_UID', id)
        commit('SET_LOGIN_NAME', loginName)
        resolve(body)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken()
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // get user menus
  getMenus({ commit }) {
    return new Promise((resolve, reject) => {
      getAccountMenus().then(res => {
        const { body } = res
        const grantRouters = menuToRouter(body).concat(endRouter)
        commit('SET_MENUS', body)
        commit('SET_ROUTERS', grantRouters)
        resolve(grantRouters)
      }).catch(er => {
        reject(er)
      })
    })
  },
  // 添加最近预览导航
  addNavigationRecentPreviews({ commit }, navigation) {
    return new Promise((resolve, reject) => {
      addDashboardPreviews(navigation).then(res => {
        resolve(res)
      }).catch(er => {
        reject(er)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

