// import { getPermission, setPermission } from '@/utils/auth'
import {
  // getMenu2,
  saveMenu,
  saveMenuAll,
  deleteMenu
} from '@/api/menu'
import Routes from '@/router/routes'
const state = {
  refresh: true, // 更新路由
  roles: Routes.routes,
  permission: Routes.permission
}

const mutations = {
  SET_REFRESH (state, params) {
    state.refresh = params
  },
  SET_ROLES (state, route) {
    state.roles = route
    // setRoles(route)
  },
  SET_PERMISSION (state, permission) {
    state.permission = permission
    // setPermission(permission)
  }
}

const actions = {
  deleteMenu ({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      deleteMenu(params).then(res => {
        // 更新模块
        dispatch('getMenu2').then((route) => {
          resolve()
        }).catch(error => {
          reject(error)
        })
      }).catch(error => {
        reject(error)
      })
    })
  },
  saveMenu ({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      saveMenu(params).then(res => {
        // 更新模块
        dispatch('getMenu2').then((route) => {
          resolve()
        }).catch(error => {
          reject(error)
        })
      }).catch(error => {
        reject(error)
      })
    })
  },
  saveMenuAll ({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      saveMenuAll(params)
        .then(res => {
          // 更新home模块
          dispatch('getMenu2').then((route) => {
            // console.log(route)
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
        .catch(error => { reject(error) })
    })
  },
  getMenu2 ({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      const { routes, permission } = Routes
      commit('SET_ROLES', routes)
      commit('SET_PERMISSION', permission)
      // 路由重新配置触发更新
      commit('SET_REFRESH', true)
      resolve(routes)
      // getMenu2({}).then(response => {
      //   commit('SET_ROLES', response.data.routes)
      //   commit('SET_PERMISSION', response.data.permission)
      //   // 路由重新配置触发更新
      //   commit('SET_REFRESH', true)
      //   resolve(response.data.routes)
      // }).catch(err => { reject(err) })
    })
  }
}

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