<script setup lang="ts">
/**
 * 养护记录列表页
 *
 * 支持搜索、日期筛选（全部/今天/本周/本月），
 * 点击记录卡片跳转到记录详情。
 * Design: #1E74FF NavBar, #F4F7F8 bg, white cards border-radius 10px, styled tabs.
 */
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

/** 搜索关键词 */
const searchText = ref('')

/** 当前激活的 Tab（日期筛选） */
const activeTab = ref(0)

/** 模拟养护记录数据 */
const mockRecords = [
  { id: 1, taskName: '管网养护-城北片区', maintainer: '刘工', startTime: '2025-06-15 09:00', endTime: '2025-06-15 11:30', result: 'normal', score: 95, address: '城北工业大道1-50号' },
  { id: 2, taskName: '阀门养护-高新区', maintainer: '陈工', startTime: '2025-06-15 14:00', endTime: '2025-06-15 16:00', result: 'abnormal', score: 72, address: '高新区创新路55号' },
  { id: 3, taskName: '水表养护-老城区', maintainer: '杨工', startTime: '2025-06-14 08:30', endTime: '2025-06-14 10:00', result: 'normal', score: 88, address: '老城区中山路88号' },
  { id: 4, taskName: '消防栓养护-商业区', maintainer: '周工', startTime: '2025-06-13 15:00', endTime: '2025-06-13 17:00', result: 'abnormal', score: 65, address: '商业区解放路101号' },
  { id: 5, taskName: '泵站养护-东区', maintainer: '吴工', startTime: '2025-06-10 09:00', endTime: '2025-06-10 11:00', result: 'normal', score: 91, address: '东区滨河路88号' },
]

/** 结果映射 */
const resultMap: Record<string, string> = {
  normal: '正常',
  abnormal: '异常',
}

const resultColorMap: Record<string, 'success' | 'danger'> = {
  normal: 'success',
  abnormal: 'danger',
}

/** 日期筛选工具函数 */
function getToday(): string {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const today = getToday()

function isThisWeek(dateStr: string): boolean {
  const d = new Date(dateStr)
  const now = new Date()
  const startOfWeek = new Date(now)
  startOfWeek.setDate(now.getDate() - now.getDay())
  startOfWeek.setHours(0, 0, 0, 0)
  return d >= startOfWeek
}

function isThisMonth(dateStr: string): boolean {
  const d = new Date(dateStr)
  const now = new Date()
  return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth()
}

/** 筛选后的记录列表 */
const filteredRecords = computed(() => {
  let list = mockRecords

  // 搜索筛选
  if (searchText.value) {
    const kw = searchText.value.toLowerCase()
    list = list.filter(r =>
      r.taskName.toLowerCase().includes(kw) ||
      r.maintainer.toLowerCase().includes(kw) ||
      r.address.toLowerCase().includes(kw)
    )
  }

  // 日期筛选
  if (activeTab.value === 1) {
    list = list.filter(r => r.startTime.startsWith(today))
  } else if (activeTab.value === 2) {
    list = list.filter(r => isThisWeek(r.startTime))
  } else if (activeTab.value === 3) {
    list = list.filter(r => isThisMonth(r.startTime))
  }

  return list
})

/** 跳转到记录详情 */
function goDetail(id: number) {
  router.push(`/maintenanceRecords/detail?id=${id}`)
}

/** 格式化时间，只显示时间部分 */
function formatTime(dateStr: string): string {
  // Returns HH:MM from "YYYY-MM-DD HH:MM"
  return dateStr.split(' ')[1] || dateStr
}
</script>

<template>
  <div class="records-page">
    <!-- NavBar — brand blue -->
    <van-nav-bar
      title="养护记录"
      left-arrow
      fixed
      placeholder
      @click-left="router.back()"
    />

    <!-- Search -->
    <div class="search-wrapper">
      <van-search
        v-model="searchText"
        placeholder="搜索任务名称、养护人"
        shape="round"
        background="transparent"
      />
    </div>

    <!-- Tabs -->
    <van-tabs
      v-model:active="activeTab"
      sticky
      :duration="0.3"
      swipeable
      color="#1E74FF"
      title-active-color="#1E74FF"
      title-inactive-color="#646566"
      line-width="20"
      line-height="3"
    >
      <van-tab title="全部" />
      <van-tab title="今天" />
      <van-tab title="本周" />
      <van-tab title="本月" />
    </van-tabs>

    <!-- Record List -->
    <div class="record-list">
      <van-empty
        v-if="filteredRecords.length === 0"
        image="search"
        description="暂无养护记录"
      />
      <div
        v-for="record in filteredRecords"
        :key="record.id"
        class="record-card"
        @click="goDetail(record.id)"
      >
        <!-- Card Header -->
        <div class="record-card__header">
          <h4 class="record-card__title">{{ record.taskName }}</h4>
          <van-tag :type="resultColorMap[record.result]" size="medium" round>
            {{ resultMap[record.result] }}
          </van-tag>
        </div>

        <!-- Card Body -->
        <div class="record-card__body">
          <div class="record-info">
            <span class="info-item">
              <van-icon name="user-o" size="13" />
              {{ record.maintainer }}
            </span>
            <span class="info-item">
              <van-icon name="star-o" size="13" />
              评分 {{ record.score }}
            </span>
          </div>
        </div>

        <!-- Card Footer -->
        <div class="record-card__footer">
          <span class="address-text">
            <van-icon name="location-o" size="12" color="#969799" />
            {{ record.address }}
          </span>
          <span class="time-range">
            <van-icon name="clock-o" size="12" color="#969799" />
            {{ formatTime(record.startTime) }} - {{ formatTime(record.endTime) }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.records-page {
  min-height: 100vh;
  background: #F4F7F8;

  // NavBar — brand blue bg, white text
  :deep(.van-nav-bar) {
    background: #1E74FF;
  }
  :deep(.van-nav-bar__title) {
    color: #fff;
    font-size: 18px;
    font-weight: 600;
  }
  :deep(.van-nav-bar__text),
  :deep(.van-nav-bar__arrow) {
    color: #fff;
  }
  :deep(.van-nav-bar .van-icon) {
    color: #fff;
  }
}

// Search — rounded, white bg
.search-wrapper {
  padding: 8px 12px 0;
  background: #F4F7F8;

  :deep(.van-search__content) {
    border-radius: 10px;
    background: #fff;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }
}

// Tabs
:deep(.van-tabs) {
  background: #fff;
}

:deep(.van-tabs__wrap) {
  padding: 0 8px;
}

:deep(.van-tab) {
  font-size: 14px;
}

// Record List
.record-list {
  padding: 8px 12px 16px;
}

.record-card {
  background: #fff;
  border-radius: 10px;
  padding: 14px 16px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: box-shadow 0.15s ease;

  &:active {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }
}

.record-card__header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 10px;
}

.record-card__title {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.record-card__body {
  margin-bottom: 8px;
}

.record-info {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: var(--color-text-regular);
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.record-card__footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 8px;
  border-top: 1px solid var(--color-border-light);
}

.address-text {
  font-size: 12px;
  color: var(--color-text-placeholder);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.time-range {
  font-size: 12px;
  color: var(--color-text-placeholder);
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
}
</style>
