<template>
  <div class="dashboard">
    <!-- ========== PC 端 ========== -->
    <template v-if="!isMobile">
      <el-row :gutter="20" class="stat-row">
        <el-col :span="6" v-for="s in statCards" :key="s.label">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-info">
                <div class="stat-label">{{ s.label }}</div>
                <div class="stat-value">{{ s.value }}</div>
              </div>
              <el-icon class="stat-icon" :style="{ color: s.color }"><component :is="s.icon" /></el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="16">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>最近任务链</span>
                <el-button text type="primary" @click="$router.push('/task/chain')">查看全部</el-button>
              </div>
            </template>
            <el-table :data="recentChains" stripe size="small">
              <el-table-column prop="code" label="任务链编号" min-width="160" />
              <el-table-column prop="type" label="类型" width="120">
                <template #default="{ row }">
                  <el-tag size="small">{{ typeMap[row.type] || row.type }}</el-tag>
                </template>
              </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag v-bind="getChainStatusTag(row.status)" size="small">
                  {{ chainStatusMap[row.status] || row.status }}
                </el-tag>
              </template>
            </el-table-column>
              <el-table-column prop="sourceContainer" label="源容器" width="130" />
              <el-table-column prop="createTime" label="创建时间" width="170" />
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="{ row }">
                  <el-button text type="primary" size="small" @click="$router.push(`/task/chain/${row.code}`)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>提升机状态</span>
                <el-button text type="primary" @click="$router.push('/elevator')">管理</el-button>
              </div>
            </template>
            <div v-for="e in elevators" :key="e.id" class="elevator-item">
              <div class="elevator-header">
                <span class="elevator-name">提升机 #{{ e.id }}</span>
                <el-tag :type="e.enable ? 'success' : 'danger'" size="small">
                  {{ e.enable ? '启用' : '禁用' }}
                </el-tag>
              </div>
              <div class="elevator-detail">
                <span>工作任务: {{ e.workingTask || '空闲' }}</span>
              </div>
              <div class="elevator-detail">
                <span>负载任务数: {{ e.taskChains?.length ?? 0 }}</span>
              </div>
            </div>
            <el-empty v-if="elevators.length === 0" description="暂无数据" :image-size="60" />
          </el-card>
        </el-col>
      </el-row>
    </template>

    <!-- ========== 移动端 ========== -->
    <template v-else>
      <!-- 统计卡片 2x2 -->
      <div class="m-stat-grid">
        <div v-for="s in statCards" :key="s.label" class="m-stat-card" :style="{ borderLeftColor: s.color }">
          <div class="m-stat-value">{{ s.value }}</div>
          <div class="m-stat-label">{{ s.label }}</div>
        </div>
      </div>

      <!-- 最近任务链 -->
      <div class="m-section">
        <div class="m-section-header">
          <span class="m-section-title">最近任务链</span>
          <el-button text type="primary" size="small" @click="$router.push('/task/chain')">全部</el-button>
        </div>
        <div
          v-for="row in recentChains"
          :key="row.code"
          class="m-recent-item"
          @click="$router.push(`/task/chain/${row.code}`)"
        >
          <div class="m-recent-top">
            <span class="m-recent-code">{{ row.code }}</span>
            <el-tag v-bind="getChainStatusTag(row.status)" size="small">
              {{ chainStatusMap[row.status] || row.status }}
            </el-tag>
          </div>
          <div class="m-recent-bottom">
            <el-tag size="small" type="info">{{ typeMap[row.type] || row.type }}</el-tag>
            <span class="m-recent-time">{{ row.createTime }}</span>
          </div>
        </div>
        <el-empty v-if="recentChains.length === 0" description="暂无数据" :image-size="48" />
      </div>

      <!-- 提升机状态 -->
      <div class="m-section">
        <div class="m-section-header">
          <span class="m-section-title">提升机状态</span>
          <el-button text type="primary" size="small" @click="$router.push('/elevator')">管理</el-button>
        </div>
        <div v-for="e in elevators" :key="e.id" class="m-elevator-item">
          <div class="m-elevator-top">
            <span class="m-elevator-name">提升机 #{{ e.id }}</span>
            <el-tag :type="e.enable ? 'success' : 'danger'" size="small">
              {{ e.enable ? '启用' : '禁用' }}
            </el-tag>
          </div>
          <div class="m-elevator-detail">{{ e.workingTask || '空闲' }}</div>
        </div>
        <el-empty v-if="elevators.length === 0" description="暂无数据" :image-size="48" />
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'DashboardView' })
import { computed, onMounted, reactive, ref } from 'vue'
import { Loading, Clock, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import { getChainPage, getChainStats, type TaskChainVO } from '@/api/task'
import { getElevatorList, type ElevatorVO } from '@/api/elevator'
import { chainStatusMap, getChainStatusTag } from '@/constants/chainStatus'
import { useDevice } from '@/composables/useDevice'

const { isMobile } = useDevice()
const stats = reactive({ inProgress: 0, waiting: 0, completed: 0, failed: 0 })
const recentChains = ref<TaskChainVO[]>([])
const elevators = ref<ElevatorVO[]>([])

const statCards = computed(() => [
  { label: '进行中任务链', value: stats.inProgress, color: '#409eff', icon: Loading },
  { label: '等待中任务链', value: stats.waiting, color: '#e6a23c', icon: Clock },
  { label: '今日完成', value: stats.completed, color: '#67c23a', icon: CircleCheck },
  { label: '今日失败', value: stats.failed, color: '#f56c6c', icon: CircleClose },
])

const typeMap: Record<string, string> = {
  INBOUND: '入库', QUICK_PALLET_INBOUND: '托盘快速入库',
  OUTBOUND: '出库', OUTBOUND_NEW: '拣货出库(新模版)',
  OUTBOUND_NO_WAIT: '出库(不等待)', OUTBOUND_NO_WAIT_NEW: '直出模式(新模版)', MOVE: '移库', MOVE_NEW: '移库(新模版)',
}

async function loadData() {
  try {
    const [chainRes, elevatorRes, statsRes] = await Promise.all([
      getChainPage({ page: 1, size: 10 }),
      getElevatorList(),
      getChainStats(),
    ])
    recentChains.value = chainRes.data.records || []
    elevators.value = elevatorRes.data || []
    const s = statsRes.data
    stats.inProgress = s.inProgress
    stats.waiting = s.waiting
    stats.completed = s.completedToday
    stats.failed = s.failedToday
  } catch { /* request interceptor handles errors */ }
}

onMounted(loadData)
</script>

<style scoped>
/* ===== PC ===== */
.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.stat-icon {
  font-size: 40px;
  opacity: 0.8;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.elevator-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.elevator-item:last-child {
  border-bottom: none;
}

.elevator-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.elevator-name {
  font-weight: 600;
  font-size: 14px;
}

.elevator-detail {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

/* ===== 移动端 ===== */
.m-stat-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.m-stat-card {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  border-left: 3px solid;
}

.m-stat-value {
  font-size: 26px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
}

.m-stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.m-section {
  background: #fff;
  border-radius: 12px;
  padding: 14px;
  margin-top: 10px;
}

.m-section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.m-section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.m-recent-item {
  padding: 10px 0;
  border-bottom: 1px solid #f5f7fa;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
}

.m-recent-item:last-child {
  border-bottom: none;
}

.m-recent-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.m-recent-code {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 70%;
}

.m-recent-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.m-recent-time {
  font-size: 11px;
  color: #c0c4cc;
}

.m-elevator-item {
  padding: 10px 0;
  border-bottom: 1px solid #f5f7fa;
}

.m-elevator-item:last-child {
  border-bottom: none;
}

.m-elevator-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.m-elevator-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.m-elevator-detail {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
