import {
  login,
} from '../../api/user'
import {getBaseInfo} from '@/api/baseInfo'
import {
  getToken,
  setToken,
  clearStorage,
  getCompanyId,
  setCompanyId,
} from '../../utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  companyId: getCompanyId(),
  introduction: '',
  roles: [],
  baseInfo: {}
}

const mutations = {
  // 设置基础信息
  SET_BASE_INFO: (state,baseInfo) => {
    state.baseInfo = {...baseInfo};
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_COMPANY: (state, companyId) => {
    state.companyId = companyId
  }
}

const actions = {
  login(_, userInfo) {
    
    const {
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        userKind: 'OPERATOR',
        domainName: 'YLYY'
      })
        .then(response => {
          const {
            data
          } = response
          setCompanyId(data.compId)
          // setToken()
          setToken('Admin-Token')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  logout({
    commit,
  }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_COMPANY', '')
      commit('SET_ROLES', [])
      clearStorage();
      resolve()
    })
  },
  async getBaseInfo({commit}){
    // debugger
    let baseInfo = await getBaseInfo();
    console.info(baseInfo)
    if (baseInfo.code==200){
      commit('SET_BASE_INFO',baseInfo.data)
    }
  }
}

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