<template>
  <div class="page-container">
    <el-card shadow="hover" class="filter-card">
      <div class="filter-actions">
        <div class="filter-warehouse">
          <span class="filter-label">仓库</span>
          <el-input
            v-model="warehouse"
            placeholder="如 WH01"
            clearable
            @keyup.enter="loadData"
          />
        </div>
        <el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
      </div>
      <el-alert type="info" show-icon :closable="false" class="hint">
        拓展资源总占用 = 已绑定数量 + Redis 中在途预占名额的任务链数量。
      </el-alert>
    </el-card>

    <div class="board-toolbar">
      <div class="board-titles">
        <span class="board-title">拓展资源</span>
        <span v-if="snapshots.length" class="board-sub">{{ snapshots[0].warehouse }}</span>
      </div>
      <div class="board-actions">
        <span class="board-hint">点击预占任务链查看详情 · 预占数据来自 Redis Set</span>
        <el-button type="primary" size="small" :loading="loading" @click="loadData">刷新</el-button>
      </div>
    </div>

    <div class="board-body" v-loading="loading">
      <el-empty v-if="!snapshots.length && !loading" description="暂无数据，请确认仓库编码" />
      <div v-else class="resource-list">
        <el-card
          v-for="resource in snapshots"
          :key="resource.resourceType"
          shadow="hover"
          class="resource-card"
        >
          <template #header>
            <div class="resource-head">
              <div class="resource-title-wrap">
                <span class="resource-title">{{ resource.resourceName }}</span>
                <span class="resource-type">{{ resource.resourceType }}</span>
              </div>
              <el-tag :type="capacityStressType(resource)" size="small" effect="plain">
                占用 {{ resource.totalCount }} / 容量 {{ resource.capacity }}
              </el-tag>
            </div>
          </template>

          <div class="resource-layout">
            <div class="summary-panel">
              <div class="capacity-bar">
                <el-progress
                  :percentage="capacityPercentage(resource)"
                  :status="capacityProgressStatus(resource)"
                  :stroke-width="12"
                  striped
                  striped-flow
                />
              </div>

              <div class="stats-grid">
                <div class="stat-block">
                  <span class="stat-k">已绑定</span>
                  <span class="stat-v">{{ resource.boundCount }}</span>
                </div>
                <div class="stat-block">
                  <span class="stat-k">在途预占</span>
                  <span class="stat-v">{{ resource.reservedCount }}</span>
                </div>
                <div class="stat-block">
                  <span class="stat-k">总占用</span>
                  <span class="stat-v">{{ resource.totalCount }}</span>
                </div>
                <div class="stat-block">
                  <span class="stat-k">剩余容量</span>
                  <span class="stat-v">{{ resource.remainingCapacity }}</span>
                </div>
              </div>
            </div>

            <div class="chains-panel">
              <div class="chains-head">
                <span class="chains-title">预占任务链</span>
                <span v-if="resource.reservedChainCodes?.length" class="chains-n">
                  {{ resource.reservedChainCodes.length }} 条
                </span>
              </div>

              <div v-if="resource.reservedChainCodes?.length" class="chains-scroll">
                <button
                  v-for="c in resource.reservedChainCodes"
                  :key="`${resource.resourceType}-${c}`"
                  type="button"
                  class="chain-row"
                  @click="goChainDetail(c)"
                >
                  <span class="chain-row__code">{{ c }}</span>
                  <span class="chain-row__sep" aria-hidden="true">：</span>
                  <span class="chain-row__containers">{{ chainContainersText(c) }}</span>
                </button>
              </div>
              <div v-else class="chains-empty">无</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'ExtensionResourceView' })
import {
  getExtensionResourceSnapshots,
  type ExtensionResourceSnapshotVO,
} from '@/api/extensionResource'
import { getChainDetail, type TaskChainDetailVO } from '@/api/task'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const warehouse = ref('WH01')
const snapshots = ref<ExtensionResourceSnapshotVO[]>([])
const loading = ref(false)

/** 任务链号 -> 容器串（冒号拼接）；载入中 / 失败为占位标记 */
const chainContainersLabel = ref<Record<string, string>>({})

function capacityPercentage(resource: ExtensionResourceSnapshotVO): number {
  if (resource.capacity <= 0) return 0
  return Math.min(100, Math.round((resource.totalCount / resource.capacity) * 100))
}

function capacityStressType(resource: ExtensionResourceSnapshotVO): 'success' | 'warning' | 'danger' | 'info' {
  if (resource.capacity <= 0) return resource.totalCount ? 'danger' : 'info'
  if (resource.totalCount >= resource.capacity) return 'danger'
  if (resource.totalCount / resource.capacity >= 0.8) return 'warning'
  return 'success'
}

function capacityProgressStatus(resource: ExtensionResourceSnapshotVO): 'success' | 'warning' | 'exception' | undefined {
  const type = capacityStressType(resource)
  if (type === 'danger') return 'exception'
  if (type === 'warning') return 'warning'
  if (type === 'success') return 'success'
  return undefined
}

function collectContainersFromDetail(d: TaskChainDetailVO): string[] {
  const out: string[] = []
  const push = (v: string | undefined) => {
    const t = v?.trim()
    if (t) out.push(t)
  }
  push(d.sourceContainer)
  for (const task of d.tasks ?? []) {
    push(task.sourceContainer)
  }
  return [...new Set(out)]
}

function chainContainersText(code: string): string {
  const v = chainContainersLabel.value[code]
  if (v === '__loading__') return '容器载入中...'
  if (v === '__error__') return '容器加载失败'
  return v ?? '-'
}

async function loadData() {
  const wh = warehouse.value?.trim()
  if (!wh) {
    ElMessage.warning('请输入仓库编码')
    return
  }
  loading.value = true
  chainContainersLabel.value = {}
  try {
    const res = await getExtensionResourceSnapshots(wh)
    snapshots.value = res.data || []
    const codes = [
      ...new Set(snapshots.value.flatMap((s) => s.reservedChainCodes ?? []).filter((c) => !!c?.trim())),
    ]
    for (const c of codes) {
      chainContainersLabel.value[c] = '__loading__'
    }
    await Promise.all(
      codes.map(async (code) => {
        try {
          const detailRes = await getChainDetail(code)
          const list = collectContainersFromDetail(detailRes.data)
          chainContainersLabel.value[code] = list.length ? list.join(':') : '-'
        } catch {
          chainContainersLabel.value[code] = '__error__'
        }
      }),
    )
  } catch {
    snapshots.value = []
    chainContainersLabel.value = {}
  } finally {
    loading.value = false
  }
}

function goChainDetail(code: string) {
  if (!code) return
  router.push(`/task/chain/${encodeURIComponent(code)}`)
}

onMounted(loadData)
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-card .hint {
  margin-top: 12px;
}

.filter-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 12px 16px;
}

.filter-warehouse {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 200px;
  flex: 1;
  max-width: 280px;
}

.filter-label {
  font-size: 13px;
  color: var(--el-text-color-regular);
}

.board-toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.board-titles {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 8px 12px;
}

.board-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.board-sub {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.board-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px 12px;
}

.board-hint {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  max-width: min(420px, 100%);
  line-height: 1.4;
}

.board-body {
  min-height: 120px;
}

.resource-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.resource-card :deep(.el-card__header) {
  padding: 14px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.resource-card :deep(.el-card__body) {
  padding: 16px;
}

.resource-head,
.chains-head {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.resource-title-wrap {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 6px 10px;
}

.resource-title,
.chains-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.resource-type {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.resource-layout {
  display: grid;
  grid-template-columns: minmax(280px, 420px) minmax(0, 1fr);
  gap: 16px;
}

.summary-panel,
.chains-panel {
  min-width: 0;
}

.capacity-bar {
  margin-bottom: 16px;
}

.capacity-bar :deep(.el-progress-bar__inner--striped.el-progress-bar__inner--striped-flow) {
  animation-duration: 12s !important;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.stat-block {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 0;
  padding: 12px;
  border-radius: 8px;
  background: var(--el-fill-color-lighter);
}

.stat-k {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.stat-v {
  font-size: 22px;
  font-weight: 600;
  line-height: 1.2;
  color: var(--el-text-color-primary);
  font-variant-numeric: tabular-nums;
}

.chains-n {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.chains-scroll {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 6px;
  max-height: 360px;
  overflow-x: auto;
  overflow-y: auto;
  padding: 2px;
  margin: 0 -2px;
  scrollbar-gutter: stable;
}

.chain-row {
  display: inline-flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 0 4px;
  width: max-content;
  max-width: none;
  margin: 0;
  padding: 6px 10px;
  box-sizing: border-box;
  text-align: left;
  font: inherit;
  line-height: 1.45;
  white-space: nowrap;
  color: var(--el-text-color-primary);
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  cursor: pointer;
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease,
    box-shadow 0.15s ease;
}

.chain-row:hover {
  background: var(--el-fill-color-blank);
  border-color: var(--el-color-primary-light-7);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}

.chain-row:active {
  background: var(--el-fill-color-light);
}

.chain-row:focus-visible {
  outline: 2px solid var(--el-color-primary-light-5);
  outline-offset: 1px;
}

.chain-row__code {
  font-size: 13px;
  font-weight: 600;
  color: var(--el-color-primary);
  letter-spacing: 0;
  flex-shrink: 0;
}

.chain-row__sep {
  font-size: 13px;
  color: var(--el-text-color-placeholder);
  flex-shrink: 0;
}

.chain-row__containers {
  font-size: 13px;
  font-weight: 400;
  color: var(--el-text-color-regular);
  flex-shrink: 0;
  font-variant-numeric: tabular-nums;
}

.chains-empty {
  font-size: 13px;
  color: var(--el-text-color-placeholder);
}

@media (max-width: 900px) {
  .resource-layout {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 640px) {
  .filter-warehouse {
    max-width: none;
  }

  .board-actions {
    width: 100%;
    justify-content: space-between;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
