import { getToken, setToken, removeToken, setUserId, TokenKey } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Query } from "@/api/webApi"
import { isValue } from "@/utils/validate"
import { getAuth, signIn, loginOut } from '@/api/login'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    isLogin: false,
    roles: [],
    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')) : [],
    // userPoewrList: sessionStorage.setItem('userAuthList') ? JSON.parse(sessionStorage.getItem('userAuthList')) : []
    userChecked: !!sessionStorage.getItem('userChecked')
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_LOGIN: (state, login) => {
    state.isLogin = login
  },
  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_USER_CHECKED (state, flag) {
    state.userChecked = flag
    if (flag) {
      sessionStorage.setItem('userChecked', 1)
    } else {
      sessionStorage.clearItem('userChecked')
    }
  }
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      signIn(userInfo)
        .then(response => {
          if (response.code == 0 && isValue(response.returnData)) {
            const { user_token, user_id } = response.returnData
            commit('SET_TOKEN', user_token)
            commit('SET_UserType', 1)
            commit('SET_UserId', user_id)
            setToken('userName', userInfo.username)
            setToken(TokenKey, user_token)
            setUserId(user_id)
            setToken('userid', user_id)
            resolve(true)
          } else {
            reject(false)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  getMenuInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      Query({
        serviceId: SERVICE_ID.sysAuthId,
        dataContent: [{ user_id: getToken('userid') }],
        page: 1,
        pageSize: 999,
        event: '0'
      })
        .then((res) => {
          if (res.code == 0 && isValue(res.returnData)) {
            commit('SET_ROLES', ['admin'])
            resolve(res.returnData)
          } else {
            reject(res.returnData)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout ({ commit }) {
    return new Promise((resolve, reject) => {
      loginOut({
        user_id: getToken('userid'),
        user_token: getToken(TokenKey)
      }).then(result => {
        if (result) {
          sessionStorage.clear()
          removeToken() // must remove  token  first
          removeToken('codeToken')
          removeToken('systemSet')
          removeToken('userid')
          resetRouter()
          commit('RESET_STATE')
          commit('SET_ROLES', [])
          resolve(true)
        } else {
          reject(false)
        }
      })
    })
  },

  // 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)
  },

  setPowerToken ({ commit }, token) {
    commit('SET_TOKEN', token)
  },

  setPowerName ({ commit }, name) {
    commit('SET_NAME', name)
  },

  setIsLogin ({ commit }, login) {
    commit('SET_LOGIN', login)
  },

  setUserChecked ({ commit }, flag) {
    commit('SET_USER_CHECKED', flag)
  }
}

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