import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken ,getIsCertification,setIsCertification,removeIsCertification,getReportSerialNumber} from '@/utils/auth'


const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    role: 0,
    openItem: [],
    sysActiveFlag: getIsCertification(),
    userInfo: '',
    ReportSerialNumber: getReportSerialNumber(),
    searchValue:'first',
  }
}

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_ROLE: (state, role) => {
    state.role = role
  },
  SET_OPENITEM: (state, openItem) => {
    state.openItem = openItem
  },
  SET_SEARCHVALUE: (state, searchValue) => {
    state.searchValue = searchValue
  },
  SET_ACTIVEFLAG: (state, sysActiveFlag) => {
    state.sysActiveFlag = sysActiveFlag
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, isCertification} = userInfo
    return new Promise((resolve, reject) => {
      var token ={
        username:username,
        password:password,
        isCertification:isCertification
      }
      commit('SET_TOKEN', token)
      setIsCertification(isCertification)
      setToken(token)
      resolve()
    })
  },
  active({ commit },data) {
    return new Promise((resolve, reject) => {
      commit('SET_ACTIVEFLAG', data)
      resolve()
    })
  },
  setUserInfo({ commit },data) {
    return new Promise((resolve, reject) => {
      commit('SET_USERINFO', data)
      resolve()
    })
  },
  setOpenList({ commit },data) {
    return new Promise((resolve, reject) => {
      commit('SET_OPENITEM', data)
      resolve()
    })
  },
  setSearchValue({ commit },data) {
    return new Promise((resolve, reject) => {
      commit('SET_SEARCHVALUE', data)
      resolve()
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

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

