import {
  login,
  logout
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getCookies,
  setCookies,
  removeCookies
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'
import $router from '@/router'
const userInfoKey = 'userInfo'
const rolesKey = 'roles'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    checked: '',
    userInfo: getCookies(userInfoKey) ? JSON.parse(getCookies(userInfoKey)) : {},
    roles: getCookies(rolesKey) ? JSON.parse(getCookies(rolesKey)) : []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  getAdmin: (state, data) => {
    state.checked = data
  }
}

const actions = {
  getAdmin: (state, data) => {
    state.checked = data
  },
  // 登录
  ActionLogin({ commit }, userInfo) {
    const { username: account } = userInfo
    login({ account, ...userInfo }).then(res => {
      if (res?.data) {
        const { token, userInfo } = res?.data
        commit('SET_TOKEN', token)
        commit('SET_USER_INFO', userInfo)
        const roleId = userInfo.roleId
        let roles = []
        if (roleId === 0) {
          roles = ['admin']  //超级管理员
        } else if (roleId === 1) {
          roles = ['salesman']  //业务管理员
        } else if (roleId === 999) {
          roles = ['supplier']  //供应商
        }
        commit('SET_ROLES', roles)

        setToken(token)
        setCookies(userInfoKey, userInfo)
        setCookies(rolesKey, roles)
        $router.push({
          path: '/contracts'
        })
      }
    })
  },
  // 获取用户信息
  ActionUserInfo({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      const userInfo = getCookies(userInfoKey)
      if (Object.keys(state.userInfo).length > 0) {
        resolve(state.userInfo)
      } else if (userInfo) {
        resolve(userInfo)
      } else {
        reject()
      }
    })
  },
  // 退出登录
  ActionLogout({ commit, dispatch }) {
    removeToken() // must remove  token  first
    removeCookies(userInfoKey)
    removeCookies(rolesKey)
    resetRouter()

    commit('SET_TOKEN', '')
    commit('SET_USER_INFO', {})
    commit('SET_ROLES', [])
    $router.push({ path: '/login' })
  },

  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password,
      loginType
    } = userInfo
    new Promise((resolve, reject) => {
      login({
        account: username.trim(),
        password: password,
        loginType: loginType
      }).then(response => {
        const {
          data
        } = response
        console.log('2', data)
        commit('SET_TOKEN', data)
        setToken(data)
        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) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

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

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      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')
      resolve()
    })
  }
}

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