import {
  getSetting,
  setSetting
} from '@/api/system/index'

const state = {
  setting: []
}

const mutations = {
  CHANGE_SETTING: (state, setting) => {
    state.setting = setting
  }
}

const actions = {
  get({ commit }) {
    return new Promise((resolve, reject) => {
      getSetting().then(res => {
        try {
          const { message, code } = res
          if (code === 200) {
            const { data } = res
            commit('CHANGE_SETTING', data)
            resolve(data)
          } else {
            reject(message)
          }
        } catch (e) {
          let message = res.message ? res.message : e.message
          message = e.message ? e.message : '请求失败'
          reject(message)
        }
      })
    })
  },
  set({ dispatch }, keys) {
    return new Promise((resolve, reject) => {
      setSetting({ keys }).then(res => {
        try {
          const { message, code } = res
          if (code === 200) {
            dispatch('get')
            resolve(res)
          } else {
            reject(message)
          }
        } catch (e) {
          let message = res.message ? res.message : e.message
          message = e.message ? e.message : '请求失败'
          reject(message)
        }
      })
    })
  }
}

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