<template>
  <aside class="engineering-statistics-panel" data-testid="engineering-statistics-panel" aria-label="生态工程分析统计" aria-live="polite">
    <header class="statistics-head">
      <div>
        <span>分析建议</span>
        <small>{{ statistics.engineeringName }} · {{ statistics.scopeName }}</small>
      </div>
      <strong>{{ adviceSource }}</strong>
    </header>

    <section class="advice-section">
      <div v-if="adviceLoading" class="advice-loading" data-testid="engineering-advice-status">
        <span class="advice-spinner"></span>
        <span>DeepSeek 正在自动生成分析建议…</span>
      </div>
      <ol v-else class="advice-list">
        <li v-for="(item, index) in adviceItems" :key="`${index}-${item}`">{{ item }}</li>
      </ol>
      <p v-if="adviceError" class="advice-error">{{ adviceError }}</p>
    </section>
  </aside>
</template>

<script setup>
import { computed, ref, watch } from "vue"
import { generateEngineeringAdvice } from "@/services/engineeringAdviceApi"

const props = defineProps({
  statistics: {
    type: Object,
    required: true,
  },
})

const adviceLoading = ref(false)
const adviceText = ref("")
const adviceError = ref("")
let adviceRequestId = 0

const distributionRows = computed(() => Array.isArray(props.statistics?.distribution) ? props.statistics.distribution : [])
const ruleAdvice = computed(() => {
  const items = []
  const first = distributionRows.value[0]
  if (first) items.push(`优先核查${first.name}等候选面积较集中的区域，进一步评价地块连片度和施工可达性。`)
  if (Number(props.statistics?.excludedCount || 0) > 0) {
    items.push(`对已排除的 ${formatCount(props.statistics.excludedCount)} 个历史项目相交图斑复核项目边界、实施年份和工程类型，避免重复建设。`)
  } else {
    items.push("本次年份条件未排除历史项目相交图斑，建议结合项目库更新时间确认筛选时段是否完整。")
  }
  items.push("候选结果用于工程初筛，立项前仍需完成权属核验、现场踏勘和实施方案论证。")
  return items
})
const adviceItems = computed(() => {
  const generated = String(adviceText.value || "")
    .split(/\n+/)
    .map((item) => item.replace(/^\s*(?:[-•]|\d+[.、)])\s*/, "").trim())
    .filter(Boolean)
  return generated.length ? generated.slice(0, 5) : ruleAdvice.value
})
const adviceSource = computed(() => {
  if (adviceLoading.value) return "DeepSeek自动研判中"
  if (adviceText.value) return "DeepSeek研判"
  return "系统初步建议"
})

watch(() => props.statistics, (statistics) => {
  const requestId = ++adviceRequestId
  adviceText.value = ""
  adviceError.value = ""
  adviceLoading.value = false
  if (statistics) requestDeepSeekAdvice(requestId, statistics)
}, { immediate: true })

async function requestDeepSeekAdvice(requestId, statistics) {
  adviceLoading.value = true
  adviceError.value = ""
  try {
    const result = await generateEngineeringAdvice(statistics)
    if (requestId !== adviceRequestId) return
    adviceText.value = String(result?.advice || result?.content || "").trim()
    if (!adviceText.value) throw new Error("DeepSeek未返回有效建议")
  } catch (error) {
    if (requestId !== adviceRequestId) return
    adviceError.value = /404/.test(String(error?.message || ""))
      ? "DeepSeek建议接口尚未部署，已保留系统初步建议。"
      : error?.message || "DeepSeek暂时不可用，已保留系统初步建议。"
  } finally {
    if (requestId === adviceRequestId) adviceLoading.value = false
  }
}

function formatCount(value) {
  const number = Number(value)
  return Number.isFinite(number) ? Math.round(number).toLocaleString("zh-CN") : "0"
}

</script>

<style scoped lang="scss">
.engineering-statistics-panel {
  position: absolute;
  z-index: 8;
  top: 168px;
  right: 32px;
  width: 390px;
  max-height: calc(100% - 284px);
  overflow-y: auto;
  padding: 15px 16px 16px;
  border: 1px solid var(--v22-border, rgba(91, 224, 244, 0.46));
  border-radius: 2px;
  background:
    radial-gradient(circle at 88% 0, rgba(74, 210, 233, 0.12), transparent 38%),
    linear-gradient(160deg, rgba(6, 38, 54, 0.96), rgba(2, 20, 32, 0.93));
  box-shadow:
    inset 0 1px 0 rgba(186, 247, 255, 0.12),
    inset 0 0 0 1px rgba(91, 224, 244, 0.08),
    0 12px 28px rgba(0, 8, 16, 0.3);
  box-sizing: border-box;
  pointer-events: auto;
  scrollbar-width: thin;
  scrollbar-color: rgba(48, 220, 255, 0.45) transparent;
}

.statistics-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  padding-left: 10px;
  border-left: 3px solid #30dcff;
  > div { display: grid; gap: 2px; }
  span { color: #fff; font-size: 16px; font-weight: 800; }
  small { color: rgba(211, 244, 250, 0.58); font-size: 10px; }
  > strong {
    padding: 3px 7px;
    border: 1px solid rgba(126, 251, 246, 0.22);
    border-radius: 2px;
    background: rgba(48, 220, 255, 0.07);
    color: var(--v22-accent, #7efbf6);
    font-size: 11px;
    font-weight: 650;
    line-height: 16px;
  }
}

.statistics-kpis {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 6px;
  margin-top: 13px;
  > div {
    min-width: 0;
    min-height: 64px;
    padding: 8px 6px 7px;
    border: 1px solid rgba(48, 220, 255, 0.15);
    border-radius: 2px;
    background: rgba(3, 23, 37, 0.52);
    box-sizing: border-box;
    text-align: center;
  }
  span { display: block; overflow: hidden; color: var(--v22-text-muted, rgba(215, 247, 252, 0.62)); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
  strong { display: inline-block; margin-top: 5px; color: #eafeff; font-family: var(--screen-font-number, D-DIN, Arial, sans-serif); font-size: 20px; line-height: 23px; }
  strong.is-warning { color: #f2b84b; }
  small { margin-left: 2px; color: rgba(215, 247, 252, 0.58); font-size: 9px; }
}

.statistics-section { margin-top: 14px; }
.statistics-section-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid rgba(48, 220, 255, 0.18);
  strong { color: #dffaff; font-size: 12px; }
  em { color: rgba(205, 241, 248, 0.48); font-size: 9px; font-style: normal; }
  > div { display: flex; align-items: center; gap: 8px; }
}

.distribution-chart {
  display: grid;
  gap: 9px;
  margin-top: 9px;
}
.distribution-label {
  display: grid;
  grid-template-columns: 18px minmax(0, 1fr) auto;
  align-items: center;
  gap: 5px;
  > span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 16px;
    height: 16px;
    border: 1px solid rgba(48, 220, 255, 0.24);
    border-radius: 2px;
    color: rgba(126, 251, 246, 0.82);
    font: 9px var(--screen-font-number, D-DIN, Arial, sans-serif);
  }
  strong { overflow: hidden; color: rgba(235, 253, 255, 0.9); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
  em { display: flex; align-items: baseline; gap: 5px; color: rgba(213, 247, 251, 0.58); font-style: normal; }
  em b { color: #bff8ff; font: 10px var(--screen-font-number, D-DIN, Arial, sans-serif); }
  em small { font: 9px var(--screen-font-number, D-DIN, Arial, sans-serif); }
}
.distribution-track {
  height: 4px;
  margin: 3px 0 0 23px;
  overflow: hidden;
  border-radius: 2px;
  background: rgba(48, 220, 255, 0.08);
  i { display: block; height: 100%; border-radius: 2px; background: linear-gradient(90deg, rgba(31, 144, 197, 0.76), #30dcff); box-shadow: 0 0 7px rgba(48, 220, 255, 0.36); }
}

.filter-composition { margin-top: 10px; }
.composition-bar {
  display: flex;
  height: 8px;
  overflow: hidden;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.05);
  i { display: block; height: 100%; }
  .is-retained { background: #30dcff; }
  .is-excluded { background: #f2b84b; }
}

.excluded-project-list {
  display: grid;
  gap: 6px;
  margin-top: 9px;
}

.excluded-project-row {
  display: grid;
  grid-template-columns: 18px minmax(0, 1fr) auto;
  align-items: center;
  gap: 7px;
  min-height: 48px;
  padding: 6px 8px;
  border: 1px solid rgba(242, 184, 75, 0.16);
  border-radius: 2px;
  background: linear-gradient(90deg, rgba(242, 184, 75, 0.07), rgba(3, 23, 37, 0.34));
  box-sizing: border-box;

  > span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 17px;
    height: 17px;
    border: 1px solid rgba(242, 184, 75, 0.38);
    border-radius: 2px;
    color: #ffd56f;
    font: 9px var(--screen-font-number, D-DIN, Arial, sans-serif);
  }

  > div {
    display: grid;
    gap: 2px;
    min-width: 0;
  }

  > div strong {
    display: -webkit-box;
    overflow: hidden;
    color: rgba(244, 253, 255, 0.9);
    font-size: 10px;
    font-weight: 600;
    line-height: 15px;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }

  > div small {
    color: var(--v22-text-muted, rgba(213, 247, 251, 0.6));
    font-size: 9px;
    line-height: 14px;
  }

  > b {
    color: #ffd56f;
    font: 600 10px var(--screen-font-number, D-DIN, Arial, sans-serif);
    white-space: nowrap;
  }
}
.composition-legend {
  display: flex;
  justify-content: space-between;
  margin-top: 7px;
  color: rgba(215, 247, 252, 0.62);
  font-size: 9px;
  span { display: flex; align-items: center; gap: 5px; }
  b { color: #eafeff; font-family: var(--screen-font-number, D-DIN, Arial, sans-serif); font-weight: 600; }
  i { width: 6px; height: 6px; }
  .is-retained { background: #30dcff; }
  .is-excluded { background: #f2b84b; }
}

.advice-list {
  display: grid;
  gap: 6px;
  margin: 9px 0 0;
  padding-left: 22px;
  color: rgba(226, 249, 252, 0.8);
  font-size: 11px;
  line-height: 18px;
  li {
    padding: 5px 7px;
    border-left: 1px solid rgba(48, 220, 255, 0.26);
    background: linear-gradient(90deg, rgba(48, 220, 255, 0.06), transparent 82%);
  }
  li::marker { color: var(--v22-accent, #7efbf6); font-family: var(--screen-font-number, D-DIN, Arial, sans-serif); font-weight: 700; }
}
.advice-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  width: 100%;
  min-height: 44px;
  margin-top: 10px;
  border: 1px solid rgba(48, 220, 255, 0.48);
  border-radius: 2px;
  background: linear-gradient(90deg, rgba(28, 155, 190, 0.26), rgba(48, 220, 255, 0.12));
  color: #eafeff;
  font-size: 11px;
  box-sizing: border-box;
}
.advice-spinner { width: 11px; height: 11px; border: 2px solid rgba(255, 255, 255, 0.25); border-top-color: #30dcff; border-radius: 50%; animation: adviceSpin 0.8s linear infinite; }
.advice-error { margin: 7px 0 0; color: #ffc288; font-size: 9px; line-height: 14px; }
.statistics-empty { margin: 10px 0 0; color: rgba(213, 247, 251, 0.48); font-size: 10px; }

@keyframes adviceSpin { to { transform: rotate(360deg); } }

@media (prefers-reduced-motion: reduce) {
  .advice-spinner { animation: none; }
}
</style>
