<template>
  <view class="sub-page">
    <TopBar title="数据可视化" show-back />

    <view v-if="loading" class="py-20 text-center">
      <text class="empty-text">加载中...</text>
    </view>

    <view v-else class="px-4 pt-3">
      <!-- 任务统计 -->
      <view class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">任务统计</text>
          <text class="realtime-tag">实时</text>
        </view>
        <view class="grid grid-cols-2 gap-3">
          <view class="stat-card">
            <view class="stat-bar"></view>
            <text class="stat-value">{{ stats.task?.total || 0 }}</text>
            <text class="stat-label">总任务</text>
          </view>
          <view class="stat-card">
            <view class="stat-bar"></view>
            <text class="stat-value stat-value-gold">{{ stats.task?.pending || 0 }}</text>
            <text class="stat-label">待处理</text>
          </view>
          <view class="stat-card">
            <view class="stat-bar"></view>
            <text class="stat-value">{{ stats.task?.completed || 0 }}</text>
            <text class="stat-label">已完成</text>
          </view>
          <view class="stat-card">
            <view class="stat-bar"></view>
            <text class="stat-value stat-value-blue">{{ stats.task?.inProgress || 0 }}</text>
            <text class="stat-label">进行中</text>
          </view>
        </view>
      </view>

      <!-- 任务时段统计 -->
      <view class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">任务时段统计</text>
          <text class="realtime-tag">图表</text>
        </view>
        <ChartView type="ring" :canvasId="'task-time-chart'" :data="taskTimeData" :height="240" />
      </view>

      <!-- 任务趋势 -->
      <view class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">任务趋势</text>
          <text class="realtime-tag">图表</text>
        </view>
        <ChartView type="line" :canvasId="'task-trend-chart'" :data="taskTrendData" :height="220" />
      </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="realtime-tag">实时</text>
        </view>
        <view class="info-row">
          <text class="info-label">总车辆数</text>
          <text class="info-value">{{ stats.vehicle?.total || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">可用</text>
          <text class="info-value">{{ stats.vehicle?.available || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">使用中</text>
          <text class="info-value">{{ stats.vehicle?.inUse || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">维修中</text>
          <text class="info-value">{{ stats.vehicle?.maintenance || 0 }}</text>
        </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="realtime-tag">实时</text>
        </view>
        <view class="info-row">
          <text class="info-label">总人数</text>
          <text class="info-value">{{ stats.personnel?.total || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">在岗</text>
          <text class="info-value">{{ stats.personnel?.onDuty || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">施工中</text>
          <text class="info-value">{{ stats.personnel?.working || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">休息</text>
          <text class="info-value">{{ stats.personnel?.rest || 0 }}</text>
        </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="realtime-tag">实时</text>
        </view>
        <view class="info-row">
          <text class="info-label">待命班组</text>
          <text class="info-value">{{ stats.emergency?.standbyTeams || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">待命车辆</text>
          <text class="info-value">{{ stats.emergency?.standbyVehicles || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">应急任务</text>
          <text class="info-value">{{ stats.emergency?.emergencyTasks || 0 }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import TopBar from '../../components/common/TopBar.vue'
import { getDashboardStats } from '../../api/dashboard'
import { getTaskList } from '../../api/task'
import { formatDate } from '../../utils'

import ChartView from '../../components/common/ChartView.vue'

const loading = ref(true)
const stats = ref<Record<string, any>>({})
const allTasks = ref<any[]>([])

const taskTimeData = computed(() => {
  const periods = [
    { label: '凌晨', color: '#8e8e93' },
    { label: '上午', color: '#34c759' },
    { label: '下午', color: '#4f8ef7' },
    { label: '晚上', color: '#ff9500' },
    { label: '未设置', color: '#d1d5db' },
  ]

  return periods
    .map((period) => ({
      ...period,
      value: allTasks.value.filter((t: any) => getTaskPeriod(t) === period.label).length,
    }))
    .filter((item) => item.value > 0)
})

function getTaskPeriod(task: any): string {
  const range = task.planTimeRange
  if (range) {
    const map: Record<string, string> = {
      morning: '上午',
      afternoon: '下午',
      evening: '晚上',
      night: '晚上',
      dawn: '凌晨',
      early_morning: '凌晨',
    }
    if (map[range]) return map[range]
  }

  const timeStr = task.scheduleTime || task.serviceTime || task.expectedArrivalTime
  if (!timeStr || typeof timeStr !== 'string') return '未设置'

  const match = timeStr.match(/(\d{1,2}):\d{2}/)
  if (!match) return '未设置'

  const hour = parseInt(match[1], 10)
  if (hour >= 0 && hour < 6) return '凌晨'
  if (hour >= 6 && hour < 12) return '上午'
  if (hour >= 12 && hour < 18) return '下午'
  if (hour >= 18 && hour < 24) return '晚上'
  return '未设置'
}

const taskTrendData = computed(() => {
  const days = 7
  const result = []
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    const dateStr = formatDate(date, 'YYYY-MM-DD')
    const label = formatDate(date, 'MM-DD')
    const count = allTasks.value.filter((t: any) => {
      const taskDate = t.planDate || t.scheduleDate || t.serviceDate || t.createTime
      if (!taskDate) return false
      const normalized = formatDate(taskDate, 'YYYY-MM-DD')
      return normalized === dateStr
    }).length
    result.push({ label, value: count })
  }
  return result
})

onMounted(async () => {
  loading.value = true
  try {
    const [res, taskRes] = await Promise.all([
      getDashboardStats(),
      getTaskList(1, 1000),
    ])
    stats.value = res
    allTasks.value = taskRes.rows || []
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.sub-page {
  max-width: 430px;
  margin: 0 auto;
  min-height: 100vh;
  background-color: #f6fbf9;
  padding-bottom: 24px;
}

.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: 24px;
  box-shadow: 0 18px 50px -12px rgba(54, 143, 111, 0.28);
  overflow: hidden;
  margin-bottom: 12px;
}

.section-head {
  display: flex;
  align-items: center;
  padding: 16px 16px 12px;
}

.section-head-inner {
  display: flex;
  align-items: center;
}

.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;
}

.realtime-tag {
  font-size: 12px;
  color: #9ca3af;
}

.stat-card {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 88px;
  padding: 14px 6px 12px;
  border-radius: 16px;
  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-value-gold {
  color: #b7791f;
}

.stat-value-blue {
  color: #2563eb;
}

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

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 13px 16px;
  border-top: 1px solid rgba(164, 216, 152, 0.18);
}

.info-label {
  font-size: 14px;
  color: #4b5563;
}

.info-value {
  font-size: 14px;
  font-weight: 600;
  color: #368f6f;
}

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