import {
  menu,
  power,
  login,
  logout
} from "@/api/module/user";
import {
  generateRoute,
  generatePower
} from "@/route/permission";
import {
  message
} from "@hwork/ant-design-vue";

const state = {
  token: localStorage.getItem("token") ? localStorage.getItem("token") : "",
  tokenKey: localStorage.getItem("token_key") ? localStorage.getItem("token_key") : "",
  userInfo: localStorage.getItem('user_info') ? JSON.parse(localStorage.getItem('user_info')) : {},
  userRoutes: localStorage.getItem("user_routes") ? localStorage.getItem("user_routes") : [],
  userPowers: localStorage.getItem("user_powers") ? localStorage.getItem("user_powers") : [],
  //界面中用过的数据字典数据
  dictData: localStorage.getItem('dict_data') ? JSON.parse(localStorage.getItem('dict_data')) : [],
  dict: [] //内存数据，不与浏览器引用缓存同步
}

const mutations = {
  SET_USER_TOKEN(state, token) {
    if (token) {
      state.tokenKey = token.key;
      state.token = token.value;
      localStorage.setItem('token_key', token.key)
      localStorage.setItem('token', token.value)
    } else {
      state.tokenKey = '';
      state.token = '';
      localStorage.removeItem('token_key')
      localStorage.removeItem('token')
    }
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('user_info', JSON.stringify(userInfo))
  },
  SET_USER_ROUTE(state, menuList) {
    if (menuList && menuList.length === 0) {
      state.userRoutes = []
      localStorage.removeItem('user_routes')
    } else {
      const finalMenu = menuList
      state.userRoutes = finalMenu
      localStorage.setItem('user_routes', JSON.stringify(finalMenu))
    }
  },
  SET_USER_POWER(state, powerList) {
    if (powerList && powerList.length === 0) {
      state.userPowers = []
      localStorage.removeItem("user_powers")
    } else {
      const finalPower = powerList;
      state.userPowers = finalPower;
      localStorage.setItem('user_powers', JSON.stringify(finalPower))
    }
  },
  //数据字典本地缓存初始化
  SET_DICT_DATA(state) {
    state.dict = [];
    state.dictData = [];
    localStorage.setItem('dict_data', JSON.stringify([]))
  },
  //数据字典使用过程中完善
  ADD_DICT_DATA(state, dictData) {
    if (state.dict.findIndex(item => item.code === dictData.code) === -1) {
      // 如果不存在新增选项卡：解决缓存更新不及时的问题
      state.dictData.push(dictData);
      state.dict.push(dictData);
      localStorage.setItem('dict_data', JSON.stringify(state.dictData))
    }
  }
}

const actions = {

  async login({ commit }, formaData) {
    const { code, msg, token, tokenKey,data } = await login(formaData);
    if (code === 200) {
      console.log("用户信息",data)
      commit('SET_USER_TOKEN', { key: tokenKey, value: token });
      commit('SET_DICT_DATA');
      commit('SET_USER_INFO',data);
      return Promise.resolve();
    } else {
      return Promise.reject(msg);
    }
  },

  async logout({ commit }) {
    const { msg } = await logout();
    message.success(msg, 0.5).then(function() {
      commit('SET_USER_TOKEN');
      commit('SET_DICT_DATA');
      commit('SET_USER_INFO',{});
      window.location.reload();
    });
    return Promise.resolve()
  },

  async addRoute({ commit }) {
    const { data } = await menu()
    commit('SET_USER_ROUTE', generateRoute(data))
  },

  async addPower({ commit }) {
    const { data } = await power()
    commit('SET_USER_POWER', generatePower(data))
  },

  addDictData({commit }, dictData) {
    commit('ADD_DICT_DATA', dictData)
  },

  async refreshUserInfo({ commit,userInfo }) {
    console.log("userInfo",userInfo)
    commit('SET_USER_INFO',userInfo);
    localStorage.setItem('userInfo',userInfo)
  },
}
export default {
  namespaced: true,
  mutations,
  actions,
  state,
}
