import { getAllRoles,addRole,updateRole,deleteRole } from '@/api/role'
import store from '../index'


const state = {
  allRoles:[]
}

const mutations = {
  SET_ALL_ROLES:(state,roles)=>{
    console.log('save all roles ',roles)
    state.allRoles=roles
  }
}

const actions = {
  getAllRoles({ commit }) {
    console.log('start to get all roles 1')
    return new Promise((resolve,reject)=>{
      getAllRoles().then(res=>{

        console.log(' get all roles',res)
        if(res.data.success)
        {
          commit('SET_ALL_ROLES',res.data.data)
        }
        resolve(res)
      }).catch(error=>{

        console.log('get all roles faild!!!')
        reject(error)
      })
    })
  },
  addRole({commit},data)
  {
    console.log('start to add role1',data)
    return new Promise((resolve,reject)=>{
      addRole(data).then(res=>{
        console.log('start to add role2',res)
        resolve(res)
      }).catch(error=>{
        console.log('add role failed!',data)
        reject(error)
      })
    })
  },
  updateRole({commit},data){
    console.log('start to update role1',data)
    var authorities=new Array();
    console.log('allAuth',store.getters.allAuthorities)
    for(var i in  store.getters.allAuthorities)
    {
      for(var j in data.authorities){
        if(store.getters.allAuthorities[i].name==data.authorities[j])
        {
          authorities.push(store.getters.allAuthorities[i])
        }
      }
    }
    data.authorities=authorities

    console.log('authList',authorities)
    return new Promise((resolve,reject)=>{
      updateRole(data).then(res=>{
        console.log('start to update role2',data)
        resolve(res)
      }).catch(error=>{
        console.log('update role failed!')
        reject(error)
      })
    })
  },
  deleteRole({commit},data){
    console.log('start to delete role',data)
    return new Promise((resolve,reject)=>{
    deleteRole(data).then(res=>{
       console.log('start to delete role',data)
        resolve(res)


    }).catch(error=>{
      console.log('delete role failed!',data)
        reject(error)
    })
  })
  },
}

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