import { login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Notification } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    rolesTree: [],
    keepList: localStorage.getItem('user-tabs') && JSON.parse(localStorage.getItem('user-tabs')) || [],
    editableTabs: [],
    editableTabsValue: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLESTREE: (state, roles) => {
    state.rolesTree = roles
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  ADD_TABS: (state, tab) => {
    // 确保 keepList 存在
    if (!state.keepList) state.keepList = []
    // 查找是否已存在相同路径的标签
    const existingIndex = state.keepList.findIndex(item => item.path === tab.path)
    if (existingIndex === -1) {
      // 添加新标签
      state.keepList.push(tab)
    } else {
      // 更新已有标签
      state.keepList[existingIndex] = {
        ...state.keepList[existingIndex],
        ...tab
      }
    }
    // 保存到缓存
    saveToCache(state.keepList)
  },
  // 删除标签 - 通过路径
  REMOVE_TAB_BY_PATH: (state, path) => {
    if (!state.keepList || !Array.isArray(state.keepList)) return
    // 记录删除前的长度
    const beforeLength = state.keepList.length
    // 过滤掉指定路径的标签
    state.keepList = state.keepList.filter(item => item.path !== path)
    // 记录删除后的长度
    const afterLength = state.keepList.length
    if (beforeLength !== afterLength) {
      console.log(`删除了标签: ${path}`)
      // 保存到缓存
      saveToCache(state.keepList)
      // 触发事件通知
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('tab-removed', {
          detail: { path }
        }))
      }
    }
  }
}

// 保存到缓存的辅助函数
function saveToCache(keepList) {
  try {
    localStorage.setItem('user-tabs', JSON.stringify(keepList))
  } catch (error) {
    console.error('保存缓存失败:', error)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, code }).then(response => {
        state.keepList = []
        localStorage.setItem('user-tabs', [])
        const { data } = response
        console.log(data, 'login')
        Notification({
          title: '成功',
          message: '欢迎登陆～',
          type: 'success'
        })
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()

      // logout().then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // })
      //   .catch(() => {
      //     removeToken() // must remove  token  first
      //     resetRouter()
      //     commit('RESET_STATE')
      //     resolve()
      //   })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  addTab({ commit }, tab) {
    commit('ADD_TABS', tab)
  }
}

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

