import { login, loginUp, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, setUserId, TokenKey } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    firstLogin: getToken('FirstLogin') ? JSON.parse(getToken('FirstLogin')) : false,
    UserType: sessionStorage.getItem('UserType') ? sessionStorage.getItem('UserType') : '',
    UserId: sessionStorage.getItem('User_Id') ? sessionStorage.getItem('User_Id') : '',
    userPoewrList: sessionStorage.getItem('userAuthList') ? JSON.parse(sessionStorage.getItem('userAuthList')) : []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_UserId: (state, UserId) => {
    state.UserId = UserId
  },
  SET_UserType: (state, UserType) => {
    state.UserType = UserType
    sessionStorage.setItem('UserType', UserType)
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_UserPoewrList: (state, arr) => {
    state.userPoewrList = arr
  },
  SET_LOGIN: (state, login) => {
    state.firstLogin = login
  },
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { returnData } = response
        commit('SET_TOKEN', returnData.Token)
        commit('SET_UserType', returnData.UserType)
        commit('SET_UserId', returnData.UserId)
        commit('SET_LOGIN', returnData.FirstLogin)
        sessionStorage.setItem("userName", userInfo.LoginName);
        sessionStorage.setItem("token", returnData.Token);
        setToken(TokenKey, returnData.Token);
        setToken('FirstLogin', returnData.FirstLogin);
        setUserId(returnData.UserId)
        let nowDate = new Date();
        let oldDate = new Date(returnData.ValidTime);
        let diffTime = oldDate - nowDate;
        setTimeout(function () {
          resetToken()
        }, diffTime)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {

      let data = {
        roles: state.userPoewrList,
        introduction: '',
        avatar: '',
        firstLogin: state.firstLogin,
        name: sessionStorage.getItem("userName"),
        token: state.token
      }

      const { name, avatar, roles, firstLogin } = data
      commit('SET_LOGIN', firstLogin)
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      commit('SET_ROLES', roles ? roles : ['admin'])
      resolve(data)
    })
  },

  // user logout
  logout ({ commit, state }) {
    console.log(state)
    return new Promise((resolve, reject) => {
      loginUp({ "UserId": state.UserId, "UserType": state.UserType }).then(result => {
        sessionStorage.removeItem("userName");
        sessionStorage.removeItem("UserType");
        sessionStorage.removeItem("User_Id");
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("userAuthList");
        removeToken(); // must remove  token  first
        removeToken('codeToken');
        removeToken('systemSet');
        removeToken('FirstLogin');
        removeToken('userAuthList');
        resetRouter();
        commit('RESET_STATE');
        commit('SET_ROLES', []);
        resolve();
      })

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

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      commit('SET_ROLES', [])
      resolve()
    })
  },
  setPowerList ({ commit }, arr) {
    commit('SET_UserPoewrList', arr);
  }
}

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

