import { login, getInfo } from '@/api/doctor'
import { getToken, setToken, removeToken } from '@/utils/auth'
import axios from 'axios';
import { status } from 'nprogress';

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    userId: null
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_HOSPITAL: (state, hospital) => {
      state.hospital = hospital
    },
    SET_DOCTOR: (state, doctor) => {
      state.doctor = doctor
    },
    SET_DEPARTMENT: (state, department) => {
      state.department = department
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
    }
  },
  actions: {
     // 登录
    Login({ commit  }, userInfo) {
      const account = userInfo.account.trim()
      const password = userInfo.password
      const type = userInfo.type
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(account, password,type,code, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          // 设置请求头
          axios.defaults.headers.common['APPToken'] = res.token;
          commit('SET_DOCTOR',res.doctor)
          commit('SET_USER_ID', "D-"+res.doctor.doctorId)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        axios.defaults.headers.common['APPToken'] = state.token; // 设置请求头的值
        getInfo(state.token).then(res => {
          const doctor = res.doctor
          const avatar = doctor.avatar == "" ? require("@/assets/images/profile.jpg") : doctor.avatar;
          commit('SET_ROLES', ['ROLE_DEFAULT'])
          commit('SET_HOSPITAL', res.hospital)
          commit('SET_DEPARTMENT', res.department)
          commit('SET_NAME', doctor.doctorName)
          commit('SET_AVATAR', avatar)
          commit('SET_DOCTOR', res.doctor)
          commit('SET_USER_ID', "D-"+res.doctor.doctorId)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_USER_ID', null) // 清除用户ID
        removeToken()
        resolve()
      })
    },

    // 获取用户ID
    GetUserId({ state }) {
      return state.userId
    }
  }
}

export default user
