import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { getDicts } from "@/api/system/dict/data";
import Cookies from "js-cookie";
NProgress.configure({ showSpinner: false })

const whiteList = [
  '/login',
  '/login_index',
  '/auth-redirect',
  '/bind',
  '/register',
  '/login_deposit',
  '/loginSingle',
  '/login_enforce',
  '/login_house',
  '/login_trans',
  '/login_finance',
  '/login_society',
  '/login_three',
  '/login_land',
  '/login_item',
  '/login_company',
  '/login_entity',
  '/login_yinnong',
  '/login_chungeng',
  // '/login_test',
]

router.beforeEach((to, from, next) => {
  console.log('11111111111')
  NProgress.start()
  if (store.getters.systemConfigList.length == 0) {

    store.dispatch('systemTitle').then(() => {
      document.title = store.getters.browserName == '' ? '农经综合信息管理平台' : store.getters.browserName
    })
  }
  if (getToken()) {
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => {
          if (res && res.code && res.code == 200) {
            // 拉取user_info

            let businessOwnerList = res.user.businessOwnership;

            if (businessOwnerList != null) {
              getDicts("business_ownership").then((response) => {
                let businessOwnerArr = businessOwnerList.split(',')
                let businessOwnerArrSort = businessOwnerArr.sort((a, b) => {//升序
                  return a - b
                });
                let arrLable = []
                response.data.forEach((v, i) => {
                  businessOwnerArr.forEach((data, length) => {
                    if (v.dictValue == data) {
                      arrLable.push({
                        dictValue: v.dictValue,
                        dictLabel: v.dictLabel,
                        remark: v.remark,
                        dictSort: v.dictSort
                      })
                    }
                  })
                })

                let routerId = window.localStorage.getItem("routerId");
                let bookType = res.user.bookType;
                let endDictValue;
                const viewPagesProfileId = Cookies.get("viewPagesProfileId");
                if (
                  viewPagesProfileId == undefined ||
                  viewPagesProfileId == "" ||
                  viewPagesProfileId == null
                ) {
                  if (routerId == null || businessOwnerArrSort.includes(routerId) == false) {
                    if (businessOwnerArrSort.includes("1") || businessOwnerArrSort.includes("2") || businessOwnerArrSort.includes("3")) {
                      if (bookType == 1) {
                        endDictValue = 1;
                      } else if (bookType == 2) {
                        endDictValue = 2;
                      } else if (bookType == 3) {
                        endDictValue = 3;
                      } else if (bookType == 8) {
                        endDictValue = 8;
                      } else {
                        endDictValue = arrLable[0].dictValue
                      }
                    } else {
                      endDictValue = arrLable[0].dictValue
                    }
                  } else {

                    if (businessOwnerArrSort.includes("1") || businessOwnerArrSort.includes("2") || businessOwnerArrSort.includes("3") || businessOwnerArrSort.includes("8")) {
                      if (bookType == 1) {
                        if (routerId == 2 || routerId == 3 || routerId == 8) {
                          endDictValue = 1;
                        } else {
                          endDictValue = routerId;
                        }
                      } else if (bookType == 2) {
                        if (routerId == 1 || routerId == 3 || routerId == 8) {
                          endDictValue = 2;
                        } else {
                          endDictValue = routerId;

                        }
                      } else if (bookType == 3) {
                        if (routerId == 2 || routerId == 1 || routerId == 8) {
                          endDictValue = 3;
                        } else {
                          endDictValue = routerId;

                        }
                      } else if (bookType == 8) {
                        if (routerId == 1 || routerId == 2 || routerId == 3) {
                          endDictValue = 8;
                        } else {
                          endDictValue = routerId;
                        }
                      } else {
                        endDictValue = routerId;
                      }
                    } else {
                      if (routerId) {
                        endDictValue = routerId;
                      } else {
                        endDictValue = arrLable[0].dictValue
                      }
                    }
                  }
                } else {
                  endDictValue = viewPagesProfileId;
                }

                store.dispatch('GenerateRoutes', endDictValue).then(accessRoutes => {
                  // 根据roles权限生成可访问的路由表
                  router.addRoutes(accessRoutes) // 动态添加可访问路由表
                  next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                })
              })
            } else {
              store.dispatch('GenerateRoutes', 'no-router').then(accessRoutes => {
                // 根据roles权限生成可访问的路由表
                router.addRoutes(accessRoutes) // 动态添加可访问路由表
                next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
              })
            }

          }
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else if (to.path.indexOf('dataScreen') != -1) {
      next()
    } else if (to.path.indexOf('subcontract') != -1) {
      next()
    } else {
      if (to.query && to.query.code && to.query.exiturl) {
        next(`/login?code=${to.query.code}&exiturl=${to.query.exiturl}`)
      } else {
        next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      }
      //next(`/zjdLogin?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
