<template>
  <a-layout style="min-height: 100vh">
    <a-layout-sider
      v-model:collapsed="state.collapsed"
      collapsible
      :theme="theme"
      class="layout-sider"
    >
      <div :class="['logoWrap', theme === 'light' ? 'light' : 'dark']">
        <div class="logo">
          <slot name="logo"><img src="@/assets/logo.png" alt="" /></slot>
        </div>
        <div class="text">雷能信息后台管理</div>
      </div>
      <a-menu
        v-model:selectedKeys="state.selectedKeys"
        mode="inline"
        :theme="theme"
        :inline-collapsed="state.collapsed"
        :items="menus"
        @click="clickMenuItemHandler"
      ></a-menu>
    </a-layout-sider>

    <a-layout class="layout-content">
      <a-layout-header>
        <slot name="header">
          <base-weather class="weather" mode="text"></base-weather>
          <time-now class="timeNow"></time-now>
          <user-dropdown class="userDropdown"></user-dropdown>
        </slot>
      </a-layout-header>
      <a-layout-content>
        <slot name="breadcrumb">
          <a-page-header
            v-if="routes && routes.length > 1"
            :title="routes[routes.length - 1]?.breadcrumbName"
            :breadcrumb="breadcrumbConfig"
            @back="backHandler"
          >
            <template #backIcon>
              <div
                :style="{
                  pointerEvents: !canGoBack ? 'none' : 'auto',
                  cursor: !canGoBack ? 'none' : 'pointer',
                  color: !canGoBack ? 'rgba(0, 0, 0, 0.25)' : 'inherit',
                }"
              >
                <ArrowLeftOutlined />
              </div>
            </template>
          </a-page-header>
        </slot>
        <slot></slot>
      </a-layout-content>
      <a-layout-footer>
        <slot name="footer">
          <span>合肥雷能信息技术有限公司 © 2025 All Rights Reserved.</span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;版本号：{{ version }}</span>
          <!-- <span>&nbsp;&nbsp;&nbsp;&nbsp;构建时间：{{ buildTime }}</span> -->
        </slot>
      </a-layout-footer>
    </a-layout>

    <alert-modal v-model:open="openAlertModal" :data="alertModalState"></alert-modal>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, defineOptions, reactive, watchEffect, computed, h, onUnmounted, onMounted } from 'vue'
import userDropdown from './components/userDropdown/index.vue'
import { menus } from '@/const/menus'
import { useRoute, useRouter } from 'vue-router'
import timeNow from './components/timeNow/index.vue'
import type { Route } from 'ant-design-vue/es/breadcrumb/Breadcrumb'
import mqtt, { MqttClient } from 'mqtt'
import { useUserStore } from '@/stores/user'
import AlertModal from './components/alertModal/index.vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'

const userStore = useUserStore()
const userId = ref(userStore?.userInfo?.userId || '')
const version = __APP_VERSION__
// const buildTime = __BUILD_TIME__

let mqttClient: MqttClient | null = null
// let mqttTimeout: number | null = null
// const MQTT_TIMEOUT_MS = 10000 // 10秒

const resetMqttTimeout = () => {
  console.log('🚀关闭MQTT连接')
  closeMqtt()
  // if (mqttTimeout) clearTimeout(mqttTimeout)
  // mqttTimeout = window.setTimeout(() => {
  //   console.log('MQTT超时未收到新消息')
  //   closeMqtt()
  // }, MQTT_TIMEOUT_MS)
}

const MqttData = ref()

const initMqttManager = async () => {
  try {
    const mqttConfig = {
      host: import.meta.env.VITE_MQTT_HOST,
      username: import.meta.env.VITE_MQTT_USERNAME,
      password: import.meta.env.VITE_MQTT_PASSWORD,
      clientId: `mqtt_client_${Math.random().toString(16).slice(2, 8)}`,
    }
    mqttClient = mqtt.connect(mqttConfig.host, {
      clientId: mqttConfig.clientId,
      username: mqttConfig.username,
      password: mqttConfig.password,
      will: {
        // ✅ 添加遗嘱消息配置
        topic: '/mps/client/connect',
        payload: JSON.stringify({
          userId: userId.value,
          deviceType: 'wb',
          msgType: 'disconnect',
        }),
        qos: 2,
        retain: false,
      },
    })
    mqttClient.on('connect', () => {
      console.log('MQTT已连接')
      const messageData = {
        userId: userId.value, // 用户ID
        deviceType: 'wb', // 设备类型
        msgType: 'connect', // 消息类型
      }
      // 发布消息
      mqttClient?.publish('/mps/client/connect', JSON.stringify(messageData), { qos: 2 }, (err) => {
        if (err) console.error('发布失败', err)
        else console.log('✅ 已发送参数:', messageData)
      })
      // 订阅所有主题
      mqttClient?.subscribe(`/mps/client/connect/`, (err) => {
        if (err) {
          console.error('MQTT订阅失败', err)
        } else {
          console.log(`🔥已订阅主题 /mps/client/connect`)
        }
      })
      mqttClient?.subscribe(`/mps/wb_${userStore.userInfo?.userId}/notice`, (err) => {
        if (err) {
          console.error('MQTT订阅失败', err)
        } else {
          console.log(`🔥已订阅主题 /mps/wb_${userStore.userInfo?.userId}/notice`)
        }
      })
    })
    mqttClient.on('error', (err) => {
      console.error('MQTT连接错误', err)
    })
    mqttClient.on('message', (topic: string, message: Uint8Array) => {
      resetMqttTimeout()
      try {
        const data = JSON.parse(message.toString())
        console.log('👏👏收到MQTT消息', topic, data)
        MqttData.value = data
      } catch (e) {
        console.error('👏👏MQTT消息解析失败', e)
      }
    })
  } catch (error) {
    console.error('MQTT连接失败:', error)
  }
}

initMqttManager()

// 报警弹窗
const openAlertModal = ref(false)
const alertModalState = reactive({
  devName: '',
  tenantName: '',
  clientId: '',
})
watchEffect(() => {
  const { msgType, event, devName, tenantName, clientId } = MqttData.value || {}
  if (msgType === 'fall' && event === 'fall_confirmed') {
    alertModalState.devName = devName
    alertModalState.tenantName = tenantName
    alertModalState.clientId = clientId
    openAlertModal.value = true
  }

  // 退出连接，取消mqtt连接
  if (!userStore.userInfo.tokenValue) {
    console.log('🚀🚀🚀退出连接，取消mqtt连接')
    closeMqtt()
  }
})

const closeMqtt = () => {
  mqttClient?.end(true)
}

onUnmounted(() => {
  resetMqttTimeout()
})

defineOptions({
  name: 'baseLayout',
})

const route = useRoute()
const router = useRouter()
const theme = ref('dark') // 主题 dark / light

const state = reactive({
  collapsed: false,
  selectedKeys: [route.name],
})

const routes = computed(() => {
  const currentRoute = router.currentRoute.value
  const items = []

  if (currentRoute.matched) {
    currentRoute.matched.forEach((matchedRoute) => {
      if (matchedRoute.meta?.title) {
        items.push({
          breadcrumbName: matchedRoute.meta.title,
          path: matchedRoute.path,
        })
      }
    })
  }

  if (items.length === 0 && currentRoute.meta?.title) {
    items.push({
      breadcrumbName: currentRoute.meta.title,
      path: currentRoute.path,
    })
  }

  return items
})

const breadcrumbConfig = computed(() => {
  return {
    routes: routes.value,
    itemRender,
  }
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const itemRender = (options: { route: Route; params: any; routes: Route[]; paths: string[] }) => {
  console.log('itemRender', options)
  if (!Array.isArray(options.routes)) {
    return h('span', options.route.breadcrumbName || '')
  }

  const currentIndex = routes.value.indexOf(options.route)

  if (currentIndex === -1 || currentIndex === routes.value.length - 1) {
    return h(
      'span',
      {
        class: 'current-breadcrumb',
      },
      options.route.breadcrumbName
    )
  }

  return h(
    'a',
    {
      class: 'breadcrumb-link',
      onClick: (e) => {
        console.log('🚀customRouterLinkRende onClickr🚀', e)
        e.preventDefault()
        if (options.route.path) {
          router.push(options.route.path)
        }
      },
    },
    options.route.breadcrumbName
  )
}

watchEffect(() => {
  if (routes.value.length > 0 && routes.value[0].path) {
    state.selectedKeys = [routes.value[0].path.split('/')[1] || 'home']
  }
})

const clickMenuItemHandler = ({ key, keyPath }: { key: string; keyPath: string[] }) => {
  console.log('🚀clickMenuItemHandler🚀', key, keyPath)
  if (route.name !== key) {
    router.push({ name: key })
  }
}

const canGoBack = ref(false)
const navigationHistory = ref<string[]>([])
let isBackNavigation = false

onMounted(() => {
  // 初始化导航历史
  navigationHistory.value = [router.currentRoute.value.path]
  canGoBack.value = false
})

// 监听路由变化，更新导航历史和canGoBack状态
watchEffect(() => {
  const currentPath = router.currentRoute.value.path

  if (isBackNavigation) {
    // 如果是返回导航，不添加到历史记录
    isBackNavigation = false
  } else {
    // 确保只添加新的路径
    if (navigationHistory.value[navigationHistory.value.length - 1] !== currentPath) {
      navigationHistory.value.push(currentPath)
    }
  }

  // 当历史记录长度大于1时可以返回
  canGoBack.value = navigationHistory.value.length > 1
})

const backHandler = async () => {
  if (navigationHistory.value.length > 1) {
    // 移除当前路径
    navigationHistory.value.pop()

    // 设置返回导航标志
    isBackNavigation = true

    // 返回到上一个路径
    const prevPath = navigationHistory.value[navigationHistory.value.length - 1]
    await router.push(prevPath)
  }
}
</script>

<style scoped lang="less">
.layout-sider {
  position: relative;
  background-color: #1a3a5f;

  :deep(.ant-layout-sider-children) {
    position: sticky;
    top: 0;
    height: auto;
    background-color: #1a3a5f;
    .ant-menu {
      background-color: #1a3a5f;
    }
  }
  :deep(.ant-layout-sider-trigger) {
    background-color: #1a3a5f;
  }
}

.logoWrap {
  height: 32px;
  margin: 16px;
  display: flex;
  align-items: center;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  color: #fff;

  .logo {
    width: 45px;
    height: 32px;
    flex-shrink: 0;
    font-size: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 100%;
      height: 100%;
    }
  }

  .text {
    margin-left: 10px;
    flex-grow: 1;
    opacity: 1;
    transition:
      opacity 0.3s cubic-bezier(0.645, 0.045, 0.355, 1),
      width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);

    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    line-clamp: 2;
  }
}

.light {
  color: #141414;
}
.dark {
  color: #fff;
}

.layout-content {
  .ant-layout-header {
    background-color: #1a3a5f;
    color: #fff;
    padding: 0 32px;
    text-align: right;
    display: flex;
    justify-content: flex-end;
    position: sticky;
    top: 0;
    z-index: 1000;
  }
  .ant-layout-content {
    margin: 16px;
  }
  .ant-layout-footer {
    text-align: center;
    background-color: transparent;
    color: #4774a7;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.ant-layout-sider-collapsed & {
  .text {
    opacity: 0;
    width: 0;
    margin-left: 0;
  }
}

.site-layout .site-layout-background {
  background: #101830b3;
}
[data-theme='dark'] .site-layout .site-layout-background {
  background: #101830b3;
}
</style>
