import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import router from '@/router'
import {
  getSilder
} from '@/api/silder'
import store from "@/store";
import {
  Message
} from 'element-ui'
// import { stat } from 'fs'
// import { removeToken } from '@/utils/auth'
// import Layout from '@/layout'

/**
 * 遍历接口菜单添加页面
 * @param asyncRoutes
 * @param getMenu
 */
function generateAsyncRouter(asyncRoutes, data) {
  if (!data) {
    return []
  }
  data.forEach((item) => {
    item.component = asyncRoutes[item.component]
    if (item.children && item.children.length > 0) {
      generateAsyncRouter(asyncRoutes, item.children)
    }
  })
  return data
}

/**
 * 判断平台端添加首页
 * @param type
 */
// const type = getters.type

const state = {
  routes: [],
  addRoutes: [],
  type: '', // 登录的平台类型
  permission: [] // 权限
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSION: (state, permission) => {

    state.permission = permission
  }
}

function getFirstMenu(routes) {
  let firstMenu = null
  routes.forEach(item => {
    if (item.children?.length > 0 && !item.hidden) {
      firstMenu = pathErgodic(item)
      // console.log(firstMenu)
      item.redirect = firstMenu
    }
  })
  return routes
}

function pathErgodic(item) {
  // console.log(item)
  let firstMenu = null
  item.children.forEach(i => {
    if (!firstMenu && i.children?.length > 0 && !i.hidden) {
      let isChildrenList = false;
      i.children.forEach(ii => {
        if (!ii.hidden) {
          isChildrenList = true
        }
      })
      if (isChildrenList) {
        firstMenu = pathErgodic(i)
      } else {
        if (!firstMenu && checkPathUrl(i.path)) {
          firstMenu = i.path
        } else {
          if (!firstMenu && !i.hidden) {
            firstMenu = item.path + '/' + i.path
          }
        }
      }

    } else {
      if (!firstMenu && checkPathUrl(i.path)) {
        firstMenu = i.path
      } else {
        if (!firstMenu && !i.hidden) {
          firstMenu = item.path + '/' + i.path
        }
      }
    }
  })
  return firstMenu
}
// 判断path有没有带/,并且是第一个位置
function checkPathUrl(path) {
  return path.indexOf('/') === 0 ? true : false
}
// 路由

// 递归遍历数组
function recursionRouter(arr) {
  // 这里来了
  if (arr.length > 0) {
    let newArr = [];
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].type == 1) {
        continue
      }
      let obj = {};
      obj.component = arr[i].component;
      obj.name = arr[i].component;
      // if (item.type != '1' && item.component) {
      //   if (!item.path.startsWith('/') && item.component != 'Layout') {
      //     obj.names = item.name
      //   }
      // }

      arr[i].hid == 0 ? obj.hidden = false : obj.hidden = true
      // console.log('高亮标签'+arr[i].parentPermission,'普通路径'+arr[i].path)
      obj.path = arr[i].path;
      obj.meta = {
        'title': arr[i].name,
        'icon': arr[i].icon,
        'noCache': arr[i].keepAlive,
        'activeMenu': arr[i].parentPermission,
        'belongTopMenu': arr[i].belongTopMenu,
        'id': arr[i].id
      }
      if (arr[i].sysMenus && arr[i].sysMenus.length > 0) {
        obj.children = recursionRouter(arr[i].sysMenus);
      }

      newArr.push(obj)
    }
    return newArr
  }
}

// 设置 belongTopMenu, 顶部菜单
function addTopMenu(arr) {
  if (arr.length > 0) {
    let newArr = [];
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].type == 1) {
        continue
      }
      let obj = arr[i]
      obj.belongTopMenu = obj.path

      if (arr[i].sysMenus && arr[i].sysMenus.length > 0) {
        obj.sysMenus = setTopMenu(arr[i].sysMenus, obj);
      }

      newArr.push(obj)
    }
    return newArr
  }
}

function setTopMenu(arr, topParentArr) {
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {
    let obj = arr[i]
    obj.belongTopMenu = topParentArr.path
    if (arr[i].sysMenus && arr[i].sysMenus.length > 0) {
      obj.sysMenus = setTopMenu(arr[i].sysMenus, topParentArr);
    }

    newArr.push(obj)
  }
  return newArr
}

// 权限
// 递归遍历数组
let tempArr = []

function recursionPermission(arr) {
  arr.map(item => {
    tempArr.push(item.memo)
    if (item.sysMenus && item.sysMenus.length > 0) {
      recursionPermission(item.sysMenus)
    }
  })
}

function setDetailRoute(accessedRoutes) {
  // console.log(accessedRoutes)
  accessedRoutes.forEach(route => {
    // console.log(route.path)
    if (route.path == '/main') {
      route.children = route.children.concat([{
          name: '日程安排',
          path: 'scheduleDetail',
          component: () => import('@/views/main/teamSchedule/scheduleDetail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '日程安排',
            belongTopMenu: "/main",
            activeMenu: '/main/main',
            id: 'xx1'
          }
        },
        {
          name: '未在班级学员',
          path: 'notClassStudent',
          component: () => import('@/views/main/notClassStudent'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '未在班级学员',
            belongTopMenu: "/main",
            activeMenu: '/main/main',
            id: 'xx2'
          }
        },
        {
          name: '学员请假列表',
          path: 'studentLeaveList',
          component: () => import('@/views/main/studentLeaveList'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '学员请假列表',
            belongTopMenu: "/main",
            activeMenu: '/main/main'
          }
        },
        {
          name: '乐团会员列表',
          path: 'teamMemberList',
          component: () => import('@/views/studentManager/memberList'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '乐团会员列表',
            belongTopMenu: "/main",
            activeMenu: '/main/main'
          }
        },
        {
          name: '乐团展演列表',
          path: 'teamShowList',
          component: () => import('@/views/main/teamShowList'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '乐团展演列表',
            belongTopMenu: "/main",
            activeMenu: '/main/main'
          }
        },
        {
          name: 'organDateDetail',
          path: 'organDateDetail',
          component: () => import('@/views/main/cloudDate/organDateDetail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '分部云教练数据详情',
            belongTopMenu: "/main",
            activeMenu: '/main/main'
          }
        },
        {
          name: 'organRankDetail',
          path: 'organRankDetail',
          component: () => import('@/views/main/cloudDate/organRankDetail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '分部云教练排行',
            belongTopMenu: "/main",
            activeMenu: '/main/main'
          }
        },
        //
      ])
    }
    if (route.path == '/business') {
      // import('@/views/resetTeaming/components/strudentPayInfo'),
      route.children = route.children.concat([{
          name: '学员缴费详情',
          path: 'strudentPayInfo',
          component: () => import('@/views/resetTeaming/components/strudentPayInfo'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '学员缴费详情',
            belongTopMenu: "/business",
            activeMenu: '/teamList',
            id: 'xx3'
          }
        },
        {
          name: '乐团详情',
          path: 'resetTeaming',
          component: () => import('@/views/resetTeaming/index'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '乐团详情',
            belongTopMenu: "/business",
            activeMenu: '/teamList',
            id: 'xx4'
          }
        },
        {
          name: '乐团档案',
          path: 'musicArchices',
          component: () => import('@/views/resetTeaming/components/musicArchices'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '乐团档案',
            belongTopMenu: "/business",
            activeMenu: '/teamList',
            id: 'xx4'
          }
        },
        //musicArchices
        {
          name: '会员排课列表',
          path: 'memberClassList',
          component: () => import('@/views/teamDetail/components/memberClassList'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '会员排课列表',
            belongTopMenu: "/business",
            activeMenu: '/teamList',
            id: 'xx28'
          }
        },
        {
          name: '相册详情',
          path: 'photo-detail',
          component: () => import('@/views/photo-detail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '相册详情',
            belongTopMenu: "/business",
            activeMenu: '/teamList',
            id: 'xxx28'
          }
        },
        // 相册详情
        {
          name: '全部证书',
          path: 'performance',
          component: () => import('@/views/photo-detail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '全部证书',
            belongTopMenu: "/business",
            activeMenu: '/teamList',
            id: 'xxx28'
          }
        },
        // 全部证书
        {
          name: '新建vip',
          path: 'buildVip',
          component: () => import('@/views/buildVip/index'),
          hidden: true,
          meta: {
            noCache: '1',
            title: 'VIP/乐理课申请',
            belongTopMenu: "/business",
            activeMenu: '/vipManager/vipList',
            id: 'xx5'
          }
        },
        {
          name: 'vip修改',
          path: 'vipReset',
          component: () => import('@/views/vipClass/vipReset'),
          hidden: true,
          meta: {
            noCache: '1',
            title: 'VIP/乐理课修改',
            belongTopMenu: "/business",
            activeMenu: '/vipManager/vipList',
            id: 'xx6'
          }
        },
        {
          name: 'vip详情',
          path: 'vipDetail',
          component: () => import('@/views/vipClass/vipDetail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: 'vip详情',
            belongTopMenu: "/business",
            activeMenu: '/vipManager/vipList',
            id: 'xx7'
          }
        },
        {
          name: '网管课详情',
          path: 'accompanys',
          component: () => import('@/views/accompanyManager/accompanys'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '网管课详情',
            belongTopMenu: "/business",
            activeMenu: '/accompanyManager/accompany',
            id: 'xx8'
          }
        },
        {
          name: '评价详情',
          path: 'evaluateDetail',
          component: () => import('@/views/evaluateManager/evaluateDetail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '评价详情',
            belongTopMenu: "/business",
            activeMenu: '/commentManager',
            id: 'xx9'
          }
        },
        {
          name: '课外训练详情',
          path: 'afterSchoolDetail',
          component: () => import('@/views/afterSchoolManager/afterSchoolDetail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: 'VIP/乐理课详情',
            belongTopMenu: "/business",
            activeMenu: '/afterSchoolManager',
            id: 'xx10'
          }
        },
        {
          name: '学员详情',
          path: 'studentDetail',
          component: () => import('@/views/studentManager/index'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '学员详情',
            belongTopMenu: "/business",
            activeMenu: '/studentManager/studentList',
            id: 'xx11'
          }
        },
        {
          name: '老师详情',
          path: 'teacherDetail',
          component: () => import('@/views/teacherManager/teacherDetail/index'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '老师详情',
            belongTopMenu: "/business",
            activeMenu: '/teacherManager/teacherList',
            id: 'xx12'
          }
        },
        {
          name: '老师修改',
          path: 'teacherOperation',
          component: () => import('@/views/teacherManager/teacherOperation/index'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '老师修改',
            belongTopMenu: "/business",
            activeMenu: '/teacherManager/teacherList',
            id: 'xx13'
          }
        },
        {
          name: '问答详情',
          path: 'answer',
          component: () => import('@/views/reaplceMusicPlayer/answerList'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '问答详情',
            belongTopMenu: "/business",
            activeMenu: '/otherManager/reaplceMusicPlayer',
            id: 'xx4'
          }
        },
        {
          name: '活动详情',
          path: 'childrensdayDetail',
          component: () => import('@/views/childrensDay/detail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '活动详情',
            belongTopMenu: "/business",
            activeMenu: '/childrensDay'
          }
        },
        // /otherManager/reaplceMusicPlayer /reaplceMusicPlayer/answer

      ])
    }
    if (route.path == '/operateManager') {
      route.children = route.children.concat([{
          name: '服务指标(详情)',
          path: 'serverIndexDetail',
          component: () => import('@/views/operateManager/serverIndexDetail'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '服务指标(详情)',
            belongTopMenu: "/operateManager",
            activeMenu: '/serverIndexManager/serverIndexList',
            id: 'xx15'
          }
        },
        {
          name: '新建活动方案',
          path: 'vipNewActive',
          component: () => import('@/views/categroyManager/vipNewActive'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '新建活动方案',
            belongTopMenu: "/operateManager",
            activeMenu: '/vipActiveManager/vipActiveList',
            id: 'xx16'
          }
        },
        {
          name: '添加分部活动',
          path: 'branchActiveOperationAdd',
          component: () => import('@/views/categroyManager/insideSetting/branchActiveOperation'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '添加分部活动',
            belongTopMenu: "/operateManager",
            activeMenu: '/branchActiveManager/branchActive',
            id: 'xx17'
          }
        },
        {
          name: '修改分部活动',
          path: 'branchActiveOperation',
          component: () => import('@/views/categroyManager/insideSetting/branchActiveOperation'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '修改分部活动',
            belongTopMenu: "/operateManager",
            activeMenu: '/branchActiveManager/branchActive',
            id: 'xx18'
          }
        },
        {
          name: '添加问卷',
          path: 'questionOperations',
          component: () => import('@/views/setQuestions/operation'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '添加问卷',
            belongTopMenu: "/operateManager",
            activeMenu: '/operateManager/setQuestions',
            id: 'xx19'
          }
        },
        // /operateManager/setQuestions /questionOperation   operateManager
      ])
    }
    if (route.path == '/financialManager') {
      route.children = route.children.concat([{
        name: '经营报表详情',
        path: 'businessStatementDetail',
        component: () => import('@/views/businessManager/orderManager/businessStatementDetail'),
        hidden: true,
        meta: {
          noCache: '1',
          title: '经营报表详情',
          belongTopMenu: "/financialManager",
          activeMenu: '/businessStatement',
          id: 'xx20'
        }
      }, ])
    }
    if (route.path == '/contentManager') {
      route.children = route.children.concat([{
          name: '经营报表详情',
          path: 'helpCategory',
          component: () => import('@/views/helpCenter/helpCategory'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '经营报表详情',
            belongTopMenu: "/contentManager",
            activeMenu: '/contentManager/helpContent',
            id: 'xx21'
          }
        },
        {
          name: '添加&修改内容管理',
          path: 'contentOperation',
          component: () => import('@/views/contentManager/contentOperation'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '添加&修改内容管理',
            belongTopMenu: "/contentManager",
            activeMenu: '/contentManager/contentManager',
            id: 'xx22'
          }
        },
      ])
    }
    if (route.path == '/shopManager') {
      route.children = route.children.concat([{
          name: '进货清单',
          path: 'purchaseLlist',
          component: () => import('@/views/businessManager/shopManager/purchase-llist'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '进货清单',
            belongTopMenu: "/shopManager",
            activeMenu: '/shopList',
            id: 'xx23'
          }
        },
        {
          name: '添加修改商品',
          path: 'shopOperation',
          component: () => import('@/views/businessManager/shopManager/shopOperation'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '添加修改商品',
            belongTopMenu: "/shopManager",
            activeMenu: '/shopList',
            id: 'xx24'
          }
        },
      ])
    }
    if (route.path == '/systemManager') {
      route.children = route.children.concat([{
          name: '创建&修改汇付账号',
          path: 'adapayOperation',
          component: () => import('@/views/adapayAccount/form'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '创建&修改汇付账号',
            belongTopMenu: "/systemManager",
            activeMenu: '/sysBasics/adapayManager',
            id: 'xx25'
          }
        },
        {
          name: '添加&查看时间充值活动',
          path: 'entryOperation',
          component: () => import('@/views/app/entryOperation'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '添加&查看时间充值活动',
            belongTopMenu: "/systemManager",
            activeMenu: '/sysBasics/entryActivities',
            id: 'xx26'
          }
        },
        {
          name: '添加&修改系统权限',
          path: 'adminOperation',
          component: () => import('@/views/categroyManager/insideSetting/adminOperation'),
          hidden: true,
          meta: {
            noCache: '1',
            title: '添加&修改系统权限',
            belongTopMenu: "/systemManager",
            activeMenu: '/parameter/adminManager',
            id: 'xx27'
          }
        },
        // /parameter/adminManager adminOperation
      ])
    }
  })
  return accessedRoutes
}
const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise(resolve => {
      // 获取接口返回的权限菜单
      getSilder().then(async res => {
        if (res.code == 200) {
          let result = addTopMenu(res.data)
          if (res.data?.length < 1) {
            // 一条权限都没有
            //退出 跳到登录页 提示'该账号无任何权限'
            // console.log(store.dispatch)
            await store.dispatch("user/logout");
            localStorage.removeItem("firstMenuUrl");
            // await this.$store.dispatch("permission/removePermission")
            Message.error('该用户无访问权限')
            router.push(`/login`);

            // window.location.reload();
          }
          let newData = recursionRouter(result);

          newData = getFirstMenu(newData)

          recursionPermission(res.data)
          let accessedRoutes

          // 生成异步路由表
          accessedRoutes = generateAsyncRouter(asyncRoutes, newData)
          accessedRoutes = setDetailRoute(accessedRoutes)
          // console.log('生成出来的异步路由', accessedRoutes)
          // var result = accessedRoutes.concat({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', accessedRoutes)
          // commit('SET_PERMISSION', recursionPermission(res.data).flat(Infinity))
          window.localStorage.removeItem('permission')
          window.localStorage.setItem('permission', tempArr)
          this.dispatch('app/setDotStatus')
          resolve(accessedRoutes)
        }
      })
    })
  },
  removePermission({
    commit
  }) {
    window.localStorage.removeItem('permission')
    commit('SET_PERMISSION', [])

  }

}

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