/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { loginByUsername, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { setName, removeName } from '@/utils/username'
import { removeEnvironment } from '@/utils/environment'
import { removeCsrfToken } from '@/utils/csrfToken'
import { Message } from 'element-ui'
import { setTenant, removeTenant } from '../../utils/tenant'
import { getUserInfo } from '@/api/users'
import { loginByCasdoor } from '../../api/login'

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          if (response.data.hasOwnProperty('error') && response.data.error.length >= 0) {
            Message({
              message: 'The username or password is incorrect',
              type: 'error',
              duration: 5 * 1000
            })
            reject('login error')
          }
          commit('SET_TOKEN', response.headers.token)
          setToken(response.headers.token)
          setName(response.headers.username)
          setTenant(response.headers.tenant)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    LoginByCasdoor({ commit }, code, state) {
      return new Promise((resolve, reject) => {
        loginByCasdoor(code, state).then(response => {
          if (response.data.hasOwnProperty('error') && response.data.error.length >= 0) {
            reject('login error')
          }
          commit('SET_TOKEN', response.headers.token)
          setToken(response.headers.token)
          setName(response.headers.username)
          setTenant(response.headers.tenant)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          commit('SET_ROLES', response.data.roles)
          commit('SET_NAME', 'admin')
          commit('SET_INTRODUCTION', 'Pulsar Manager')
          resolve(response)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          removeCsrfToken()
          removeName()
          removeTenant()
          removeEnvironment()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        removeName()
        removeTenant()
        removeEnvironment()
        resolve()
      })
    },

    SetEnvironment({ commit }, environment) {
      return new Promise(resolve => {
        commit('ENVIRONMENT', environment)
      })
    },

    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        // getUserInfo(role).then(response => {
        //   const data = response.data
        //   commit('SET_ROLES', data.roles)
        //   commit('SET_NAME', data.name)
        //   commit('SET_AVATAR', data.avatar)
        //   commit('SET_INTRODUCTION', data.introduction)
        //   dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
        //   resolve()
        // })
      })
    }
  }
}

export default user
