<template>
  <view class="dispatch-home">
    <!-- 顶部山水背景 banner -->
    <view class="banner">
      <image class="banner-bg" src="/static/index-backpage.jpg" mode="aspectFill" />
      <view class="banner-veil"></view>
      <StatusBar />
      <view class="banner-inner px-4">
        <view class="flex items-center flex-1 min-w-0">
          <view class="avatar mr-3">
            <text class="uni-icons uniui-person-filled avatar-icon"></text>
          </view>
          <view class="min-w-0">
            <text class="greet block">{{ greetText }}，欢迎回来</text>
            <text class="username truncate">{{ userName }}</text>
          </view>
        </view>
        <view
          class="notify-btn flex-shrink-0"
          hover-class="notify-hover"
          :hover-start-time="0"
          :hover-stay-time="120"
          @click="goToNotification"
        >
          <text class="uni-icons uniui-notification-filled notify-icon"></text>
          <view v-if="notificationCount > 0" class="notify-badge">
            {{ notificationCount > 99 ? '99+' : notificationCount }}
          </view>
        </view>
      </view>
    </view>

    <!-- 内容区 -->
    <view class="content-wrap px-4 pb-24">
      <!-- 统计卡片 -->
      <view class="glass-card p-4">
        <view class="grid grid-cols-3 gap-3">
          <view
            class="stat-card"
            hover-class="stat-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToTaskList"
          >
            <view class="stat-bar"></view>
            <text class="stat-value">{{ todayTasks.length }}</text>
            <text class="stat-label">今日任务</text>
          </view>
          <view
            class="stat-card"
            hover-class="stat-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToTaskList"
          >
            <view class="stat-bar"></view>
            <text class="stat-value">{{ taskStore.pendingCount }}</text>
            <text class="stat-label">待审核</text>
          </view>
          <view
            class="stat-card"
            hover-class="stat-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToEmergencyTeam"
          >
            <view class="stat-bar"></view>
            <text class="stat-value">{{ approvedCount }}</text>
            <text class="stat-label">待安排</text>
          </view>
        </view>
      </view>

      <!-- 快捷入口 -->
      <view class="glass-card p-4">
        <view class="grid grid-cols-4 gap-3">
          <view
            class="entry-card"
            hover-class="entry-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToSchedule"
          >
            <view class="icon-chip">
              <text class="uni-icons uniui-calendar-filled chip-glyph"></text>
            </view>
            <text class="entry-label">排班管理</text>
          </view>
          <view
            class="entry-card"
            hover-class="entry-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToTaskList"
          >
            <view class="icon-chip">
              <text class="uni-icons uniui-flag-filled chip-glyph"></text>
            </view>
            <text class="entry-label">任务列表</text>
          </view>
          <view
            class="entry-card"
            hover-class="entry-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToVehicleList"
          >
            <view class="icon-chip">
              <text class="uni-icons uniui-cart-filled chip-glyph"></text>
            </view>
            <text class="entry-label">车辆管理</text>
          </view>
          <view
            class="entry-card"
            hover-class="entry-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToVisualization"
          >
            <view class="icon-chip">
              <text class="uni-icons uniui-map-filled chip-glyph"></text>
            </view>
            <text class="entry-label">可视化</text>
          </view>
        </view>
      </view>

      <!-- 待审核任务 -->
      <view class="glass-card">
        <view class="section-head">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">待审核任务</text>
          <text class="section-more" @click="goToTaskList">查看全部</text>
        </view>
        <view v-if="pendingTasks.length === 0" class="py-6 text-center">
          <text class="empty-text">暂无待审核任务</text>
        </view>
        <view v-else>
          <view
            v-for="task in pendingTasks"
            :key="taskIdOf(task)"
            class="list-row"
            hover-class="row-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToTaskDetail(taskIdOf(task))"
          >
            <view class="icon-chip mr-3">
              <text class="uni-icons uniui-flag chip-glyph"></text>
            </view>
            <view class="flex-1 min-w-0 mr-2">
              <text class="row-title truncate">{{ task.projectName }}</text>
              <text class="row-sub truncate">{{ task.address || '暂无地址' }}</text>
              <text class="row-sub truncate">申请时间：{{ task.applyTime || task.createTime }}</text>
            </view>
            <StatusTag :status="task.status" />
          </view>
        </view>
      </view>

      <!-- 通知公告 -->
      <view class="glass-card">
        <view class="section-head">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">通知公告</text>
          <text class="section-more" @click="goToNoticeList">更多</text>
        </view>
        <view
          v-for="notice in notices"
          :key="notice.noticeId"
          class="list-row"
          hover-class="row-hover"
          :hover-start-time="0"
          :hover-stay-time="120"
          @click="goToNoticeDetail(notice.noticeId)"
        >
          <view class="dot mr-3" :class="notice.priority >= 2 ? 'dot-active' : 'dot-muted'"></view>
          <text class="flex-1 row-title truncate mr-2">{{ notice.title }}</text>
          <text class="row-date flex-shrink-0">{{ formatDate(notice.publishTime, 'YYYY-MM-DD') }}</text>
        </view>
        <view v-if="notices.length === 0" class="list-row">
          <text style="font-size: 12px; color: #9ca3af;">暂无通知</text>
        </view>
      </view>

      <!-- 行业知识 -->
      <view>
        <view class="section-head px-4">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">行业知识</text>
          <text class="section-more" @click="goToKnowledgeList">更多</text>
        </view>
        <view class="knowledge-list px-4 pb-4">
          <view
            v-for="item in knowledgeList"
            :key="item.id"
            class="knowledge-card"
            hover-class="knowledge-card-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToKnowledgeDetail(item.id)"
          >
            <view v-if="item.cover" class="knowledge-cover">
              <image :src="item.cover" mode="aspectFill" class="w-full h-full" />
            </view>
            <view v-else class="knowledge-cover knowledge-cover-placeholder">
              <text class="uni-icons uniui-chart knowledge-cover-icon"></text>
            </view>
            <text class="knowledge-card-title truncate">{{ item.title }}</text>
          </view>
          <view v-if="knowledgeList.length === 0" class="py-6 text-center">
            <text class="empty-text">暂无知识内容</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useTaskStore } from '@/stores/task'
import { useNotificationStore } from '@/stores/notification'
import { formatDate } from '@/utils'
import { getNoticeList } from '@/api/notice'
import { getKnowledgeList, type KnowledgeItem } from '@/api/knowledge'
import StatusBar from '@/components/common/StatusBar.vue'
import StatusTag from '@/components/common/StatusTag.vue'

const authStore = useAuthStore()
const taskStore = useTaskStore()
const notificationStore = useNotificationStore()

const today = formatDate(new Date(), 'YYYY-MM-DD')

const userName = ref(authStore.user?.name || '调度员')
const notificationCount = computed(() => notificationStore.unreadCount)

function dateHit(dateStr: string, planDate?: string, planEndDate?: string) {
  if (!planDate) return false
  if (dateStr === planDate) return true
  if (planEndDate && dateStr >= planDate && dateStr <= planEndDate) return true
  return false
}

const approvedCount = computed(() => taskStore.tasks.filter(t => t.status === 'approved').length)
const todayTasks = computed(() => taskStore.tasks.filter(t => dateHit(today, t.planDate, t.planEndDate) || t.scheduleDate === today || t.serviceDate === today))
const pendingTasks = computed(() => taskStore.tasks.filter(t => t.status === 'auditing').slice(0, 3))

function taskIdOf(task: any): string {
  const id = task?.id ?? task?.taskId ?? ''
  return id && !Number.isNaN(id) ? String(id) : ''
}

const greetText = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '凌晨好'
  if (hour < 12) return '上午好'
  if (hour < 14) return '中午好'
  if (hour < 18) return '下午好'
  return '晚上好'
})

function goToTaskList() {
  uni.switchTab({ url: '/pages/task/task' })
}

function goToTaskDetail(taskId: string) {
  if (!taskId || taskId === 'NaN') return
  uni.navigateTo({ url: `/subPackages/pages-dispatch/taskDetail?id=${taskId}` })
}

function goToSchedule() {
  uni.switchTab({ url: '/pages/schedule/schedule' })
}

function goToVehicleList() {
  uni.navigateTo({ url: '/subPackages/pages-dispatch/vehicleList' })
}

function goToVisualization() {
  uni.navigateTo({ url: '/subPackages/pages-dispatch/visualization' })
}

function goToEmergencyTeam() {
  uni.navigateTo({ url: '/subPackages/pages-dispatch/emergencyTeam' })
}

function goToNotification() {
  uni.navigateTo({ url: '/subPackages/pages-common/messageList' })
}

function goToNoticeList() {
  uni.navigateTo({ url: '/subPackages/pages-dispatch/noticeList' })
}

function goToNoticeDetail(noticeId: number) {
  uni.navigateTo({ url: `/subPackages/pages-dispatch/noticeDetail?id=${noticeId}` })
}

function goToKnowledgeList() {
  uni.navigateTo({ url: '/subPackages/pages-common/knowledgeList' })
}

function goToKnowledgeDetail(id: number) {
  uni.navigateTo({ url: `/subPackages/pages-common/knowledgeDetail?id=${id}` })
}

const notices = ref<any[]>([])
const knowledgeList = ref<KnowledgeItem[]>([])

onMounted(async () => {
  taskStore.fetchMyTasks(today)
  notificationStore.fetchUnreadCount()
  try {
    const res = await getNoticeList(1, 3)
    notices.value = res.rows || []
  } catch (error) {
    console.error('获取通知列表失败:', error)
  }
  try {
    const res = await getKnowledgeList(1, 2)
    knowledgeList.value = res.rows || []
  } catch (error) {
    console.error('获取知识列表失败:', error)
  }
})
</script>

<style scoped>
/* ==================== 页面外壳 ==================== */
.dispatch-home {
  position: relative;
  max-width: 430px;
  margin: 0 auto;
  min-height: 100vh;
  background-color: #f6fbf9; /* 云雾白 */
}

/* ==================== 顶部 banner（山水背景） ==================== */
.banner {
  position: relative;
  height: 168px;
  overflow: hidden;
  background-color: #dff0e8; /* 图片加载前的浅青绿兜底 */
}

.banner-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

/* 蒙版：顶部提亮保文字、底部淡出衔接云雾白 */
.banner-veil {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  background: linear-gradient(
    180deg,
    rgba(255, 255, 255, 0.5) 0%,
    rgba(255, 255, 255, 0.16) 45%,
    rgba(246, 251, 249, 0.66) 100%
  );
}

.banner-inner {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  padding-top: 14px;
  padding-bottom: 24px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 22px -8px rgba(31, 41, 37, 0.4);
  flex-shrink: 0;
}

.avatar-icon {
  font-size: 24px;
  color: #368f6f;
}

.greet {
  font-size: 12px;
  color: rgba(31, 41, 37, 0.62);
}

.username {
  display: block;
  margin-top: 2px;
  font-size: 18px;
  font-weight: 800;
  letter-spacing: 0.5px;
  color: #1f2937;
}

/* 通知铃铛 */
.notify-btn {
  position: relative;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  box-shadow: 0 6px 18px -8px rgba(31, 41, 37, 0.35);
}

.notify-icon {
  font-size: 20px;
  color: #368f6f;
}

.notify-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  min-width: 18px;
  height: 18px;
  padding: 0 4px;
  border-radius: 9px;
  background-color: #ef4444;
  border: 1.5px solid rgba(255, 255, 255, 0.9);
  color: #ffffff;
  font-size: 10px;
  font-weight: 700;
  line-height: 15px;
  text-align: center;
}

.notify-hover {
  background-color: rgba(255, 255, 255, 0.88);
}

/* ==================== 内容区（轻微上叠 banner） ==================== */
.content-wrap {
  position: relative;
  z-index: 2;
  margin-top: -18px;
}

/* 磨砂玻璃卡 */
.glass-card {
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  border: 1px solid rgba(164, 216, 152, 0.35);
  border-radius: 16px;
  box-shadow: 0 18px 50px -12px rgba(54, 143, 111, 0.28);
  overflow: hidden;
  margin-bottom: 12px;
}

/* ==================== 统计卡 ==================== */
.stat-card {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 88px;
  padding: 14px 6px 12px;
  border-radius: 12px;
  background-color: rgba(164, 216, 152, 0.14);
  border: 1px solid rgba(164, 216, 152, 0.3);
  overflow: hidden;
}

.stat-bar {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 26px;
  height: 3px;
  border-radius: 0 0 3px 3px;
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
}

.stat-value {
  font-size: 24px;
  font-weight: 800;
  line-height: 1.1;
  color: #368f6f;
}

.stat-label {
  margin-top: 6px;
  font-size: 12px;
  color: #6b7280;
}

.stat-hover {
  transform: scale(0.97);
  background-color: rgba(164, 216, 152, 0.24);
}

/* ==================== 快捷入口 ==================== */
.entry-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 14px 4px 12px;
  border-radius: 12px;
}

.entry-label {
  margin-top: 8px;
  font-size: 13px;
  font-weight: 500;
  color: #374151;
}

.entry-hover {
  background-color: rgba(164, 216, 152, 0.14);
  transform: scale(0.97);
}

/* 嫩芽浅底图标块 */
.icon-chip {
  width: 42px;
  height: 42px;
  border-radius: 12px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(164, 216, 152, 0.2);
}

.chip-glyph {
  font-size: 20px;
  color: #368f6f;
}

/* ==================== 区块标题栏 ==================== */
.section-head {
  display: flex;
  align-items: center;
  padding: 16px 16px 12px;
}

.section-bar {
  width: 4px;
  height: 16px;
  border-radius: 2px;
  background: linear-gradient(180deg, #368f6f 0%, #5ab8d0 100%);
}

.section-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
}

.section-more {
  font-size: 13px;
  color: #368f6f;
}

/* ==================== 列表行 ==================== */
.list-row {
  display: flex;
  align-items: center;
  padding: 13px 16px;
  border-top: 1px solid rgba(164, 216, 152, 0.18);
}

.row-title {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.row-sub {
  display: block;
  margin-top: 3px;
  font-size: 12px;
  color: #9ca3af;
}

.row-date {
  font-size: 12px;
  color: #9ca3af;
}

.row-hover {
  background-color: rgba(164, 216, 152, 0.1);
}

/* 通知圆点 */
.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.dot-active {
  background-color: #368f6f;
  box-shadow: 0 0 0 3px rgba(164, 216, 152, 0.3);
}

.dot-muted {
  background-color: #c4d0cb;
}

.empty-text {
  font-size: 13px;
  color: #9ca3af;
}

/* ==================== 行业知识（独立卡片：封面+标题） ==================== */
.knowledge-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.knowledge-card {
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  border: 1px solid rgba(164, 216, 152, 0.35);
  border-radius: 16px;
  box-shadow: 0 14px 40px -10px rgba(54, 143, 111, 0.22);
  overflow: hidden;
}

.knowledge-cover {
  height: 120px;
  overflow: hidden;
  background-color: rgba(164, 216, 152, 0.12);
}

.knowledge-cover-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
}

.knowledge-cover-icon {
  font-size: 40px;
  color: #368f6f;
}

.knowledge-card-title {
  display: block;
  padding: 12px 14px;
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.knowledge-card-hover {
  background-color: rgba(164, 216, 152, 0.1);
}
</style>
