<template>
  <div :class="{content: !fullScreen}">
    <!-- 全屏 -->
    <template v-if="fullScreen">
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive" />
      </keep-alive>
      <router-view v-if="!$route.meta.keepAlive" />
    </template>
    <template v-else>
      <navbar :left="width" />
      <div class="body" ref="body">
        <side class="stick" :style="`height: calc(100% - ${this.top}px)`" />
        <div class="view d-flex flex-column" :style="`padding-left: ${width}px;`">
          <div class="breadcrumbs_sticky">
            <div class=" d-flex align-center justify-space-between">
              <v-breadcrumbs :items="title" elevation="3">
                <template v-slot:item="{ item }">
                  <span class="text" :class="{active: !item.disabled}" @click="toPath(item)">{{ item.text }}</span>
                </template>
              </v-breadcrumbs>
              <v-btn v-if="$route.meta.editModules" text color="primary" class="mr-5" @click="handleClickModules">{{ $t('common.moduleEditing') }}</v-btn>
            </div>
            <v-divider></v-divider>
            <!-- <div v-if="list.length && showChip">
              <scroll-tabs class="px-3" :items="list" @handleClick="$event => handleToHref(`${$event.name}${$event.id}`)"></scroll-tabs>
              <v-divider></v-divider>
            </div> -->
          </div>
          <div class="box pa-3 d-flex" :style="`width: calc(100vw - ${width}px); position: relative`">
            <!-- 避免容器因为文字影响 设置字体大小为0 -->
            <div class="box-content" style="font-size: 0;">
              <keep-alive>
                <router-view v-if="$route.meta.keepAlive" />
              </keep-alive>
              <router-view v-if="!$route.meta.keepAlive" />
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 智能助手 -->
    <assistant-iframe
      v-if="assistantWebhookUrl"
      title="数据智能助手"
      subTitle="我可以帮助您管理元数据和数据订单。"
      inputPlaceholder="请输入您的需求，例如：查看所有元数据"
      :iframe-url="assistantWebhookUrl"
    />
  </div>
</template>

<script>
// import ScrollTabs from '@/components/ScrollTabs'
import Navbar from '@/components/Header/navbar.vue'
import Side from '@/components/Side/index.vue'
import { mapGetters } from 'vuex'
// import cloneDeep from 'lodash/cloneDeep'
import AssistantIframe from '@/components/AssistantIframe'
export default {
  name: 'layoutIndex',
  components: { Navbar, Side, AssistantIframe },
  data () {
    return {
      width: 230,
      selectTabs: 0,
      list: [],
      scrollTop: null,
      showChip: true,
      top: 0
    }
  },
  computed: {
    ...mapGetters(['lang', 'userInfo']),
    assistantWebhookUrl () {
      return window?.g?.VUE_APP_N8N_CHAT_URL ?? process.env.VUE_APP_N8N_CHAT_URL ?? ''
    },
    fullScreen () {
      return this.$route.meta.fullScreen
    },
    title () {
      const route = this.$route.matched.map((item, index) => {
        if (item.path === this.$route.matched[index - 1]?.path) return false
        const text = this.lang === 'zh' ? item.meta.title : item.meta.enName
        const obj = {
          text,
          to: item.path
        }
        if (!item.meta?.allowClick) {
          obj.disabled = true
          obj.link = false
        }
        return obj
      }).filter(e => e)
      route[route.length - 1].disabled = true
      route[route.length - 1].link = true
      // route.unshift({ text: '首页', to: '/home' })
      return route
    }
  },
  watch: {
    $route: {
      handler: function (val) {
        this.selectTabs = 0
        this.list = []
        const roles = val.meta.roles.filter(e => e.active === '1').sort((a, b) => a.sort - b.sort)
        if (!['/home'].includes(val.path) && roles && roles.length > 1) {
          this.list = roles.map(e => ({ label: e.label, name: e.name, id: e.id }))
        }
      },
      immediate: true
    }
  },
  created () {
    this.$eventBus.$on('scroll-top', (num) => {
      // console.log('scroll-top', num)
      this.scrollTop = num
    })
    this.$eventBus.$on('show-chip', (show) => {
      // console.log('show-chip', show)
      this.showChip = show
    })

    // this.getMessageUnRead()
    // if (this.timer) {
    //   clearInterval(this.timer)
    // }
    // this.timer = setInterval(() => {
    //   this.getMessageUnRead()
    // }, 10000)
  },
  mounted () {
    if (!this.$refs.body) return
    this.top = this.$refs.body.offsetTop
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    if (!this.$refs.body) return
    // 在组件销毁前移除滚动事件监听
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll () {
      if (!this.list.length) return
      this.list.forEach((section, index) => {
        const selector = document.getElementById(section.name + section.id)
        if (!selector) return
        if (window.scrollY - selector.offsetTop > -400) {
          this.selectTabs = index
        }
      })
    },
    handleToHref (id) {
      // 获取需要跳转到的元素
      const selector = document.getElementById(id)
      if (!selector) return
      // 使用scrollIntoView方法滚动到指定元素
      // selector.scrollIntoView({ behavior: 'smooth', block: 'center' })
      window.scrollTo({
        top: selector.offsetTop - (this.scrollTop ? this.scrollTop : 188), // 滚动到距离顶部280的位置
        behavior: 'smooth' // 平滑滚动
      })
    },
    handleToggle () {
      this.width = 300 - this.width
    },
    handleClick () {
      const path = this.$route.path
      this.$router.push(`${path}/edit`)
    },
    toPath ({ disabled, to }) {
      if (disabled) {
        event.preventDefault()
        return
      }
      this.$router.push(to)
    },
    handleClickModules () {
      this.$emit('$HANDLE_EDIT_MODULES')
    }
    // 查询是否存在未读消息
    // async getMessageUnRead () {
    //   try {
    //     const { data } = await getMessageList({ readState: 0, userId: this.userInfo.id })
    //     this.bellMessage = data.total > 0
    //   } catch (error) {
    //     this.$snackbar.error(error)
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
.stick {
  position: fixed;
  overflow: auto;
  background: #FFF;
  transition: .1s;
  /* 针对 WebKit 浏览器（如 Chrome 和 Safari）使用伪元素 */
  &::-webkit-scrollbar {
    width: 0;
  }
  overflow: -moz-scrollbars-none;  /* 针对 Firefox */
  // -ms-overflow-style: none;  /* 针对 IE 10+ */
  scrollbar-width: none;  /* 针对 Firefox */
  -webkit-overflow-scrolling: touch;  /* 针对 iOS Safari */
}
.breadcrumbs_sticky {
  background: #FFF;
  z-index: var(--zIndex-breadcrumbs);
  border-left: 1px solid #eaecef;
}
.content {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex: 1;
  .body {
    position: relative;
    overflow: hidden;
    height: 0;
    flex: 1;
    display: flex;
    .view {
      background: #f0f2f5;
      box-sizing: border-box;
      .box {
        height: 0;
        flex: 1;
        // overflow-x: hidden;
        &-content {
          width: 100%;
          min-height: 100%;
          position: relative;
          overflow-y: auto;
          overflow-x: hidden;
        }
      }
    }
  }
}
.text {
  color: #999;
  font-size: 14px;
  &.active {
    color: #1867c0;
    cursor: pointer;
  }
}
// .item {
//   padding: 0 8px;
//   cursor: auto;
//   &:focus {
//     color: inherit !important;
//   }
// }

</style>
