import { changeAdminAvatar, getAdminInfo } from '@/api/admin'

const state = {
  adminInfo: {},
  isAdminEditDlgExist: false
}

const getters = {
  adminInfo(state) {
    return state.adminInfo
  },
  isAdminEditDlgExist(state) {
    return state.isAdminEditDlgExist
  }
}

const mutations = {
  SET_ADMIN_INFO: (state, payload) => {
    state.adminInfo = payload
  },
  TOGGLE_EDIT_DLG: (state, value) => {
    state.isAdminEditDlgExist = value
  },
  SET_AVATAR: (state, value) => {
    state.adminInfo.headerImg = value
  }
}

const actions = {
  initAdminInfo({ commit }, isShowDialog) {
    return new Promise((resolve, reject) => {
      getAdminInfo().then((res) => {
        const data = res.data
        commit('SET_ADMIN_INFO', data)
        // 显示编辑弹窗
        if (isShowDialog) {
          commit('TOGGLE_EDIT_DLG', true)
        }
        resolve(data)
      }).catch((error) => {
        reject(error)
      })
    })
  },

  updateAvatar({ commit }, payload) {
    return new Promise((resolve, reject) => {
      changeAdminAvatar({ headImg: payload.saveName }).then((res) => {
        const data = res.data
        commit('SET_AVATAR', payload.fileName)
        resolve(data)
      }).catch((error) => {
        console.log('error:', error)
        reject(error)
      })
    })
  }
}

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