const InitUserInfo = {
  roles: [],
};

// 定义的state初始值
const state = {
  token: localStorage.getItem('associationToken') || 'main_token', // 默认token不走权限
  userInfo: InitUserInfo,
  association:localStorage.getItem('associationInfo') || '',
  //apiUrl:'http://192.168.3.130',
  apiUrl:'https://ysx.0rui.cn'
};

const mutations = {
  setToken(state, token) {
    localStorage.setItem('associationToken', token);
    state.token = token;
  },
  removeToken(state) {
    localStorage.removeItem('associationToken');
    state.token = '';
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
  setAssociation(state, Association) {
    localStorage.setItem('associationInfo',  JSON.stringify(Association) );
    state.association = Association;
  },
  removeAssociation(state) {
    localStorage.removeItem('associationInfo');
    state.association = '';
  },
};

const getters = {
  token: (state) => state.token,
  roles: (state) => state.userInfo?.roles,
};

const actions = {
  async login({ commit }, userInfo) {
    const mockLogin = async (userInfo) => {
      // 登录请求流程
      console.log(userInfo);
      commit('setAssociation',userInfo[0]);
      return{
        code: 200,
      }
    };

    const res = await mockLogin(userInfo);
    if (res.code === 200) {
      commit('setToken', 'main_token');
    } else {
      return res;
    }
  },
  async getUserInfo({ commit, state }) {
    const mockRemoteUserInfo = async (token) => {
      if (token === 'main_token') {
        return {
          name: 'td_main',
          roles: ['ALL_ROUTERS'],
        };
      }
      return {
        name: 'td_dev',
        roles: ['UserIndex', 'DashboardBase', 'login'],
      };
    };

    const res = await mockRemoteUserInfo(state.token);

    commit('setUserInfo', res);
  },
  async logout({ commit }) {
    commit('removeToken');
    commit('setUserInfo', InitUserInfo);
  },
};

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