<template>
  <a-layout class="layout">
    <a-layout-header class="layout-navbar">
      <a-button
        class="mobile-menu-trigger"
        type="text"
        shape="circle"
        @click="toggleSider"
      >
        <template #icon>
          <icon-menu-unfold v-if="siderCollapsed" />
          <icon-menu-fold v-else />
        </template>
      </a-button>
      <Navbar />
    </a-layout-header>
    <a-layout
      class="layout-body"
      :class="{
        'layout-body--mobile': isMobile,
        'layout-body--menu-open': isMobile && !siderCollapsed
      }"
    >
      <a-layout-sider
        class="layout-sider"
        :width="200"
        :collapsed-width="0"
        :collapsed="siderCollapsed"
        :hide-trigger="true"
        collapsible
        breakpoint="lg"
        @collapse="(val) => (siderCollapsed = val)"
      >
        <Menu class="menu-wrapper" />
      </a-layout-sider>
      <a-layout-content class="layout-content">
        <PageLayout class="page-layout-main" />
        <Footer />
      </a-layout-content>
      <div
        v-if="isMobile && !siderCollapsed"
        class="mobile-menu-mask"
        @click="siderCollapsed = true"
      />
    </a-layout>

    <a-badge v-if="aiAvailable" :count="aiUnread" :dot="aiUnread > 0" class="aiButtonBadge">
      <a-avatar class="aiButton" @click="chat = !chat">
        <img alt="AI助手" src="@/assets/img/ai.png" />
      </a-avatar>
    </a-badge>

    <AIChat v-if="aiAvailable" :visible="chat" @close="chat = false" @unread-change="aiUnread = $event" />

    <a-modal
      v-model:visible="popupVisible"
      :title="popupData.title || '公告'"
      :footer="false"
      width="760px"
      modal-class="home-popup-modal"
      @cancel="handlePopupClose"
    >
      <div class="popup-html" v-html="popupData.content_html"></div>
    </a-modal>
  </a-layout>
</template>

<script setup>
import { computed, onMounted, onBeforeUnmount, ref, onUnmounted } from 'vue'
import { eventBus } from '@/utils/eventBus'
import { Notification } from '@arco-design/web-vue'
import { getUnreadPopup, markPopupRead } from '@/api/public'
import { useUserStore } from '@/store'

import PageLayout from './page-layout.vue'
import Menu from '@/components/Menu/index.vue'
import Navbar from '@/components/Navbar/index.vue'
import Footer from '@/components/Footer/index.vue'
import AIChat from '@/components/AIChat/index.vue'

const chat = ref(false)
const aiUnread = ref(0)
const popupVisible = ref(false)
const popupData = ref({})
const siderCollapsed = ref(false)
const isMobile = ref(false)
const userStore = useUserStore()
const aiAvailable = computed(() => !!(userStore.uuid && userStore.session))

// 按钮拖动
let isDragging = false
let offsetX = 0
let offsetY = 0
let button = null

function handleMouseDown(e) {
  isDragging = true
  const rect = button.getBoundingClientRect()
  offsetX = e.clientX - rect.left
  offsetY = e.clientY - rect.top

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

function handleMouseMove(e) {
  if (!isDragging) return
  const x = e.clientX - offsetX
  const y = e.clientY - offsetY

  button.style.left = x + 'px'
  button.style.top = y + 'px'
  button.style.right = 'auto'
  button.style.bottom = 'auto'
}

function handleMouseUp() {
  isDragging = false
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
}

onMounted(() => {
  button = document.querySelector('.aiButtonBadge')
  if (button) {
    button.addEventListener('mousedown', handleMouseDown)
  }
  eventBus.on('closeAI', () => { chat.value = false })
  const mobile = window.innerWidth <= 992
  isMobile.value = mobile
  if (mobile) {
    siderCollapsed.value = false
  }
  window.addEventListener('resize', syncSiderCollapsed)
  getPopup()
})

onBeforeUnmount(() => {
  if (button) {
    button.removeEventListener('mousedown', handleMouseDown)
  }
  window.removeEventListener('resize', syncSiderCollapsed)
})

onUnmounted(() => {
  eventBus.off('closeAI', () => { chat.value = false })
})

const getPopup = async () => {
  try {
    const res = await getUnreadPopup({ limit: 1 })
    if (!res || res.code !== 0) return
    const list = res.data || []
    if (!list.length) return
    popupData.value = list[0]
    popupVisible.value = true
  } catch (error) {
    Notification.error({
      title: '获取首页公告失败',
      content: error.message || '请稍后再试'
    })
  }
}

const handlePopupClose = async () => {
  popupVisible.value = false
  if (!popupData.value?.id) return
  try {
    await markPopupRead({ popup_id: popupData.value.id })
  } catch (_) {}
}

const syncSiderCollapsed = () => {
  const mobile = window.innerWidth <= 992
  isMobile.value = mobile
  if (!mobile) {
    siderCollapsed.value = false
  }
}

const toggleSider = () => {
  siderCollapsed.value = !siderCollapsed.value
}

</script>

<style scoped lang="less">
@import '@/styles/store-theme.less';

@nav-size-height: 60px;


.layout {
  min-width: 0;
  width: 100%;
  min-height: 100vh;
}

.layout-body {
  margin-top: @nav-size-height;
  min-height: calc(100vh - @nav-size-height);
  height: calc(100vh - @nav-size-height);
  position: relative;
  overflow: hidden;
}

.layout-navbar {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: @nav-size-height;
}

.mobile-menu-trigger {
  display: none;
}

.layout-sider {
  position: sticky;
  top: @nav-size-height;
  z-index: 99;
  height: calc(100vh - @nav-size-height);
  transition: all 0.2s cubic-bezier(0.34, 0.69, 0.1, 1);

  &::after {
    position: absolute;
    top: 0;
    right: -1px;
    display: block;
    width: 1px;
    height: 100%;
    background-color: var(--color-border);
    content: '';
  }
}

.menu-wrapper {
  user-select: none;
  margin-top: 0;
  height: 100%;
  overflow: auto;
  overflow-x: hidden;

  :deep(.arco-menu) {
    ::-webkit-scrollbar {
      width: 12px;
      height: 4px;
    }

    ::-webkit-scrollbar-thumb {
      border: 4px solid transparent;
      background-clip: padding-box;
      border-radius: 7px;
      background-color: var(--color-text-4);
    }

    ::-webkit-scrollbar-thumb:hover {
      background-color: var(--color-text-3);
    }
  }
}

.layout-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
  min-height: calc(100vh - @nav-size-height);
  overflow-x: hidden;
  overflow-y: auto;
  background-color: @store-bg;
  transition: transform 0.22s ease;

  &::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    border: 2px solid transparent;
    border-radius: 8px;
    background-clip: padding-box;
    background-color: rgba(22, 93, 255, 0.28);
    transition: background-color 0.2s ease;
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: rgba(22, 93, 255, 0.46);
  }
}

@media (min-width: 993px) {
  .layout-body {
    display: block;
  }

  .layout-sider {
    position: fixed;
    left: 0;
    top: @nav-size-height;
    width: 200px !important;
    height: calc(100vh - @nav-size-height);
  }

  .layout-content {
    margin-left: 200px;
    height: calc(100vh - @nav-size-height);
  }
}

.mobile-menu-mask {
  position: fixed;
  top: @nav-size-height;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.28);
}

.aiButton {
  width: 55px;
  height: 55px;
  background-color: #fff;
  cursor: pointer;
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.15);
  }
}

.aiButtonBadge {
  position: fixed;
  bottom: 100px;
  right: 60px;
  z-index: 200;
}

.popup-html {
  margin-top: 0;
  padding-right: 4px;
  max-height: min(56vh, 520px);
  overflow-y: auto;
  line-height: 1.7;
  color: var(--color-text-1);

  &::-webkit-scrollbar {
    width: 8px;
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 6px;
    background-color: rgba(134, 144, 156, 0.35);
  }

  &::-webkit-scrollbar-thumb:horizontal {
    border-radius: 999px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: rgba(134, 144, 156, 0.55);
  }
}

:deep(.home-popup-modal) {
  border-radius: 14px;
  box-shadow: 0 14px 40px rgba(15, 35, 95, 0.16);
  overflow: hidden;

  .arco-modal-header {
    margin-bottom: 0;
    padding: 18px 24px 14px;
    border-bottom: 1px solid var(--color-border-2);
    background: linear-gradient(180deg, rgba(22, 93, 255, 0.06) 0%, rgba(22, 93, 255, 0) 100%);
  }

  .arco-modal-title {
    font-size: 18px;
    font-weight: 600;
    color: var(--color-text-1);
  }

  .arco-modal-body {
    padding: 18px 24px 22px;
  }

  .arco-modal-close-btn {
    top: 14px;
    right: 14px;
    width: 28px;
    height: 28px;
    border-radius: 8px;
    color: var(--color-text-2);
    background-color: rgba(240, 243, 245, 0.9);
    transition: all 0.2s ease;
  }

  .arco-modal-close-btn:hover {
    color: var(--color-text-1);
    background-color: rgba(229, 233, 237, 1);
  }
}

@media (max-width: 992px) {
  .mobile-menu-trigger {
    display: inline-flex;
    position: absolute;
    left: 8px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1001;
  }

  :deep(.navbar .left-side) {
    padding-left: 48px;
  }

  .layout-body--mobile {
    display: block;
  }

  .layout-body--mobile .layout-sider {
    position: fixed;
    left: 0;
    top: @nav-size-height;
    z-index: 1001;
    height: calc(100vh - @nav-size-height);
    width: 200px !important;
    transform: translateX(-100%);
    transition: transform 0.22s ease;
    box-shadow: 2px 0 16px rgba(0, 0, 0, 0.14);
  }

  .layout-body--menu-open .layout-sider {
    transform: translateX(0);
  }

  .layout-body--mobile .layout-content {
    min-height: calc(100vh - @nav-size-height);
    transform: translateX(0);
  }

  .layout-body--menu-open .layout-content {
    transform: translateX(200px);
  }

  .aiButtonBadge {
    right: 18px;
    bottom: 24px;
  }
}
</style>
