import { login, logout, getInfo } from '@/api/user'
import { getJson } from '@/api/common'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'
import Cookies from 'js-cookie'

const state = {
  token: getToken(),
  name: '',
  avatar: '',

  dashchartid: '',
  dashchartidisedit: '',

  roles: [],
  buttons: [],
}

const mutations = {
  SET_DASHCHARTID: (state, dashchartid) => {
    state.dashchartid = dashchartid
  },
  SET_DASHCHARTIDISEDIT: (state, dashchartidisedit) => {
    state.dashchartidisedit = dashchartidisedit
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
    Cookies.set('pageCount', 50)
    Cookies.set('username', username)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  ST_DOWNLIST: (state, downlist) => {
    state.downlist = downlist
    sessionStorage.setItem('downlist', JSON.stringify(downlist))
  },

  SET_BUTTONS: (state, buttons) => {
    Cookies.set('buttons', buttons)
    sessionStorage.setItem('buttons', JSON.stringify(buttons))
    state.buttons = buttons
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ user_name: username.trim(), password: password }).then(response => {
        const { data, msg } = response
        commit('SET_USERNAME', userInfo.username)
        if (msg !== 'ok') {
          Message({ message: data, type: 'error', duration: 5 * 1000  })
          reject(data)
        }
        commit('SET_TOKEN', data.token)
        if (Cookies == null) {
          console.log(1)
        }
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, username, avatar } = data
        if (!roles || roles.length <= 0) {
          reject('该用户未授权，请联系管理员！')
          return false
        }
        let url = 'api/v1/ops/forage/enum/list'
        let datas = ''
        getJson(url, datas).then(response => {
          commit('ST_DOWNLIST', response.data)
        })
        commit('SET_ROLES', roles)
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_BUTTONS', [])
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        sessionStorage.clear()
        removeToken()
        resetRouter()
        resolve()
        location.reload()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

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