<template>
  <div class="tab-container">
    <el-tabs
      class="fullheight tab-container-root"
      :class="{'tab-default': !finalTabsStyle.tabType}"
      v-model="currentTabComponent"
      :type="finalTabsStyle.tabType"
      @tab-click="handlePaneClick"
      v-if="tabComponentOptions.length > 0"
    >
      <el-tab-pane
        :name="tabComponent.alias"
        v-for="(tabComponent, index) in tabComponentOptions"
        :key="index"
        :class="{'not-aside-tree': !hasTreeComponents(tabComponent.alias)}"
      >
        <span slot="label">
          <span class="ht-menu_title">
            <router-link
              style="color: #333;"
              :to="{path: '/' + tabComponent.alias}"
              >{{ tabComponent.name }}</router-link
            >
            <bookmark-star :tabAlias="tabComponent.alias"></bookmark-star>
          </span>
        </span>

        <component
          v-if="currentTabComponent == tabComponent.alias && !tabComponent.href"
          v-bind:is="currentTabComponent"
        ></component>
        <iframe
          v-if="tabComponent.href"
          :id="tabComponent.id"
          style="height: 100%; width: 100%; border: 0px"
          :src="tabComponent.href"
        ></iframe>
      </el-tab-pane>
    </el-tabs>

    <component
      v-if="tabComponentOptions.length <= 0"
      v-bind:is="currentTabComponent"
    ></component>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import utils from '@/hotent-ui-util.js'

// 懒加载组件 只加载当前页面用到的组件
/** 表单相关页面 **/
const formManager = () => import('@/views/form/FormManager.vue')
const mobileFormManager = () => import('@/views/form/MobileFormManager.vue')
const customDialogList = () =>
  import('@/views/form/customDialog/CustomDialogList.vue')
const customQueryList = () =>
  import('@/views/form/customquery/CustomQueryList.vue')
const businessObj = () => import('@/views/form/BusinessObj.vue')
const formTemplateList = () => import('@/views/form/FormTemplateList.vue')
const flowChartManager = () => import('@/views/form/FlowChartManager.vue')
const customViewManager = () => import('@/views/form/CustomViewManager.vue')
const customChartManager = () => import('@/views/form/CustomChartManager.vue')
const dataTemplateList = () =>
  import('@/views/form/dataTemplate/DataTemplateManager.vue')
const dataDicManager = () => import('@/views/meta/DataDicManager.vue')
const viewManageList = () => import('@/views/form/ViewManageList.vue')
const formPrintTemplateListManager = () =>
  import('@/views/form/FormPrintTemplateListManager.vue')
const formUrlFormManager = () =>
  import('@/views/form/urlForm/FormUrlFormManager.vue')

/** 用户中心相关页面 **/
const tenantManager = () => import('@/views/uc/TenantManager.vue')
const tenantInfoManager = () => import('@/views/system/TenantInfoManager.vue')
const Demension = () => import('@/views/uc/org/Demension.vue')
const roleManager = () => import('@/views/uc/RoleManager.vue')
const reportLine = () => import('@/views/uc/ReportLine.vue')
const userListManager = () => import('@/views/uc/UserListManager.vue')
const tenantTypeManager = () => import('@/views/uc/TenantTypeManager.vue')
const tenantParamsManager = () => import('@/views/uc/TenantParamsManager.vue')
const orgManager = () => import('@/views/uc/org/Organization.vue')
const heiOrganization = () =>
  import('@/views/uc/heiorgmanager/HeiOrganization.vue')
const jobManage = () => import('@/views/uc/org/JobManager.vue')
const postManager = () => import('@/views/uc/org/PostManager.vue')
const prgParamManage = () => import('@/views/uc/org/PrgParamManage.vue')
const userParamManager = () => import('@/views/uc/UserParamManager.vue')
const matrixManager = () => import('@/views/uc/MatrixManager.vue')
const loginLogManager = () => import('@/views/uc/LoginLogManager.vue')
const holidayManager = () => import('@/views/uc/HolidayManager.vue')
const shiftRuleManager = () => import('@/views/uc/ShiftRuleManager.vue')
const onlineUserManager = () => import('@/views/uc/OnlineUserManager.vue')

/** 流程相关页面 **/
const printRecordManager = () => import('@/views/flow/PrintRecordManager.vue')
const defManager = () => import('@/views/flow/DefManager.vue')
const instanceManager = () => import('@/views/flow/InstanceManager.vue')
const instanceRecovery = () => import('@/views/flow/InstanceRecovery.vue')
const taskManager = () => import('@/views/flow/TaskManager.vue')
const delegationManager = () => import('@/views/flow/DelegationManager.vue')
const agentManager = () => import('@/views/flow/AgentManager.vue')
const secretaryManager = () => import('@/views/flow/SecretaryManager.vue')
// const transferManager = () => import("@/views/flow/TransferManager.vue"); //废除
const approvalItemList = () => import('@/views/flow/help/ApprovalItemList.vue')
const historyDataConfig = () =>
  import('@/views/flow/help/HistoryDataConfig.vue')
const msgTemplateList = () => import('@/views/flow/help/MsgTemplateList.vue')
const flowAuthManager = () => import('@/views/flow/FlowAuthManager.vue')
const scriptList = () => import('@/views/flow/help/ScriptList.vue')
const conditionScriptList = () =>
  import('@/views/flow/help/ConditionScriptList.vue')
const bpmCommonDefList = () => import('@/views/flow/BpmCommonDefList.vue')
const mobileFlowType = () => import('@/views/flow/MobileFlowType.vue')
const startTaskButtons = () =>
  import('@/views/flow/flowButtons/startTaskButtons.vue')
const userTaskButtons = () =>
  import('@/views/flow/flowButtons/userTaskButtons.vue')
const signTaskButtons = () =>
  import('@/views/flow/flowButtons/signTaskButtons.vue')
const extendJarManager = () => import('@/views/flow/BpmExtendJarManager.vue')
const extendClassManager = () =>
  import('@/views/flow/BpmExtendClassManager.vue')
const simpleFlowTable = () =>
  import('@/views/flow/simpleFlow/SimpleFlowTable.vue')

/** 门户相关页面 **/
const fileList = () => import('@/views/file/FileList.vue')
const identityManager = () => import('@/views/meta/IdentityManager.vue')
const dataSourceManager = () => import('@/views/meta/DataSourceManager.vue')
const i18nMessageManager = () =>
  import('@/views/system/i18n/I18nMessageManager.vue')
const i18nMessageTypeManager = () =>
  import('@/views/system/i18n/I18nMessageTypeManager.vue')
const menuManager = () => import('@/views/system/menu/MenuManager.vue')
const methodListManager = () =>
  import('@/views/system/menu/MethodListManager.vue')
const schedulerManager = () => import('@/views/system/SchedulerManager.vue')
const executeJobList = () => import('@/views/system/ExecuteJobList.vue')
const schedulerTriggerList = () =>
  import('@/views/system/SchedulerTriggerList.vue')
const sysTypeTreeManager = () => import('@/views/system/SysTypeTreeManager.vue')
const sysTypeCatManager = () => import('@/views/system/SysTypeCatManager.vue')
const demo = () => import('@/views/Demo.vue')
const indexLayout = () => import('@/views/portal/IndexLayout.vue')
const indexColumn = () => import('@/views/portal/IndexColumn.vue')
const flowInterfaceCllLog = () =>
  import('@/views/system/log/FlowInterfaceCllLog.vue')
const messageSendLog = () => import('@/views/system/log/MessageSendLog.vue')
const systemLogConfig = () => import('@/views/system/log/SystemLogConfig.vue')
const systemLogList = () => import('@/views/system/log/SystemLogList.vue')
const layoutDistribution = () => import('@/views/portal/LayoutDistribution.vue')
const defaultLayout = () => import('@/views/portal/DefaultLayout.vue')
const sysPropertiesManager = () =>
  import('@/views/system/SysPropertiesManager.vue')
const layoutManager = () => import('@/views/portal/LayoutManager.vue')
const sysSetting = () => import('@/views/system/SysSetting.vue')
const pwdStrategy = () => import('@/views/uc/PwdStrategy.vue')
const startGenerator = () =>
  import('@/views/system/generator/StartGenerator.vue')
const generatorLog = () => import('@/views/system/generator/GeneratorLog.vue')
const sysExternalUniteList = () =>
  import('@/views/system/sysExternalUnite/SysExternalUnite.vue')
const appModelManager = () => import('@/views/portal/AppModelManager.vue')
const portalNewsNoticeManager = () =>
  import('@/views/news/PortalNewsNoticeManager.vue')
const flowUploadProperties = () =>
  import('@/views/file/FlowUploadPropertiesManager.vue')
const portalDataSensitiveManager = () =>
  import(
    /* webpackChunkName: "group-portal" */ '@/views/portal/PortalDataSensitiveManager.vue'
  )
const sysTagManager = () => import('@/views/portal/SysTagManager.vue')
const pcAppCenter = () => import('@/views/portal/AppCenter.vue')
const watermarkManager = () => import('@/views/flow/WatermarkManager.vue')
const sysModuleList = () => import('@/views/system/generator/sysModuleList.vue')
const DatavManager = () => import('@/views/portal/DatavManager.vue')
const PopupManager = () => import('@/components/portal/PopupManager.vue')
const permissionAdjustmentManage = () =>
  import('@/views/flow/PermissionAdjustmentManage.vue')
const PortalMeetingRoomManager = () =>
  import('@/views/portal/PortalMeetingRoomManager.vue')
const connectionManager = () =>
  import('@/views/service/connectManage/PortalConnectionManagerManager.vue')
const bizSystemManager = () =>
  import('@/views/portal/PortalBizSystemManager.vue')
const interfaceManage = () =>
  import('@/views/service/interfaceManage/PortalInterfaceManagerManager.vue')
const serviceChoreography = () =>
  import(
    '@/views/service/serviceChoreography/PortalServiceChoreographyManager.vue'
  )
const apiManager = () => import('@/views/portal/PortalUrlPermissionManager.vue')
const externalSystemLog = () =>
  import('@/views/system/log/ExternalSystemLogList.vue')
const externalSystemQueueLog = () =>
  import('@/views/portal/PortalMsgSendLogManager.vue')

const formCustomComponentManager = () =>
  import('@/views/form/FormCustomComponentManager.vue')

const formAuthorizeManager = () =>
  import('@/views/form/FormAuthorizeManager.vue')

import BookmarkStar from '@/components/common/BookmarkStar.vue'

import menuApi from '@/api/menu.js'

const IGNORE_ALIAS = []

export default {
  name: 'ht-tabs-component',
  components: {
    formCustomComponentManager,
    portalNewsNoticeManager,
    formManager,
    formUrlFormManager,
    mobileFormManager,
    formPrintTemplateListManager,
    roleManager,
    reportLine,
    menuManager,
    schedulerManager,
    userListManager,
    tenantTypeManager,
    tenantParamsManager,
    tenantManager,
    tenantInfoManager,
    orgManager,
    instanceManager,
    instanceRecovery,
    taskManager,
    printRecordManager,
    identityManager,
    executeJobList,
    schedulerTriggerList,
    dataSourceManager,
    dataDicManager,
    i18nMessageManager,
    i18nMessageTypeManager,
    fileList,
    defManager,
    Demension,
    customDialogList,
    customQueryList,
    businessObj,
    bpmCommonDefList,
    sysTypeTreeManager,
    sysTypeCatManager,
    customChartManager,
    delegationManager,
    agentManager,
    secretaryManager,
    // transferManager,
    prgParamManage,
    jobManage,
    postManager,
    formTemplateList,
    dataTemplateList,
    demo,
    indexLayout,
    indexColumn,
    msgTemplateList,
    approvalItemList,
    historyDataConfig,
    scriptList,
    userParamManager,
    flowAuthManager,
    conditionScriptList,
    methodListManager,
    flowInterfaceCllLog,
    messageSendLog,
    systemLogConfig,
    systemLogList,
    layoutDistribution,
    defaultLayout,
    layoutManager,
    flowChartManager,
    customViewManager,
    heiOrganization,
    sysPropertiesManager,
    startGenerator,
    generatorLog,
    pwdStrategy,
    viewManageList,
    matrixManager,
    sysSetting,
    sysExternalUniteList,
    loginLogManager,
    appModelManager,
    flowUploadProperties,
    portalDataSensitiveManager,
    holidayManager,
    shiftRuleManager,
    sysTagManager,
    pcAppCenter,
    watermarkManager,
    sysModuleList,
    DatavManager,
    PopupManager,
    BookmarkStar,
    mobileFlowType,
    startTaskButtons,
    userTaskButtons,
    signTaskButtons,
    permissionAdjustmentManage,
    PortalMeetingRoomManager,
    connectionManager,
    interfaceManage,
    serviceChoreography,
    apiManager,
    externalSystemLog,
    externalSystemQueueLog,
    onlineUserManager,
    extendJarManager,
    extendClassManager,
    bizSystemManager,
    simpleFlowTable,
    formAuthorizeManager
  },
  props: {},
  computed: {
    ...mapGetters({
      tabsStyle: 'styleSetting/tabsStyle'
    }),
    finalTabsStyle: function() {
      // 使用菜单的配置
      if (
        (this.tabsStyle.tabType == 'menuSetting' ||
          this.tabsStyle.tabType == null) &&
        this.menuTabsStyle
      ) {
        return this.menuTabsStyle
      }

      // 使用默认的
      if (
        this.tabsStyle.tabType == null ||
        ((this.tabsStyle.tabType == 'menuSetting' ||
          this.tabsStyle.tabType == null) &&
          !this.menuTabsStyle)
      ) {
        return {tabType: ''}
      }
      // 使用全局的配置
      return this.tabsStyle
    },
    hasTreeComponents() {
      return alias => {
        const aliasList = [
          'businessObj',
          'formManager',
          'mobileFormManager',
          'formUrlFormManager',
          'formPrintTemplateListManager',
          'customQueryList',
          'customDialogList',
          'identityManager',
          'dataDicManager',
          'sysTagManager',
          'datavManager',
          'dataTemplateList',
          'pcAppCenter',
          'appModelManager',
          'sysModuleList',
          'defManager',
          'mobileFlowType',
          'fileList',
          'connectionManager',
          'menuManager',
          'methodListManager',
          'orgManager',
          'bizSystemManager'
        ]
        return aliasList.includes(alias)
      }
    }
  },
  data() {
    return {
      tabComponentOptions: [],
      currentTabComponent: '',
      menuTabsStyle: null,
      menuMap: {}
    }
  },
  methods: {
    handlePaneClick: function(data) {
      if (data.alias) {
        this.currentTabComponent = data.alias
      } else if (data.name) {
        this.currentTabComponent = data.name
      }
    },
    genHref(anchor) {
      if (this.$router.mode == 'history') {
        return anchor
      }
      return '/#' + this.$route.path + '#' + anchor
    },
    activeTab(fullpath) {
      let lastIdx = fullpath.lastIndexOf('#')
      if (lastIdx != -1) {
        let urlAnchor = fullpath.substr(lastIdx + 1)
        this.tabComponentOptions.filter(item => {
          if (item.alias == urlAnchor) {
            this.currentTabComponent = urlAnchor
            console.log(1, this.currentTabComponent)
          }
        })
      }
    },
    renderMenu(vm, to, m) {
      if (m) {
        vm.$emit('menuChange', m)
        let children = m.children
          ? m.children.filter(item => {
              return !IGNORE_ALIAS.includes(item.alias)
            })
          : []
        if (children && children.length > 0) {
          vm.tabComponentOptions = children
          let hasSame = false
          children.forEach(i => {
            if (m.activeTab && m.activeTab == i.alias) {
              hasSame = true
            }
          })
          if (hasSame) {
            vm.currentTabComponent = m.activeTab
          } else {
            vm.currentTabComponent = vm.tabComponentOptions[0].alias
          }
          // vm.currentTabComponent =
          //   m.activeTab || vm.tabComponentOptions[0].alias
          vm.activeTab(to.fullPath)
        } else {
          // 没有下级，并且是3级菜单。有上级，并且上级有下级菜单。
          if (
            m.path &&
            m.path.split('.').length == 6 &&
            m.parent &&
            m.parent.children
          ) {
            // 用上级的下级菜单来渲染页签
            vm.tabComponentOptions = m.parent.children
          } else {
            vm.tabComponentOptions = []
          }
          vm.currentTabComponent = m.alias
        }
        if (m.tabsStyle) {
          vm.menuTabsStyle = utils.parseToJson(m.tabsStyle)
        } else {
          vm.menuTabsStyle = null
        }
      } else {
        // 没有菜单的路由跳转   需要显示TAb名称需要定义tobName参数传递过来
        vm.tabComponentOptions = []
        vm.currentTabComponent = to.name
        vm.$emit('menuChange', {name: to.params.tobName})
      }
    }
  },
  mounted() {},
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 通过 `vm` 访问组件实例
      let routePath = vm.$route.path
      if (routePath) {
        routePath = routePath.replace('/', '')
      }
      if (vm.menuMap[routePath]) {
        vm.renderMenu(vm, to, vm.menuMap[routePath])
      } else {
        menuApi.getMenuByAlias(routePath, m => {
          vm.renderMenu(vm, to, m)
          vm.menuMap[routePath] = m
        })
      }
    })
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变，但是该组件被复用时调用
    // 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
    // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    this.activeTab(to.fullPath)
    next()
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.tab-container >>> .is-active .el-link {
  color: $--color-primary;
  font-weight: bold;
}
.tab-container .el-tab-pane {
  height: 100%;
}
// 表单内边距
.tab-container {
  .not-aside-tree {
    padding: 9px 24px 20px 24px;
  }
  ::v-deep {
    .el-tabs__content {
      height: calc(100% - 60px);
      .pagination-panel {
        padding-bottom: 0;
      }
    }
    .el-tabs--card {
      padding: 24px 24px 0px 24px;
      .el-tabs__content {
        height: calc(100% - 102px);
      }
      .not-aside-tree {
        padding: 0 0 20px 0;
      }
    }
    .tab-default {
      .el-tabs__content {
        // height: calc(100% - 92px);
        height: calc(100% - 70px);
        //多层tabs
        .el-tabs__content {
          height: calc(100% - 48px);
          .el-main {
            padding: 0px 0px 0px 20px;
            .ht-table-panel {
              margin: 0;
            }
          }
          .ht-table-panel {
            padding: 0;
          }
        }
        .not-aside-tree {
          .el-tabs__content {
            .ht-table-panel {
              margin: 0;
            }
          }
        }
      }
    }
  }
}
.ht-menu_title {
  display: flex;
  ::v-deep.collect-icon {
    padding-left: 6px;
  }
}
::v-deep {
  //列表上下24px全局设置
  .el-tabs__content {
    .el-container {
      .el-main {
        padding: 9px 20px 24px 20px;
      }
      .ht-table-panel {
        padding: 0;
      }
    }
    .not-aside-tree {
      height: calc(100% - 24px);
    }
  }

  .el-tabs--card > .el-tabs__header .el-tabs__nav {
    background-color: rgba(248, 248, 248, 0.39);
  }
  // .el-tabs--card > .el-tabs__header .el-tabs__item {
  //   // border: 0;
  // }
  .el-row--flex {
    // justify-content: flex-end;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
    background-color: #fff;
    span {
      .ht-menu_title {
        // border-bottom: 3px solid #409eff;
        height: 37px;
      }
    }
  }
  .el-tabs__nav-wrap::after {
    height: 1px;
  }
  .tab-default {
    .el-tabs__item.is-top:nth-child(2) {
      padding-left: 30px;
    }
    .el-tabs__item {
      height: 56px;
      line-height: 56px;
    }
    .el-tabs--card {
      .el-tabs__item {
        height: 40px;
        line-height: 40px;
      }
    }
  }
}
</style>
