import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
	workMenuList
} from '@/api/system/menu'

const baseUrl = config.baseUrl

const permission = {
	state: {
		permissions_menu: storage.get(constant.permissions_menu),
		permissions_btn: storage.get(constant.permissions_btn)
	},

	mutations: {
		SET_PERMISSIONS_MENU: (state, permissions) => {
			state.permissions_menu = permissions
			storage.set(constant.permissions_menu, permissions)
		},
		SET_PERMISSIONS_BTN: (state, permissions) => {
			state.permissions_btn = permissions
			storage.set(constant.permissions_btn, permissions)
		}
	},

	actions: {
		// 获取用户权限信息
		GetPermis({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				let sysId = [uni.getStorageSync('sysId')]
				workMenuList({
					sysId: sysId //平台端获取固定系统ID
				}).then(res => {
					let data = res.data;
					if (data && data.length > 0) {
						let permission=assembleRouter(data[0].menu)
						commit('SET_PERMISSIONS_MENU', JSON.stringify(permission.menu))
						commit('SET_PERMISSIONS_BTN', JSON.stringify(permission.btn))
					}
					resolve(data)
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}

//遍历后台传来的路由,组成路由树结构
function assembleRouter (allRouterMenu) {
  // 收集每一项的下标
  const idMapping = allRouterMenu.reduce((acc, el, i) => {
    acc[el.id] = i;
    return acc;
  }, {});
  let menu = [];
  let btn=[];
  allRouterMenu.forEach(el => {
    // 判断根节点
    if (el.paterId === null || el.paterId === 0) {
      menu.push(el)
      return;
    }
    // 用映射表找到父元素
    const parentEl = allRouterMenu[idMapping[el.paterId]];
    // 把当前元素添加到父元素的`children`数组中
    if (parentEl&&el.type !== 3) { //非按钮，组成路由树结构
      parentEl.children = [...(parentEl.children || []), el];
    }else{
		btn.push(el.code)
	}
  });
  return {
	  menu:menu,
	  btn:btn
  }
}

export default permission
