/**
 * 1. 前端维护的完整路由表, 用于创建"菜单"
 * 2. component 是 string，并不是 组件对象。
 * 3. 生成菜单，关注的 path，name，component，icon。
 * 4. 部分路由组件是菜单不可见的，当访问该路由时，左侧菜单的menu item会失去active状态。需要设置 meta.activeMenu 保持选中状态。
 */
import { AppRouteRecordRaw } from './types';
import { getTreeItem } from '@/utils';
import { cloneDeep } from 'lodash-es';
import { RouteRecordRaw } from 'vue-router';
import { PageEnum } from '@/enums/pageEnum';

type RouteRecordString = Omit<AppRouteRecordRaw, 'component'> & { component?: string };

export const RootRoute: RouteRecordString = {
  path: '/',
  name: 'Root',
  redirect: PageEnum.BASE_HOME,
  meta: {
    title: 'Root',
  },
};

export const HOME_PAGE: RouteRecordString = {
  // 模板管理
  path: '/home',
  name: 'HomePage',
  component: '/home/PageHome',
  meta: {
    icon: '',
    title: '公司主页',
  },
};

/** 灾害防范的路由 */
export const disasterPreventionRoute = {
  children: [
    {
      component: '/todo/todo',
      id: 1025,
      meta: {
        activeMenu: null,
        alwaysShow: false,
        frameSrc: '',
        hidden: false,
        icon: 'DashboardOutlined',
        isFrame: 0,
        isRoot: false,
        noCache: false,
        query: '',
        title: '总览',
      },
      name: '/disaster-prevention/overview',
      parentId: 1022,
      path: 'overview',
      redirect: '',
    },
    {
      component: '/todo/todo',
      id: 1026,
      meta: {
        activeMenu: null,
        alwaysShow: false,
        frameSrc: '',
        hidden: false,
        icon: '',
        isFrame: 0,
        isRoot: false,
        noCache: false,
        query: '',
        title: '重点区域监测',
      },
      name: '/disaster-prevention/risk-point-monitoring',
      parentId: 1022,
      path: 'risk-point-monitoring',
      redirect: '',
    },
    {
      component: '/todo/todo',
      id: 1027,
      meta: {
        activeMenu: null,
        alwaysShow: false,
        frameSrc: '',
        hidden: false,
        icon: '',
        isFrame: 0,
        isRoot: false,
        noCache: false,
        query: '',
        title: '灾害预警',
      },
      name: '/disaster-prevention/disaster-warning',
      parentId: 1022,
      path: 'disaster-warning',
      redirect: '',
    },
    {
      children: [
        {
          component: '/todo/todo',
          id: 1029,
          meta: {
            activeMenu: null,
            alwaysShow: false,
            frameSrc: '',
            hidden: false,
            icon: '',
            isFrame: 0,
            isRoot: false,
            noCache: false,
            query: '',
            title: '任务管理',
          },
          name: '/disaster-prevention/disaster-precaution/task-management',
          parentId: 1028,
          path: 'task-management',
          redirect: '',
        },
        {
          component: '/todo/todo',
          id: 1030,
          meta: {
            activeMenu: null,
            alwaysShow: false,
            frameSrc: '',
            hidden: false,
            icon: '',
            isFrame: 0,
            isRoot: false,
            noCache: false,
            query: '',
            title: '任务执行',
          },
          name: '/disaster-prevention/disaster-precaution/task-execution',
          parentId: 1028,
          path: 'task-execution',
          redirect: '',
        },
        {
          component: '/todo/todo',
          id: 1031,
          meta: {
            activeMenu: null,
            alwaysShow: false,
            frameSrc: '',
            hidden: false,
            icon: '',
            isFrame: 0,
            isRoot: false,
            noCache: false,
            query: '',
            title: '任务模板',
          },
          name: '/disaster-prevention/disaster-precaution/task-template',
          parentId: 1028,
          path: 'task-template',
          redirect: '',
        },
      ],
      component: '/todo/todo',
      id: 1028,
      meta: {
        activeMenu: null,
        alwaysShow: false,
        frameSrc: '',
        hidden: false,
        icon: '',
        isFrame: 0,
        isRoot: false,
        noCache: false,
        query: '',
        title: '预防检查',
      },
      name: '/disaster-prevention/disaster-precaution',
      parentId: 1022,
      path: 'disaster-precaution',
      redirect: '',
    },
    {
      component: '/todo/todo',
      id: 1032,
      meta: {
        activeMenu: null,
        alwaysShow: false,
        frameSrc: '',
        hidden: false,
        icon: '',
        isFrame: 0,
        isRoot: false,
        noCache: false,
        query: '',
        title: '灾害处置',
      },
      name: '/disaster-prevention/disaster-control',
      parentId: 1022,
      path: 'disaster-control',
      redirect: '',
    },
  ],
  component: 'MENU_LAYOUT',
  id: 1022,
  meta: {
    activeMenu: null,
    alwaysShow: false,
    frameSrc: '',
    hidden: false,
    icon: 'CameraOutlined',
    isFrame: 0,
    isRoot: false,
    noCache: false,
    query: '',
    title: '灾害防范',
    ignoreAuth: false,
  },
  name: 'DisasterPrevention',
  parentId: -1,
  path: '/disaster-prevention',
  redirect: '',
};

const fullRoutes: AppRouteRecordRaw[] = [
  disasterPreventionRoute,

  /**
   * 用户管理
   */
  {
    path: '/user',
    name: 'User',
    component: 'LAYOUT',
    meta: {
      icon: 'UserOutlined',
      title: '用户管理',
    },
    children: [
      {
        // 账号管理
        path: 'account',
        name: 'UserAccount',
        component: '/system/user/user',
        meta: {
          icon: '',
          title: '账号管理',
        },
      },
      {
        // 角色管理
        path: 'role',
        name: 'UserRole',
        component: '/system/role/role',
        meta: {
          icon: '',
          title: '角色管理',
        },
      },
      {
        // 组织管理
        path: 'department',
        name: 'UserDepartment',
        component: '/auth/dept/dept',
        meta: {
          icon: '',
          title: '组织管理',
        },
      },
      {
        // 岗位管理 （目前不需要）
        path: 'post',
        name: 'UserPost',
        component: '/auth/post/post',
        meta: {
          icon: '',
          title: '岗位管理',
        },
      },
    ],
  },

  /**
   * 消息管理
   */
  {
    path: '/message',
    name: 'Message',
    component: 'LAYOUT',
    meta: {
      icon: 'SendOutlined',
      title: '消息管理',
    },
    children: [
      {
        // 报表推送
        path: 'report',
        name: 'MessageReport',
        component: '/message/reportmessage/ReportMessage',
        meta: {
          icon: '',
          title: '报表推送',
        },
      },
      {
        // 报表推送配置。二级页面，菜单不可见！！！
        path: 'report-config',
        name: 'MessageReportConfig',
        component: '/message/reportmessage/ReportOperation',
        meta: {
          icon: '',
          title: '报表推送配置',
          activeMenu: 'MessageReport',
        },
      },
      {
        // 报警推送
        path: 'alarm',
        name: 'MessageAlarm',
        component: '/message/alarmMessages/alarmMessages',
        meta: {
          icon: '',
          title: '报警推送',
        },
      },
      {
        // 报警推送配置 。二级页面，菜单不可见！！！
        path: 'alarm-config',
        name: 'MessageAlarmConfig',
        component: '/message/alarm-config/AlarmConfig',
        meta: {
          icon: '',
          title: '报警推送配置',
          activeMenu: 'MessageAlarm',
        },
      },
      {
        // 系统通知
        path: 'sys-notification',
        name: 'MessageSysNotification',
        component: '/message/systemNotifications/systemNotifications',
        meta: {
          icon: '',
          title: '系统通知',
        },
      },
      {
        // 系统通知配置。二级页面，菜单不可见！！！
        path: 'sys-notification-config',
        name: 'MessageSysNotificationConfig',
        component: '/message/sysnotion-config/SysnotionConfig',
        meta: {
          icon: '',
          title: '系统通知配置',
          activeMenu: 'MessageSysNotification',
        },
      },
      {
        // 人员分组
        path: 'personnel-group',
        name: 'MessagePersonnelGroup',
        component: '/message/persongroup/UserGroup',
        meta: {
          icon: '',
          title: '人员分组',
        },
      },
      {
        // 问题处理通知
        path: 'question-notification',
        name: 'MessageQuestionNotification',
        component: '/message/question-notifications/QuestionNotifications',
        meta: {
          icon: '',
          title: '问题处理通知',
        },
      },
    ],
  },

  /**
   * 数据管理
   */
  {
    path: '/data',
    name: 'Data',
    component: 'LAYOUT',
    meta: {
      icon: 'LineChartOutlined',
      title: '数据管理',
    },
    children: [
      {
        // 平台统计
        path: 'platform',
        name: 'DataPlatform',
        component: '/datamanager/platformdata/PlatformData',
        meta: {
          icon: '',
          title: '平台统计',
        },
      },
      {
        // 历史视频 (视频回看)
        path: 'playback',
        name: 'DataPlayback',
        component: '/datamanager/playback/Playback',
        meta: {
          icon: '',
          title: '历史视频',
        },
      },
      {
        // 违规问题
        path: 'violation',
        name: 'DataViolation',
        component: '/datamanager/alertformdata/AlertformData',
        meta: {
          icon: '',
          title: '违规问题',
        },
      },
    ],
  },

  /**
   * 系统管理 （只有超管可见）
   */
  {
    path: '/system',
    name: 'System',
    component: 'LAYOUT',
    meta: {
      icon: 'OptionsSharp',
      title: '系统管理',
    },
    children: [
      {
        // 租户管理
        path: 'tenant',
        name: 'SystemTenant',
        component: '/system/tenant/tenant',
        meta: {
          icon: '',
          title: '租户管理',
        },
      },
      {
        // 菜单管理
        path: 'menu',
        name: 'SystemMenu',
        component: '/system/menu/menu',
        meta: {
          icon: '',
          title: '菜单管理',
        },
      },
      {
        // 权限管理
        path: 'permission',
        name: 'SystemPermission',
        component: '/system/permssion/PagePermission',
        meta: {
          icon: '',
          title: '权限管理',
        },
      },
      {
        // 权限管理
        path: 'comments',
        name: 'SystemComments',
        component: '/system/comments/PageCommentsManage',
        meta: {
          icon: '',
          title: '评论管理',
        },
      },
      {
        // 意见反馈
        path: 'feedback',
        name: 'SystemFeedback',
        component: '/feedback/feedback',
        meta: {
          icon: '',
          title: '意见反馈',
        },
      },
      {
        // 反馈处理 。意见反馈的二级页面。菜单不可见！！！
        path: 'feedback-handle',
        name: 'SystemFeedbackHandle',
        component: '/feedback/handleFeedback',
        meta: {
          icon: '',
          title: '反馈处理',
          activeMenu: 'SystemFeedback',
        },
      },
      // {
      //   // 字典管理 （暂时用不到）
      //   path: 'dictionary',
      //   name: 'SystemDictionary',
      //   component: '/system/dictionary/dictionary',
      //   meta: {
      //     icon: '',
      //     title: '字典管理',
      //   },
      // },
      {
        // 日志管理
        path: 'log',
        name: 'SystemLog',
        component: '/system/log/log',
        meta: {
          icon: '',
          title: '日志管理',
        },
      },
    ],
  },

  /**
   * 异常页面
   */
  {
    path: '/exception',
    name: 'Exception',
    component: 'LAYOUT',
    redirect: '/exception/403',
    meta: {
      icon: 'ExclamationCircleOutlined',
      title: '异常页面',
    },
    children: [
      {
        // 403,
        path: '403',
        name: 'Exception403',
        component: '/exception/403',
        meta: {
          icon: '',
          title: '403',
        },
      },
      {
        path: '404',
        name: '/exception/404',
        component: '/exception/404',
        meta: {
          icon: '',
          title: '404',
        },
      },
      {
        path: '500',
        name: 'Exception500',
        component: '/exception/500',
        meta: {
          icon: '',
          title: '500',
        },
      },
    ],
  },
] as const;

/**
 * 类型定义。避免与已有的定义冲突，避免与 vue-router的类型定义冲突，前面加 _ 前缀
 */
export interface _RouteViewItem {
  label: string;
  value: string;
}
export type _RouteView = _RouteViewItem & { children?: _RouteViewItem[] | null };
export type _RouteViewTree = _RouteView[];

/**
 * 获取指定 父路由 下的子路由。
 * 若 父级路由 未指定，则返回一级路由
 */
export function getChildRoutesView(parentRouteName?: string | null): _RouteViewItem[] {
  // 未指定 parentRouteName， 则返回 level1 的路由
  if (parentRouteName == null) {
    return fullRoutes.map((route) => ({
      label: route.meta.title as string,
      value: route.name,
    }));
  }

  // 获取指定父路由的子路由
  const parentRoute: AppRouteRecordRaw = cloneDeep(getTreeItem(fullRoutes, parentRouteName, 'name'));
  if (parentRoute.children && parentRoute.children.length > 0) {
    return parentRoute.children.map((route) => ({
      label: route.meta.title as string,
      value: route.name,
    }));
  } else {
    return [];
  }
}

/**
 * 获取指定的 路由信息
 */
export function getRouteByName(routeName: string) {
  return cloneDeep(getTreeItem(fullRoutes, routeName, 'name')) as AppRouteRecordRaw;
}

/**
 * 转换成 el-tree-select 的数据结构形式
 */
export function transformToRouteViewTree(routes?: AppRouteRecordRaw[] | null) {
  const tree: _RouteViewTree = [];
  if (routes == null) return tree;

  for (const route of routes) {
    const treeItem: _RouteView = {
      value: route.name,
      label: route.meta.title as string,
      children: null,
    };

    if (route.children && route.children.length > 0) {
      treeItem.children = transformToRouteViewTree(route.children);
      tree.push(treeItem);
    } else {
      tree.push(treeItem);
    }
  }

  return tree;
}

export const routeViewTree = transformToRouteViewTree(fullRoutes);
