<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useTokenStore } from '@/store/token'
import { useUserStore } from '@/store'
import { getBanners, getNotices } from '@/api/appointment'
import type { IBanner, INotice } from '@/api/types/appointment'

definePage({
  type: 'home',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
})

const tokenStore = useTokenStore()
const userStore = useUserStore()
const { isEmployee, isGuard } = storeToRefs(userStore)

// ==================== 轮播图 ====================
const banners = ref<IBanner[]>([
  {"image_url":"https://mmbiz.qpic.cn/mmbiz_jpg/XekA4rfc3lccQHzZScOHm74CUWic2L0mmnUYkThXMTyjk6XMeCmiacZ8FyH8yoeNicac5vImCT8TrYURwsvfZKWufHdHqVibXtoc6oWmbLWvAv0/0?from=appmsg","jump_path":"","is_jump":false},
  {"image_url":"https://mmbiz.qpic.cn/mmbiz_jpg/XekA4rfc3lcztReQUQC5VhIYPy5wibC6gnxflibgP7hcjw88ZlT2JT3j6RConSxMej5WVWxHEKEK7Z55uKJqb1CRibShyDkmGLQMCSrUo8LrY8/0?from=appmsg","jump_path":"","is_jump":false},
  {"image_url":"https://mmbiz.qpic.cn/mmbiz_jpg/XekA4rfc3leNOuzXa7ERs9lWSBZDnrqJlqDnjVdnoaB9PmyUh20dqD72D4xibhNdDPMs7JxHZFJpqficngc2DIDwptgmlZt8lY7jp03La43KM/0?from=appmsg","jump_path":"","is_jump":false},
  {"image_url":"https://mmbiz.qpic.cn/sz_mmbiz_jpg/XekA4rfc3ldCJC3G64VvKR4T3RVQavicFbvXooEg69icEamMyy4MGiaRlHVibgicvb3J1cGTkHlhD3oZhOiabSoP1u1hzUG4exaIwH6zJymGJk3dM/0?from=appmsg","jump_path":"","is_jump":false}
])

async function loadBanners() {
  try { banners.value = await getBanners() } catch {}
}

function onBannerClick(banner: IBanner) {
  if (!banner.is_jump || !banner.jump_path) return
  const encodedUrl = encodeURIComponent(banner.jump_path)
  uni.navigateTo({ url: `/pages/public/webview?url=${encodedUrl}` })
}

// ==================== 消息通知（接口查询） ====================
const notices = ref<INotice[]>([])
const noticeScrollIndex = ref(0)
let noticeTimer: ReturnType<typeof setInterval> | null = null

// 通知详情弹窗
const showNoticeDetail = ref(false)
const currentNotice = ref<INotice | null>(null)

async function loadNotices() {
  try { notices.value = await getNotices() } catch {}
}

function startNoticeScroll() {
  if (notices.value.length <= 1) return
  noticeTimer = setInterval(() => {
    noticeScrollIndex.value = (noticeScrollIndex.value + 1) % notices.value.length
  }, 4000)
}

function onNoticeClick() {
  if (notices.value.length === 0) return
  currentNotice.value = notices.value[noticeScrollIndex.value]
  showNoticeDetail.value = true
}

onMounted(() => {
  loadBanners()
  loadNotices()
  startNoticeScroll()
})

onUnmounted(() => {
  if (noticeTimer) clearInterval(noticeTimer)
})

// 分享
onShareAppMessage(() => ({ title: '四川凌空天行 - 访客预约', path: '/pages/index/index' }))
onShareTimeline(() => ({ title: '四川凌空天行 - 访客预约' }))

// ==================== 功能模块（仅保留访客预约入口） ====================
interface ModuleEntry {
  title: string
  desc: string
  icon: string
  path: string
  show: boolean
  color: string
  bgColor: string
}

const modules = computed<ModuleEntry[]>(() => [
  {
    title: '访客预约',
    desc: '预约来访、核验、审查、管理',
    icon: 'i-carbon-add',
    path: '/subpackages/appointment/index',
    show: true,
    color: '#2979ff',
    bgColor: '#e8f0fe',
  },
])

const visibleModules = computed(() => modules.value.filter(m => m.show))

function goPage(path: string) {
  if (!tokenStore.hasLogin) {
    uni.navigateTo({ url: `/pages/auth/login?redirect=${encodeURIComponent(path)}` })
    return
  }
  uni.navigateTo({ url: path })
}

// 导航栏
const navOpacity = ref(0)
const sysInfo = uni.getSystemInfoSync()
const statusBarHeight = sysInfo.statusBarHeight || 0

// #ifdef H5
function onPageScroll(e: any) {
  navOpacity.value = Math.min((e?.scrollTop || 0) / 200, 0.95)
}
// #endif
</script>

<template>
  <view class="home-page">
    <view :style="`height: ${statusBarHeight}px`" />
    <view class="flex items-center px-4" style="height: 44px;">
      <wd-img round :width="40" :height="40" src="//wx.qlogo.cn/mmhead/B2EfAOZfS1hcmGxwIBm2jqd7g94iaWziaURo0f8bsAu3GKKIsTY8NMtweRMJ8H7YXBQXfibkrCAKp0/0" />
      <view class="ml-2 text-white font-bold">
        <view>欢迎使用</view>
        <view class="text-xs">四川凌空访客预约系统</view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section px-4 pt-4">
      <swiper
        class="banner-swiper"
        :indicator-dots="banners.length > 1"
        :autoplay="true"
        :interval="4000"
        :duration="500"
        :circular="true"
        indicator-color="rgba(255,255,255,0.5)"
        indicator-active-color="#2979ff"
      >
        <swiper-item v-for="(item, idx) in banners" :key="idx">
          <image
            :src="item.image_url"
            class="banner-image h-full w-full rounded-2xl"
            mode="aspectFill"
            @click="onBannerClick(item)"
          />
        </swiper-item>
      </swiper>
    </view>

    <!-- 消息通知（接口查询） -->
    <view v-if="notices.length > 0" class="notice-section mx-4 mt-3">
      <view class="notice-bar flex items-center rounded-xl bg-white px-3 py-2.5 shadow-sm" @click="onNoticeClick">
        <view class="mr-2 h-7 w-7 flex items-center justify-center rounded-lg bg-[#fff3e0]">
          <view class="i-carbon-notification text-sm text-[#ff9900]" />
        </view>
        <view class="notice-content flex-1 overflow-hidden">
          <swiper class="notice-swiper" :vertical="true" :autoplay="true" :interval="4000" :duration="600" :circular="true" :disable-touch="true" :current="noticeScrollIndex">
            <swiper-item v-for="item in notices" :key="item.id">
              <view class="h-full flex items-center">
                <text class="notice-text truncate text-sm text-[#333]">{{ item.content }}</text>
              </view>
            </swiper-item>
          </swiper>
        </view>
        <view class="i-carbon-chevron-right text-sm text-[#ccc]" />
      </view>
    </view>

    <!-- 通知详情弹窗 -->
    <wd-popup v-model="showNoticeDetail" position="center" custom-style="width: 320px; border-radius: 12px; padding: 20px;">
      <view v-if="currentNotice">
        <view class="text-center">
          <text class="text-lg font-bold">{{ currentNotice.title }}</text>
        </view>
        <view class="mt-4 rounded-lg bg-gray-50 p-4">
          <text class="text-sm leading-relaxed text-[#333]">{{ currentNotice.content }}</text>
        </view>
        <view class="mt-4 flex justify-center">
          <wd-button @click="showNoticeDetail = false">关闭</wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 功能模块（仅访客预约） -->
    <view class="module-section px-4 pb-6 pt-4">
      <view class="mb-3 flex items-center gap-2">
        <view class="flex h-6 w-6 items-center justify-center rounded-lg bg-[#e8f0fe]">
          <view class="i-carbon-list-boxes text-md text-[#2979ff]" />
        </view>
        <text class="text-base text-[#1a1a1a] font-semibold">功能模块</text>
      </view>
      <view class="flex flex-col gap-3">
        <view
          v-for="mod in visibleModules"
          :key="mod.title"
          class="module-card flex items-center rounded-2xl bg-white p-4 shadow-sm transition-transform active:scale-[0.98]"
          @click="goPage(mod.path)"
        >
          <view
            class="h-13 w-13 flex items-center justify-center rounded-2xl"
            :style="{ backgroundColor: mod.bgColor }"
          >
            <view :class="[mod.icon, 'text-3xl']" :style="{ color: mod.color }" />
          </view>
          <view class="ml-4 flex-1">
            <text class="block text-base text-[#1a1a1a] font-semibold">{{ mod.title }}</text>
            <text class="mt-0.5 block text-xs text-[#999]">{{ mod.desc }}</text>
          </view>
          <view class="i-carbon-chevron-right text-base text-[#ccc]" />
        </view>
      </view>
    </view>

    <view class="h-6" />
  </view>
</template>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  background: url('//mmbiz.qpic.cn/mmbiz_png/XekA4rfc3ld2iccHrK4eZNiaaHCdlmggda6GFmZHhuLo4hHPrbHWORiax6xyHExKPBKXa6OjHCWQbHJHibnZaaYYDjvk9R9qsaVzbbFmQwv5jYo/0?from=appmsg')
    #f3f4fc no-repeat;
  background-size: contain;
}

.banner-swiper {
  height: 320rpx;
  border-radius: 24rpx;
  overflow: hidden;
}

.banner-image {
  display: block;
}

.notice-bar {
  border: 1rpx solid #f0f0f0;
}
.notice-swiper {
  height: 40rpx;
}
.notice-text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}

.module-card {
  transition: transform 0.15s;
}
</style>