import ajax from '../../util/ajax'
import api from '../../util/api'

export default {
  namespaced: true,
  state: {
    roleList: [],
    roleInfo: {},
    roleMenus: [],
  },
  mutations: {
    updateList (state, payload) {
      state.roleList = payload || []
    },
    updateInfo (state, payload) {
      state.roleInfo = payload || {}
    },
    updateRoleMenus (state, payload) {
      state.roleMenus = payload || {}
    },
  },
  actions: {
    GetRolesList ({ commit }, payload) {
      ajax(api.role.list.url, {
        method: api.role.list.method,
        queryData: {
          ...payload,
        }
      }).then(res => {
        commit('updateList', res)
      })
    },
    GetRoleByID ({ commit }, { roleid }) {
      ajax(api.role.info.url, {
        method: api.role.info.method,
        urlData: {
          id: roleid,
        }
      }).then(res => {
        commit('updateInfo', res)
      })
    },
    AddRole ({ commit }, payload) {
      ajax(api.role.add.url, {
        method: api.role.add.method,
        data: {
          ...payload
        }
      }).then(res => {
        commit('updateInfo', res)
        if (payload.callback) {
          payload.callback()
        }
      })
    },
    UpdateRole ({ commit }, payload) {
      ajax(api.role.update.url, {
        method: api.role.update.method,
        data: {
          ...payload
        }
      }).then(res => {
        if (payload.callback) {
          payload.callback()
        }
      })
    },
    DelRole ({ commit }, { id, callback }) {
      ajax(api.role.delete.url, {
        method: api.role.delete.method,
        urlData: {
          id: id,
        }
      }).then(res => {
        callback()
      })
    },
    SetRoleNull ({ commit }) {
      commit('updateInfo', {})
    },
    GetRoleMenu ({ commit }, payload) {
      return new Promise((resolve, reject) => {
        ajax(api.role.getmenus.url, {
          method: api.role.getmenus.method,
          urlData: {
            id: payload.id,
          },
        }).then(res => {
          commit('updateRoleMenus', res)
          resolve(res)
        }).catch(reject)
      })
    },
    SaveRoleMenus ({ commit }, payload) {
      ajax(api.role.savemenu.url, {
        method: api.role.savemenu.method,
        urlData: {
          id: payload.id,
        },
        data: {
          menuids: payload.menuids
        }
      }).then(res => {
        payload.callback()
      })
    },
  }
}
