import router from './router'
import {resetRouter} from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')

          // 请求获取路由表
          await store.dispatch('user/getRouter')
          if (store.getters.menus.length < 1) {
            global.antRouter = []
            next()
          }

          // 设置路由
          var newRoutes = []
          for (var route of store.getters.menus) {
            const item = buildRootRoute(route)
            newRoutes.push(item)
          }
          // newRoutes.shift();

          // 添加一项根目录重定向页面
          if(newRoutes[0].path != '/') {
            let path = newRoutes[0].path;
            if(newRoutes[0].children.length > 0) {
              path = `${path}/${newRoutes[0].children[0].path}`
            }
            if(newRoutes[0].children[0].children.length > 0) {
              path = `${path}/${newRoutes[0].children[0].children[0].path}`
            }
            newRoutes.unshift({
              path: '/',
              component: Layout,
              redirect: path
            })
          }else {
            newRoutes[0].redirect = '/dashboard'
          }

          console.log(newRoutes);
          router.addRoutes(newRoutes) // 2.动态添加路由
          global.antRouter = newRoutes // 3.将路由数据传递给全局变量，做侧边栏菜单渲染工作

          // const menus = filterAsyncRouter(store.getters.menus) // 1.过滤路由
          // console.log(menus);
          // router.addRoutes(menus) // 2.动态添加路由
          // global.antRouter = menus // 3.将路由数据传递给全局变量，做侧边栏菜单渲染工作
          next({
            ...to,
            replace: true
          })
          // next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    console.log(route);
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = _import(route.component) // 导入组件
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}

function buildRootRoute(route) {
  const { url, icon, moduleName, moduleId, code, type } = route
  var item = {}
  item.path = url
  item.component = Layout
  item.name = code
  item.meta = {
    title: moduleName,
    icon: icon
  }
  if(code == 'index') {
    item.path = '/';
    item.alwaysShow = false;
    let children = route.children;
    route.children = [];
    route.children.push(
      {
        'code': "dashboard",
        'moduleName': "首页",
        'type': 2,
        'url': '/dashboard',
        'children': children
      }
    )
  }
  if (code == 'merchant') {
    let children = route.children;
    route.children.push(
      {
        'code': "merchant_detail",
        'moduleName': "商户详情",
        'type': 2,
        'url': '/merchant_detail',
        'children': children,
        'hidden': true
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'marketing') {
    let children = route.children;
    route.children.push(
      {
        'code': "sop_add",
        'moduleName': "新增个人SOP",
        'type': 2,
        'url': '/sop_add',
        'children': children,
        'hidden': true
      },
      {
        'code': "sop_detail",
        'moduleName': "个人SOP详情",
        'type': 2,
        'url': '/sop_detail',
        'children': children,
        'hidden': true
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'goods_manage') {
    let children = route.children;
    route.children.push(
      {
        'code': "goods_add",
        'moduleName': "添加商品",
        'type': 2,
        'url': '/goods_add',
        'children': children,
        'hidden': true
      },
      {
        'code': "explain_add",
        'moduleName': "添加模块",
        'type': 2,
        'url': '/explain_add',
        'children': children,
        'hidden': true
      },
      {
        'code': "explain_common",
        'moduleName': "公共模块",
        'type': 2,
        'url': '/explain_common',
        'children': children,
        'hidden': true
      },
      {
        'code': "watermark_add",
        'moduleName': "添加水印",
        'type': 2,
        'url': '/watermark_add',
        'children': children,
        'hidden': true
      },
      {
        'code': "newclassify_set",
        'moduleName': "新维度分类配置",
        'type': 2,
        'url': '/newclassify_set',
        'children': children,
        'hidden': true
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'order_manage') {
    let children = route.children;
    route.children.push(
      {
        'code': "order_detail",
        'moduleName': "订单详情",
        'type': 2,
        'url': '/detail',
        'children': children,
        'hidden': true
      },{
        'code': "order_refund_detail",
        'moduleName': "维权订单详情",
        'type': 2,
        'url': '/order_refund_detail',
        'children': children,
        'hidden': true
      },{
        'code': "workOrder_detail",
        'moduleName': "工单详情",
        'type': 2,
        'url': '/workOrder_detail',
        'children': children,
        'hidden': true
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'promotion') {
    let children = route.children;
    route.children.push(
      {
        'code': "coupon_add",
        'moduleName': "添加优惠券",
        'type': 2,
        'url': '/coupon_add',
        'children': children,
        'hidden': true
      },{
        'code': "seckill_add",
        'moduleName': "添加秒杀活动",
        'type': 2,
        'url': '/seckill_add',
        'children': children,
        'hidden': true
      },{
        'code': "groupbuy_add",
        'moduleName': "添加团购活动",
        'type': 2,
        'url': '/groupbuy_add',
        'children': children,
        'hidden': true
      },{
        'code': "groupbuy_set",
        'moduleName': "团长设置",
        'type': 2,
        'url': '/groupbuy_set',
        'children': children,
        'hidden': true
      },{
        'code': "groupbuy_detail",
        'moduleName': "拼团详情",
        'type': 2,
        'url': '/groupbuy_detail',
        'children': children,
        'hidden': true
      },{
        'code': "special_set",
        'moduleName': "活动专区配置",
        'type': 2,
        'url': '/special_set',
        'children': children,
        'hidden': true
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'wxcustomer') {
    let children = route.children;
    route.children = [];
    route.children.push(
      {
        'code': "wxcustomer_index",
        'moduleName': "企微客户管理",
        'type': 2,
        'url': '/index',
        'children': children
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'settle_manage') {
    let children = route.children;
    route.children = [];
    route.children.push(
      {
        'code': "settlement_index",
        'moduleName': "结算管理",
        'type': 2,
        'url': '/index',
        'children': children
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'delivery_manage') {
    let children = route.children;
    route.children = [];
    route.children.push(
      {
        'code': "freight_index",
        'moduleName': "配送管理",
        'type': 2,
        'url': '/index',
        'children': children
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'stockpile_manage') {
    let children = route.children;
    route.children = [];
    route.children.push(
      {
        'code': "storage_index",
        'moduleName': "仓储管理",
        'type': 2,
        'url': '/index',
        'children': children
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'msg') {
    let children = route.children;
    route.children = [];
    route.children.push(
      {
        'code': "notice_index",
        'moduleName': "消息列表",
        'type': 2,
        'url': '/index',
        'children': children
      }
    )
    item.alwaysShow = false;
  }
  if (code == 'message') {
    let children = route.children;
    route.children = [];
    route.children.push(
      {
        'code': "message_index",
        'moduleName': "短信群发设置",
        'type': 2,
        'url': '/index',
        'children': children
      }
    )
    item.alwaysShow = false;
  }
  item.children = []
  if ((route.hasOwnProperty('children') && type === 1) || code == 'wxcustomer' || code == 'settle_manage' || code == 'delivery_manage' || code == 'stockpile_manage' || code == 'msg' || code == 'message' || code == 'index') {
    for (var child of route.children) {
      item.children.push(buildRoute(child, url))
    }
  }
  return item
}

function buildRoute(route, p_url) {
  const { url, moduleName, icon, moduleId, code, type, hidden } = route
  var item = {}
  if(url.substr(0, 1) == '/') {
    item.path = url.substr(1)
  }else {
    item.path = url
  }
  try {
    if(code == 'dashboard') {
      // item.component = _import(`${url}/index`)
      item.component = (resolve) => require(["@/views"+`${url}/index`], resolve)
    }
    else {
      item.component = _import(`${p_url}${url}`)
    }
  } catch (e) {
    console.log(e)
  }
  item.name = code
  item.meta = {
    title: moduleName,
    icon: icon
  }
  if((route.children && type == 2)) {
    let roles = [];
    for(var role of route.children) {
      roles.push(role.code)
    }
    item.meta.roles = roles;
  }
  item.hidden = hidden
  item.children = []
  if (route.hasOwnProperty('children') && type === 1) {
    for (var child of route.children) {
      item.children.push(buildThirdRoute(child, `${p_url}${url}`))
    }
  }
  return item
}

function buildThirdRoute(route, p_url) {
  const { url, moduleName, icon, moduleId, code, hidden, type } = route
  var item = {}
  if(url.substr(0, 1) == '/') {
    item.path = url.substr(1)
  }else {
    tem.path = url
  }
  try {
    item.component = _import(`${p_url}${url}`)
  } catch (e) {
    console.log(e)
  }
  item.name = code

  item.meta = {
    title: moduleName,
    icon: icon
  }
  if(route.children && type == 2) {
    let roles = [];
    for(var role of route.children) {
      roles.push(role.code)
    }
    item.meta.roles = roles;
  }
  item.hidden = hidden
  item.children = []
  return item
}

function mapIconFun(code) {
  const mapIcon = {
    dashboard: 'el-icon-s-home', // 首页
    goods_manage: 'el-icon-s-goods', // 商品管理
    goods_list: 'el-icon-s-goods', // 商品列表
    category_manage: 'el-icon-menu', // 分类管理
    explain: 'el-icon-s-management', // 说明管理
    order_manage: 'el-icon-s-order', // 订单管理
    order_list: 'el-icon-s-order', // 订单列表
    order_pr: 'el-icon-s-release', // 维权订单
    ticket: 'el-icon-s-ticket', // 开发票
    comment_tag: 'el-icon-s-flag', // 评价标签
    promotion: 'el-icon-s-opportunity', // 活动管理
    groupbuy_index: 'el-icon-s-goods', // 团购活动
    promotion_ms: 'el-icon-s-help', // 秒杀活动
    discode_index: 'el-icon-s-grid', // 优惠码
    promotion_coupon: 'el-icon-s-ticket', // 优惠券设置
    vip_manage: 'el-icon-s-custom', // 会员管理
    member_index: 'el-icon-s-custom', // 会员列表
    salesman_apply: 'el-icon-s-check', // 业务员申请
    wxcustomer: 'el-icon-s-custom', // 企微客户管理
    settle_manage: 'el-icon-s-check', // 结算管理
    delivery_manage: 'el-icon-s-cooperation', // 配送管理
    stockpile_manage: 'el-icon-s-shop', // 仓储管理
    msg: 'el-icon-message-solid', // 消息列表
    tag_manage: 'el-icon-s-flag', // 消息列表

    setting: 'el-icon-s-tools', // 系统设置
    account: 'el-icon-s-promotion', // 帐号管理
    authority: 'el-icon-s-flag', // 权限管理
    log: 'el-icon-s-order', // 操作日志
    carousel: 'el-icon-picture', // 轮播图设置
    profile: 'el-icon-user-solid', // 个人信息
    noticebar: 'el-icon-warning', // 通告管理
    offline: 'el-icon-s-help', // 线下数据
    offline_index: 'el-icon-s-marketing', // 线下数据
    sales_index: 'el-icon-s-marketing', // 线下数据

    merchant: 'el-icon-s-shop', // 商户管理
    merchant_list: 'el-icon-s-shop', // 商户列表
    create_account: 'el-icon-circle-plus', // 开通账号

    marketing: 'el-icon-s-marketing', // 营销活动
    material: 'el-icon-picture', // 营销素材
    spu_list: 'el-icon-s-claim', // 个人SOP
  }
  return mapIcon[code]
}
