import { login, logout, getInfo, createUser, getAllUsers, deleteUser, updateUser, updateUserPassword } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import logoImg from '@/assets/logo.png'
import store from '../index'
const state = {
  token: getToken(),
  name: '',
  username: '',
  avatar: logoImg,
  introduction: '',
  roles: [],
  allUsers: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ALL_USERS: (state, allUsers) => {
    state.allUsers = allUsers
  },
  SET_USER_NAME: (state, username) => {
    console.log('SET_USER_NAME', username)
    state.username = username
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    console.log('SET_ROLES', roles)
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        // const { data } = response.data
        console.log('res', response)

        console.log('token', response.headers.authorization)
        // commit('SET_TOKEN', data.token)
        commit('SET_TOKEN', response.headers.authorization)
        commit('SET_USER_NAME', response.data.username)
        // commit('SET_ROLES', response.data.roles)

        // store.dispatch('permission/generateRoutes', state.roles)
        // setToken(data.token)
        setToken(response.headers.authorization)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       // const { data } = response.data
  //       console.log('res', response)

  //       if (process.env.NODE_ENV === 'development') {
  //         console.log('[Token In Dev]', response.data)

  //         commit('SET_TOKEN', response.data.token)
  //         commit('SET_USER_NAME', response.data.username)
  //         setToken(response.data.token)
  //         console.log('[Save Token]')
  //       } else {
  //         console.log('token', response.headers.authorization)
  //         // commit('SET_TOKEN', data.token)
  //         commit('SET_TOKEN', response.headers.authorization)
  //         commit('SET_USER_NAME', response.data.username)
  //         // commit('SET_ROLES', response.data.roles)

  //         // store.dispatch('permission/generateRoutes', state.roles)
  //         // setToken(data.token)
  //         setToken(response.headers.authorization)
  //       }

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

  deleteUser({ commit }, username) {
    console.log('start to delete user', username)
    return new Promise((resolve, reject) => {
      deleteUser(username).then(res => {
        console.log('delete user res', res)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  updateUserPassword({ commit }, data) {
    console.log('start to update user password ', data)
    return new Promise((resolve, reject) => {
      updateUserPassword(data).then(res => {
        console.log('update user pass word res', res)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  updateUser({ commit }, data) {
    console.log('start to update user1', data)
    // eslint-disable-next-line no-array-constructor
    var sysRoles = new Array()
    console.log('allRoles', store.getters.allRoles)
    for (var i in store.getters.allRoles) {
      for (var j in data.sysRoles) {
        // eslint-disable-next-line eqeqeq
        if (store.getters.allRoles[i].name == data.sysRoles[j]) {
          sysRoles.push(store.getters.allRoles[i])
        }
      }
    }
    data.sysRoles = sysRoles

    console.log('update user ', data)
    return new Promise((resolve, reject) => {
      updateUser(data).then(res => {
        console.log('update user2', data)
        resolve(res)
      }).catch(error => {
        console.log('update user failed!')
        reject(error)
      })
    })
  },
  createUser({ commit, state }, user) {
    return new Promise((resolve, reject) => {
      console.log('start to create user', user)
      createUser(user).then(res => {
        console.log('create user res', res.data)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getAllUsers({ commit }) {
    return new Promise((resolve, reject) => {
      console.log('start to get all users')
      getAllUsers().then(res => {
        console.log('all users', res.data)
        if (res.data.success) {
          // console.log('start to save all users ')
          commit('SET_ALL_USERS', res.data.data)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },

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

        // const { roles, name, avatar, introduction } = data
        const { roles, name, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    console.log('start to logout 1')
    return new Promise((resolve, reject) => {
      logout().then(() => {
        console.log('start to logout 2')
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        console.log(state.username + ' logout!')

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        console.log('error', error)
        reject(error)
      })
    })
  },

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

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

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