<script setup lang="ts">
/**
 * 防汛指令列表 — 接收与处理防汛指令
 *
 * 展示下发的防汛指令，支持按状态筛选、搜索和下拉刷新，
 * 每条指令显示级别标签和发布时间。
 * DESIGN: #1E74FF NavBar, #F4F7F8 bg, white cards border-radius 10px.
 */
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()

// ── 类型 ──
type InstructionStatus = 'pending' | 'accepted' | 'completed'
type InstructionLevel = 'urgent' | 'normal'

interface Instruction {
  id: number
  title: string
  level: InstructionLevel
  from: string
  time: string
  status: InstructionStatus
}

// ── 状态 ──
const searchText = ref('')
const activeTab = ref(0)
const loading = ref(false)
const refreshing = ref(false)

// ── 映射 ──
const statusMap: Record<InstructionStatus, string> = {
  pending: '待接收',
  accepted: '已接收',
  completed: '已完成',
}

const statusStyleMap: Record<InstructionStatus, { type: 'warning' | 'primary' | 'success'; bg: string }> = {
  pending: { type: 'warning', bg: 'var(--color-warning-bg)' },
  accepted: { type: 'primary', bg: 'var(--color-primary-bg)' },
  completed: { type: 'success', bg: 'var(--color-success-bg)' },
}

const levelMap: Record<InstructionLevel, string> = {
  urgent: '紧急',
  normal: '普通',
}

const levelStyleMap: Record<InstructionLevel, { color: string; bg: string }> = {
  urgent: { color: '#fff', bg: '#ee0a24' },
  normal: { color: '#fff', bg: '#1989fa' },
}

// ── 数据 ──
const instructions = ref<Instruction[]>([])

const mockInstructions: Instruction[] = [
  { id: 1, title: '启动III级防汛应急响应', level: 'urgent', from: '市防汛指挥部', time: '2025-06-15 08:00', status: 'pending' },
  { id: 2, title: '河道巡查任务通知', level: 'normal', from: '水务局', time: '2025-06-14 14:30', status: 'accepted' },
  { id: 3, title: '泵站设备检修通知', level: 'normal', from: '运维中心', time: '2025-06-13 09:00', status: 'completed' },
  { id: 4, title: '重点积水路段值守', level: 'urgent', from: '市政管理处', time: '2025-06-15 07:30', status: 'pending' },
  { id: 5, title: '防洪物资调配通知', level: 'urgent', from: '市防汛指挥部', time: '2025-06-15 09:00', status: 'pending' },
  { id: 6, title: '排水管网排查任务', level: 'normal', from: '水务局', time: '2025-06-14 10:00', status: 'accepted' },
]

// ── 计算属性 ──
const filteredList = computed(() => {
  let list = instructions.value
  if (searchText.value) {
    const kw = searchText.value.toLowerCase()
    list = list.filter(i =>
      i.title.toLowerCase().includes(kw) ||
      i.from.toLowerCase().includes(kw)
    )
  }
  const tabStatus: (InstructionStatus | null)[] = [null, 'pending', 'accepted', 'completed']
  const filter = tabStatus[activeTab.value]
  if (filter) list = list.filter(i => i.status === filter)
  return list
})

const pendingCount = computed(() => instructions.value.filter(i => i.status === 'pending').length)

// ── 方法 ──
async function fetchData() {
  loading.value = true
  await new Promise(resolve => setTimeout(resolve, 400))
  instructions.value = mockInstructions
  loading.value = false
}

async function onRefresh() {
  refreshing.value = true
  await new Promise(resolve => setTimeout(resolve, 600))
  instructions.value = [...mockInstructions]
  refreshing.value = false
  showToast('刷新成功')
}

function goReceive(item: Instruction) {
  router.push({ path: '/instructionReceive', query: { id: item.id } })
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="page-container">
    <!-- 导航栏 -->
    <van-nav-bar title="防汛指令" left-arrow fixed placeholder @click-left="router.back()" />

    <!-- 搜索栏 -->
    <van-search v-model="searchText" placeholder="搜索指令标题、来源单位" shape="round" />

    <!-- 标签页 -->
    <van-tabs v-model:active="activeTab" sticky color="var(--color-primary)">
      <van-tab title="全部" />
      <van-tab :title="`待接收${pendingCount ? ` (${pendingCount})` : ''}`" />
      <van-tab title="已接收" />
      <van-tab title="已完成" />
    </van-tabs>

    <!-- 下拉刷新 + 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="pull-refresh-wrap">
      <!-- 加载骨架 -->
      <div v-if="loading" class="skeleton-wrap">
        <div v-for="i in 4" :key="i" class="skeleton-card">
          <van-skeleton title :row="2" />
        </div>
      </div>

      <!-- 空状态 -->
      <van-empty v-else-if="filteredList.length === 0" description="暂无指令">
        <van-button type="primary" size="small" @click="onRefresh">刷新</van-button>
      </van-empty>

      <!-- 指令卡片列表 -->
      <div v-else class="card-list">
        <div
          v-for="item in filteredList"
          :key="item.id"
          class="inst-card"
          @click="goReceive(item)"
        >
          <div class="card-hd">
            <div class="card-title-wrap">
              <span
                class="level-badge"
                :style="{ background: levelStyleMap[item.level].bg, color: levelStyleMap[item.level].color }"
              >
                {{ levelMap[item.level] }}
              </span>
              <span class="card-title">{{ item.title }}</span>
            </div>
            <span
              class="status-badge"
              :style="{ background: statusStyleMap[item.status].bg }"
            >
              <van-tag :type="statusStyleMap[item.status].type" size="medium">
                {{ statusMap[item.status] }}
              </van-tag>
            </span>
          </div>
          <div class="card-bd">
            <div class="card-info">
              <van-icon name="user-o" size="14" />
              <span>{{ item.from }}</span>
            </div>
            <div class="card-info">
              <van-icon name="clock-o" size="14" />
              <span>{{ item.time }}</span>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: var(--color-bg-page);

  :deep(.van-nav-bar) {
    background: var(--color-primary);
    --van-nav-bar-title-text-color: #fff;
    --van-nav-bar-text-color: #fff;
    --van-nav-bar-icon-color: #fff;
  }
}

.pull-refresh-wrap {
  min-height: calc(100vh - 140px);
}

// ── 骨架屏 ──
.skeleton-wrap {
  padding: 8px 16px;
}
.skeleton-card {
  padding: 16px;
  margin-bottom: 8px;
  background: var(--color-bg-card);
  border-radius: 10px;
}

// ── 指令卡片 ──
.card-list {
  padding: 8px 12px;
}

.inst-card {
  background: var(--color-bg-card);
  border-radius: 10px;
  padding: 16px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  cursor: pointer;

  &:active {
    opacity: 0.85;
  }

  .card-hd {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
    gap: 8px;
  }

  .card-title-wrap {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    flex: 1;
    min-width: 0;
  }

  .level-badge {
    display: inline-block;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
    white-space: nowrap;
    flex-shrink: 0;
  }

  .card-title {
    font-size: 15px;
    font-weight: 600;
    color: var(--color-text-primary);
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .card-bd {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }

  .card-info {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    color: var(--color-text-secondary);
  }
}
</style>
