import { resolve } from 'path'
import { hasPermission } from '@/utils/permission'
import { isExternal } from 'vue-plugin-utils'
import { recordRoute } from '@/config'
import qs from 'qs'

import icon from '../views/403.vue'

/**
 * @description all模式渲染后端返回路由,支持包含views路径的所有页面
 * @param asyncRoutes
 * @returns {*}
 */
export function convertRouter(asyncRoutes) {
  return asyncRoutes.map((route) => {
    if (route.meta.title == '商品' && route.name == 'Vab320') {
      const obj = {
        path: '/goodsTool',
        component: '@/views/product/goodsTool/index',
        name: 'Vab88000',
        redirect: null,
        meta: {
          title: '商品映射配置',
          icon: '',
          noClosable: 0,
          hidden: null,
        },
        menuHidden: false,
      }

      route.children.splice(0, 0, obj)
    }
    
    if (route.meta.title == '店铺' && route.name == 'Vab330') {
      const obj = {
        path: '/shopAudit',
        component: '@/views/store/shopAudit/shopAudit',
        name: 'Vab83000',
        redirect: null,
        meta: {
          title: '商家入驻审批',
          icon: '',
          noClosable: 0,
          hidden: null,
        },
        menuHidden: false,
      }

      route.children.splice(0, 0, obj)
    }

    if (route.meta.title == '设置') {
      const obj = {
        path: '/receiptMachine',
        component: '@/views/settings/config/receiptMachine',
        name: 'Vab86001',
        redirect: null,
        meta: {
          title: '小票机品牌',
          icon: '',
          noClosable: 0,
          hidden: null,
        },
        menuHidden: false,
      }

      route.children.push(obj)
    }

    if (route.meta.title == '基础') {
      const cloudPrintRoute = {
        path: '/cloudPrint',
        name: 'Vab81000',
        component: '@/views/vab/icon',
        redirect: null,

        meta: {
          title: '云打印',
          icon: '',
          noClosable: 0,
          hidden: null,
        },
        menuHidden: false,
        children: [
          {
            path: '/plotterManager',
            component: '@/views/store/base/cloudPrint/plotterManager',
            name: 'Vab81001',
            redirect: null,
            meta: {
              title: '打印机管理',
              icon: '',
              noClosable: 0,
              hidden: null,
            },
            menuHidden: false,
          },
          {
            path: '/addCloudPrint',
            component: '@/views/store/base/cloudPrint/editCloudPrint',
            name: 'Vab81002',
            redirect: null,
            meta: {
              title: '添加打印机',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
          {
            path: '/editCloudPrint',
            component: '@/views/store/base/cloudPrint/editCloudPrint',
            name: 'Vab81003',
            redirect: null,
            meta: {
              title: '编辑打印机',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
          {
            path: '/templateManagement',
            component: '@/views/store/base/cloudPrint/templateManagement',
            name: 'Vab81004',
            redirect: null,
            meta: {
              title: '模板管理',
              icon: '',
              noClosable: 0,
              hidden: null,
            },
            menuHidden: false,
          },
          {
            path: '/templateManagementAdd',
            component: '@/views/store/base/cloudPrint/editTemplateManagement',
            name: 'Vab81005',
            redirect: null,
            meta: {
              title: '添加模板',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
          {
            path: '/templateManagementEdit',
            component: '@/views/store/base/cloudPrint/editTemplateManagement',
            name: 'Vab81006',
            redirect: null,
            meta: {
              title: '编辑模板',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
        ],
      }

      const distributionSetup = {
        path: '/distributionSetup',
        name: 'Vab82000',
        component: '@/views/vab/icon',
        redirect: null,

        meta: {
          title: '配送设置',
          icon: '',
          noClosable: 0,
          hidden: null,
        },
        menuHidden: false,
        children: [
          {
            path: '/distributionMode',
            component: '@/views/store/base/distributionSetup/distributionMode',
            name: 'Vab82001',
            redirect: null,
            meta: {
              title: '配送方式',
              icon: '',
              noClosable: 0,
              hidden: null,
            },
            menuHidden: false,
          },
          {
            path: '/logisticsInterface',
            component:
              '@/views/store/base/distributionSetup/logisticsInterface',
            name: 'Vab82002',
            redirect: null,
            meta: {
              title: '物流接口',
              icon: '',
              noClosable: 0,
              hidden: null,
            },
            menuHidden: false,
          },
          {
            path: '/localDelivery',
            component: '@/views/store/base/distributionSetup/localDelivery',
            name: 'Vab82003',
            redirect: null,
            meta: {
              title: '同城配送',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
          {
            path: '/selfPickUpSite',
            component: '@/views/store/base/distributionSetup/selfPickUpSite',
            name: 'Vab82004',
            redirect: null,
            meta: {
              title: '自提点列表',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
          {
            path: '/selfPickUpSiteAdd',
            component:
              '@/views/store/base/distributionSetup/editSelfPickUpSite',
            name: 'Vab82005',
            redirect: null,
            meta: {
              title: '编辑自提点',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
          {
            path: '/selfPickUpSiteEdit',
            component:
              '@/views/store/base/distributionSetup/editSelfPickUpSite',
            name: 'Vab82006',
            redirect: null,
            meta: {
              title: '编辑自提点',
              icon: '',
              noClosable: 0,
              hidden: true,
            },
            menuHidden: false,
          },
        ],
      }
      route.children.push(...[cloudPrintRoute, distributionSetup])
      route.children = route.children.filter((item) => item.name != 'Vab8083')
    }

    if (route.meta.title == '设置' && route.name == 'Settings') {
      const obj = {
        path: '/appVersion',
        component: '@/views/settings/config/appVersion',
        name: 'Vab9019',
        redirect: null,
        meta: {
          title: '商家APP设置',
          icon: '',
          noClosable: 0,
          hidden: null,
        },
        menuHidden: false,
      }

      route.children.splice(0, 0, obj)
    }

    if (route.meta.title == '订单' && route.name == 'Vab350') {
      const obj = {
        path: '/orderPush',
        component: '@/views/order/orderPush/orderPush',
        name: 'Vab8088',
        redirect: null,
        meta: {
          title: '个推订单测试',
          icon: '',
          noClosable: 0,
          hidden: null,
        },
        menuHidden: false,
      }
      route.children.splice(0, 0, obj)
    }

    if (route.component) {
      if (route.component === 'Layout') {
        route.component = (resolve) => require(['@/vab/layouts'], resolve)
      } else {
        const index = route.component.indexOf('views')
        const path =
          index > 0 ? route.component.slice(index) : `views/${route.component}`
        route.component = (resolve) => require([`@/${path}`], resolve)
      }
    }
    if (route.children && route.children.length)
      route.children = convertRouter(route.children)
    if (route.children && route.children.length === 0) delete route.children
    return route
  })
}

/**
 * @description 根据roles数组拦截路由
 * @param routes 路由
 * @param rolesControl 是否进行权限控制
 * @param baseUrl 基础路由
 * @returns {[]}
 */
export function filterRoutes(routes, rolesControl, baseUrl = '/') {
  return routes
    .filter((route) =>
      rolesControl && route.meta && route.meta.guard
        ? hasPermission(route.meta.guard)
        : true
    )
    .map((route) => {
      route = { ...route }
      route.path =
        route.path !== '*' && !isExternal(route.path)
          ? resolve(baseUrl, route.path)
          : route.path
      if (route.children && route.children.length > 0) {
        route.children = filterRoutes(route.children, rolesControl, route.path)
        if (route.children.length > 0) {
          route.childrenNameList = route.children.flatMap(
            (_) => _.childrenNameList
          )
          if (!route.redirect)
            route.redirect = route.children[0].redirect
              ? route.children[0].redirect
              : route.children[0].path
        }
      } else route.childrenNameList = [route.name]
      return route
    })
}

/**
 * 根据path路径获取matched
 * @param routes 菜单routes
 * @param name 路由名
 * @returns {*} matched
 */
export function handleMatched(routes, name) {
  return routes
    .filter((route) => route.childrenNameList.indexOf(name) + 1)
    .flatMap((route) =>
      route.children ? [route, ...handleMatched(route.children, name)] : [route]
    )
}

/**
 * 生成单个多标签元素，可用于同步/异步添加多标签
 * @param tag route页信息
 */
export function handleTabs(tag) {
  let parentIcon = null
  if (tag.matched)
    for (let i = tag.matched.length - 2; i >= 0; i--)
      if (!parentIcon && tag.matched[i].meta.icon)
        parentIcon = tag.matched[i].meta.icon
  if (!parentIcon) parentIcon = 'menu-line'
  const path = handleActivePath(tag, true)
  if (tag.name && tag.meta && tag.meta.tabHidden !== true) {
    return {
      path: path,
      query: tag.query,
      params: tag.params,
      name: tag.name,
      parentIcon,
      meta: { ...tag.meta },
    }
  }
}

/**
 * 根据当前route获取激活菜单
 * @param route 当前路由
 * @param isTab 是否是标签
 * @returns {string|*}
 */
export function handleActivePath(route, isTab = false) {
  const { meta, path } = route
  const rawPath = route.matched
    ? route.matched[route.matched.length - 1].path
    : path
  const fullPath =
    route.query && Object.keys(route.query).length
      ? `${route.path}?${qs.stringify(route.query)}`
      : route.path
  if (isTab) return meta.dynamicNewTab ? fullPath : rawPath
  if (meta.activeMenu) return meta.activeMenu
  return fullPath
}

/**
 * 获取当前跳转登录页的Route
 * @param currentPath 当前页面地址
 */
export function toLoginRoute(currentPath) {
  if (recordRoute && currentPath !== '/')
    return {
      path: '/login',
      query: { redirect: currentPath },
      replace: true,
    }
  else return { path: '/login', replace: true }
}
