import Vue from 'vue'
import { getInfo, login } from "@/api/common/login"
import { ACCESS_TOKEN, BEARER } from "@/store/mutation-types"
import SocketService from '@/util/websocket'

const user = {
  state: {
    token: '',
    name: '',
    username: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    buttons: null,
    websocket: null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    },
    SET_WEBSOCKET: (state, websocket) => {
      state.websocket = websocket
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if (response.code == SYS_CONST.REQUEST.SUCCEED) {
            let token = BEARER + response.data.token;
            console.log("token====================", token)
            if (userInfo.rememberMe == true) {
              Vue.ls.set(ACCESS_TOKEN, token, response.data.expirationTime)
            } else {
              sessionStorage.setItem(ACCESS_TOKEN, token)
            }
            commit('SET_TOKEN', token)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          let data = response.data;
          console.log("userinfo", data);

          const buttonAuthList = new Set();
          data.operateList.forEach(button => {
            if (button) {
              buttonAuthList.add(button)
            }
          });

          commit('SET_NAME', data.userInfo.realName || data.userInfo.username);
          commit('SET_AVATAR', data.userInfo.avatar);
          commit('SET_BUTTONS', buttonAuthList);
          try {
            SocketService.init()
          } catch (e) {
            console.error(e)
          }


          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        commit('SET_BUTTONS', []);
        Vue.ls.remove(ACCESS_TOKEN);
        sessionStorage.removeItem(ACCESS_TOKEN);
        resolve()
      })
    },

  }
}

export default user