import { getUserInfos, login, logout, userBindWechat } from '@/api/user';
import { getToken, removeToken, setToken } from '@/utils/token';
// import { resetRouter, setRouterMenus } from '@/router'
import { resetRouter, setRouterMenus, delRouterMenus } from '@/router';
// import { isArray } from '@/utils/validate'
import { title, tokenName } from '@/config';
import { ElNotification, ElMessage } from 'element-plus';

const state = () => ({
  token: getToken(),
  username: '游客',
  avatar: 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif',
});
const getters = {
  token: state => state.token,
  username: state => state.username,
  avatar: state => state.avatar,
  roles: state => state.roles,
  // menu: (state) => state.menu,
};
const mutations = {
  setToken(state, token) {
    state.token = token;
    setToken(token);
  },
  setUsername(state, username) {
    state.username = username;
  },
  setAvatar(state, avatar) {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  // menu: (state, menu) => {
  //   state.menu = menu
  // },
};
const actions = {
  setVirtualRoles({ commit, dispatch }) {
    dispatch('acl/setFull', true, { root: true });
    commit(
      'setAvatar',
      'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif'
    );
    commit('setUsername', 'admin(未开启登录拦截)');
  },
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo);
    const token = data[tokenName];
    if (token) {
      commit('setToken', token);
      const hour = new Date().getHours();
      const thisTime =
        hour < 8
          ? 'Good morning'
          : hour <= 11
          ? 'Good morning'
          : hour <= 13
          ? 'Good afternoon'
          : hour < 18
          ? 'Good afternoon'
          : 'Good evening';
      ElNotification.success({
        title: `welcome login ${title}`,
        message: `${thisTime}！`,
        position: 'top-right',
      });
      // const { data } = await getUserInfos()
      // const { menus } = data
      // if (menus) {
      //   await setRouterMenus(menus)
      // } else {
      //   ElMessage.error('getUserInfo核心接口异常，请检查返回JSON格式是否正确')
      //   return Promise.reject()
      // }
    } else {
      ElMessage.error(`登录接口异常，未正确返回${tokenName}...`);
      return Promise.reject();
    }
  },
  async getUserInfo({ commit, dispatch }) {
    const { data } = await getUserInfos();
    const { userName, nickName, role, menus } = data;
    var openid = sessionStorage.getItem('userOpenid');
    if (openid != '' && openid != undefined) {
      await userBindWechat({
        openid: openid,
        userName: userName,
      });
      sessionStorage.removeItem('userOpenid');
    }
    if (userName && nickName && role && menus) {
      localStorage.setItem('userId', data.id);
      commit('setUsername', userName);
      commit('setAvatar', nickName);
      commit('SET_ROLES', role);
      // commit('menu', menus)
      if (!role && !menus) dispatch('acl/setFull', true, { root: true });
      if (role) dispatch('acl/setRole', role, { root: true });
      if (menus) dispatch('acl/setAbility', menus, { root: true });
      await setRouterMenus(menus);
      // await setRouterMenus(menus)
    } else {
      ElMessage.error('getUserInfo核心接口异常，请检查返回JSON格式是否正确');
      return Promise.reject();
    }
  },
  async logout({ dispatch }) {
    delRouterMenus();
    await logout(state.token);
    await dispatch('resetAll');
    location.reload();
  },
  async resetAll({ dispatch }) {
    await dispatch('setToken', '');
    await dispatch('acl/setFull', false, { root: true });
    await dispatch('acl/setRole', [], { root: true });
    await dispatch('acl/setAbility', [], { root: true });
    await dispatch('tabsBar/delAllVisitedRoutes', [], { root: true });
    await resetRouter();
    removeToken();
    location.reload();
  },
  setToken({ commit }, token) {
    commit('setToken', token);
  },
  setAvatar({ commit }, avatar) {
    commit('setAvatar', avatar);
  },
};
export default { state, getters, mutations, actions };
