// import auth from '@/plugins/auth'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import InnerLink from '@/layout/components/InnerLink/index.vue'
import Cookies from 'js-cookie'
import _ from 'lodash'
import { getLocal, getSession } from '@/utils/auth'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../views/**/*.vue')

export const separateAndCreateRoutes = (responseRouteList) => {
  // 1.分离菜单和按钮
  let menus = [] // 菜单数组（排除按钮）
  let buttonsArr = [] // 所有按钮数组
  let buttons = [] // 根据按钮数组生成的全部按钮权限集合

  // 超级管理员admin的排除
  if (getSession('user_account') !== 'admin') {
    const popedomArr = _.uniq(window.atob(window.atob(getSession('popedom'))).split(','))

    //menu_type  1-目录  2-菜单  3-按钮
    menus = responseRouteList.filter((item, index) => {
      return popedomArr.includes(String(item.menu_id)) && item.menu_type !== 3
    })

    buttonsArr = responseRouteList.filter((item, index) => {
      return popedomArr.includes(String(item.menu_id)) && item.menu_type === 3
    })
  } else {
    menus = responseRouteList.filter((item, index) => {
      return item.menu_type !== 3
    })
    buttonsArr = responseRouteList.filter((item, index) => {
      return item.menu_type === 3
    })
  }

  buttonsArr.forEach((item, index) => {
    buttons.push(item.perms)
  })

  // console.log('buttons_promissions:', buttons);

  const rootMenu = getRootMenu(menus) // 2.生成路由结构
  // console.log('生成路由结构:', rootMenu)

  const routers = generator(rootMenu) // 3.生成路由配置格式（components未加载）
  // console.log('生成动态路由:', routers)

  // 复制菜单
  const sdata = JSON.parse(JSON.stringify(routers))
  const rdata = JSON.parse(JSON.stringify(routers))
  const defaultData = JSON.parse(JSON.stringify(routers))

  // 左侧菜单数组
  const sidebarRoutes = filterAsyncRouter(sdata)
  const rewriteRoutes = filterAsyncRouter(rdata, false, true)
  const defaultRoutes = filterAsyncRouter(defaultData)

  return {
    menus,
    buttonsAuth: buttons,
    sidebarRoutes,
    rewriteRoutes,
    defaultRoutes,
  }
}

/* 生成菜单树
 * rows       ajax获取的数据库菜单
 * rootMenu   生成的最初菜单
 */
export function getRootMenu(rows) {
  let rootMenu = []
  const arr = []
  const menus = []
  // 生成菜单树
  buildtree(rows, arr, 0)
  arr.forEach((row) => {
    menus.push(row)
  })

  // 按照order_num递归排序
  menus.sort((a, b) => {
    return a.sort - b.sort
  })

  rootMenu = menus
  return rootMenu
}

/**
 * 生成菜单树方法，调用自身
 * @param {*} list
 * @param {*} arr
 * @param {*} parentId
 */
export function buildtree(list, arr, parentId) {
  list.forEach((item) => {
    if (item.parent_id === parentId) {
      var child = {
        key: item.menu_id, // 菜单id
        title: item.menu_name, // 标题
        icon: item.icon, // 图标
        breadcrumb: item.hidden_header, // 是否显示在面包屑
        hidden: item.visible, // 是否显示在左侧菜单
        noCache: item.no_cache, // 是否缓存页面
        // alwaysShow: item.alwaysShow, // 是否始终显示
        path: item.path && item.path.length > 0 ? item.path : undefined, // path
        name: item.menu_key, //   routeName
        component: item.component, // 组件
        redirect: item.redirect, // 重定向地址
        activeMenu: item.active_menu, // 激活显示的菜单路由
        children: [],
        sort: item.order_num, // 排序
      }
      buildtree(list, child.children, item.menu_id)
      if (child.children.length === 0) {
        delete child.children
      }

      arr.push(child)
    }
  })
}

/**
 * 格式化 后端 结构信息并递归生成层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map((item) => {
    const currentRouter = {
      // 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
      // 该路由对应页面的 组件 优先根据组件名或者key从constantRouterComponents获取，没有则通过组件名地址查询
      component: item.component,
      // 左侧菜单显示
      hidden: !!item.hidden,
      // alowShow
      alwaysShow: !!item.alwaysShow,
      // redirect
      redirect: item.redirect || null,
      // meta
      meta: {
        icon: item.icon || '',
      },
    }

    // title
    if (item.title) {
      currentRouter.meta.title = item.title
    }

    // 单独处理defaultRouterMap中的首页
    if (item.meta?.title) {
      currentRouter.meta.title = item.meta.title
    }
    // icon
    if (item.meta?.icon) {
      currentRouter.meta.icon = item.meta.icon
    }

    // 面包屑显示
    if (item.breadcrumb) {
      currentRouter.meta.breadcrumb = item.breadcrumb
    }

    // 是否缓存
    if (item.noCache) {
      currentRouter.meta.noCache = item.noCache
    }

    // 当前激活的菜单路由
    if (item.activeMenu) {
      // /community-manage/community-manage  => /communitymanage/communitymanage 去掉-
      const newMenu = _.replace(item.activeMenu, /-/g, '')
      currentRouter.meta.activeMenu = newMenu
    }

    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }

    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }

    // console.log(currentRouter)
    return currentRouter
  })
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === '/layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach((c) => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  let res
  for (const path in modules) {
    const dir = path.split('views')[1].split('/index.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

/**
 * 将api接口返回的菜单数据进行转换
 * @param {*} apiMenus
 */
export const reformateMenuData = (apiMenus) => {
  let newMenus = []

  newMenus = apiMenus
  // apiMenus.forEach((item, index) => {
  //   newMenus.push({
  //     component: item.component,
  //     menuHidden: item.visible !== 0,
  //     breadcrumb: item.hidden_header !== 0,
  //     noCache: item.no_cache !== 0,
  //     icon: item.icon,
  //     menuId: item.menu_id,
  //     menuKey: item.menu_key,
  //     menuName: item.menu_name,
  //     parentId: item.parent_id,
  //     path: item.path,
  //     redirect: item.redirect,
  //     activeMenu: item.active_menu,
  //     menuType: item.menu_type,
  //     orderNum: item.order_num,
  //     perms: item.perms,
  //     remark: item.remark
  //   })
  // })
  return newMenus
}

/**
 * 构造树型结构数据
 * @param {*} source 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export const buildTreeData = (source, id, parentId, children, rootId, bodt) => {
  id = id || 'id'
  parentId = parentId || 'parent_id'
  children = children || 'children'
  rootId = rootId || 0
  const cloneData = JSON.parse(JSON.stringify(source)) // 对源数据深度克隆
  return cloneData.filter((father) => {
    // console.log(father[parentId], 'father[parentId]')
    const branchArr = cloneData.filter((child) => father[id] === child[parentId]) // 返回每一项的子级数组
    branchArr.length > 0 ? (father[children] = branchArr) : delete father[children] // 如果存在子级，则给父级添加一个children属性，并赋值
    return bodt || father[parentId] === rootId // 返回第一层
  })
}
