<template>
  <section class="dash-card home-kpi-card" @click="onCardClick">
    <header class="dash-card__head">
      <span class="dash-card__code">{{ moduleCode }}</span>
      <span class="dash-card__title">{{ title }}</span>
      <el-icon v-if="icon" class="dash-card__module-icon" :size="22">
        <component :is="icon" />
      </el-icon>
    </header>
    <div class="dash-card__body s4-body">
      <div
        v-if="cells.length > 0"
        class="s4-kpi-grid"
        :class="{ 's4-kpi-grid--dense': cells.length > 4 }"
      >
        <div v-for="cell in cells" :key="cell.key" class="s4-kpi-cell">
          <el-tooltip v-if="cell.formulaText" placement="top" :show-after="200" :content="cell.formulaText">
            <div class="s4-kpi-label s4-kpi-label--formula">{{ cell.label }}</div>
          </el-tooltip>
          <div v-else class="s4-kpi-label">{{ cell.label }}</div>
          <div class="s4-kpi-body">
            <div class="s4-kpi-main">
              <div class="s4-kpi-value-row">
                <span class="s4-kpi-value">{{ cell.value }}</span>
                <span v-if="cell.unit" class="s4-kpi-unit">{{ cell.unit }}</span>
              </div>
              <div v-if="cell.targetDisplay" class="s4-kpi-target">目标: {{ cell.targetDisplay }}</div>
            </div>
            <span
              class="s4-kpi-trend"
              :class="{
                's4-kpi-trend--good': cell.trendTone === 'good',
                's4-kpi-trend--warn': cell.trendTone === 'warn',
                's4-kpi-trend--bad': cell.trendTone === 'bad',
              }"
            >
              <span class="s4-kpi-trend__arrow" aria-hidden="true">{{
                cell.trendArrow === 'up' ? '▲' : cell.trendArrow === 'down' ? '▼' : '—'
              }}</span>
              {{ cell.trend }}
            </span>
          </div>
        </div>
      </div>
      <div v-else class="home-kpi-card__empty">
        <span v-if="loading">加载中…</span>
        <span v-else>暂无指标配置，点击卡片进入模块后到“运营指标建模”配置 L1 指标</span>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { fetchHomeGrid } from '../../aidop/api/kanbanData'
import { AIDOP_LAYOUT_SAVED, AIDOP_S4_LAYOUT_SAVED } from '../../aidop/kanban/utils/s4LayoutEvents'

const props = defineProps({
  moduleCode: { type: String, required: true },
  title: { type: String, default: '' },
  icon: { type: [Object, Function], default: null },
  factoryId: { type: Number, default: 1 },
  /** 透传 smartOps base 查询参数（日期/产品/订单号/产线） */
  extra: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['click'])

const apiItems = ref([])
const loading = ref(false)

function fmtValue(v, unit) {
  if (v == null || v === '') return '—'
  const n = Number(v)
  if (Number.isNaN(n)) return String(v)
  if (unit === '%') return `${Math.round(n * 10) / 10}`
  if (unit === '天') return `${Math.round(n * 10) / 10}`
  if (Math.abs(n - Math.round(n)) < 1e-9) return `${Math.round(n)}`
  return `${Math.round(n * 100) / 100}`
}

function fmtTargetDisplay(v, unit) {
  if (v == null || v === '') return ''
  const n = Number(v)
  if (Number.isNaN(n)) return String(v)
  const num =
    unit === '%'
      ? `${Math.round(n * 10) / 10}`
      : unit === '天'
      ? `${Math.round(n * 10) / 10}`
      : Math.abs(n - Math.round(n)) < 1e-9
      ? `${Math.round(n)}`
      : `${Math.round(n * 100) / 100}`
  if (unit === '%') return `${num}%`
  if (unit === '天') return `${num} 天`
  if (unit) return `${num} ${unit}`
  return `${num}`
}

function mapItem(item) {
  const arrow = item.gapArrow
  const trendArrow = arrow === 'up' ? 'up' : arrow === 'down' ? 'down' : 'flat'
  const lv = String(item.achievementLevel || 'green')
  const trendTone = lv === 'red' ? 'bad' : lv === 'yellow' ? 'warn' : 'good'
  const unit = item.unit ?? ''
  const ft =
    item.formulaText != null && String(item.formulaText).trim()
      ? String(item.formulaText).trim()
      : ''
  return {
    key: item.rowId || item.metricCode,
    label: item.displayName || item.metricCode,
    formulaText: ft,
    value: fmtValue(item.currentValue, unit),
    unit,
    targetDisplay: fmtTargetDisplay(item.targetValue, unit),
    trend: item.gapLabel || '—',
    trendArrow,
    trendTone,
  }
}

const cells = computed(() =>
  Array.isArray(apiItems.value) ? apiItems.value.map(mapItem) : []
)

async function load() {
  const mc = String(props.moduleCode || '').toUpperCase()
  if (!mc) return
  loading.value = true
  try {
    const grid = await fetchHomeGrid(mc, props.factoryId, props.extra || {})
    apiItems.value = grid?.items && grid.items.length > 0 ? grid.items : []
  } catch {
    apiItems.value = []
  } finally {
    loading.value = false
  }
}

function onLayoutSaved(e) {
  const detailMc = String(e?.detail?.moduleCode || '').toUpperCase()
  if (!detailMc || detailMc === String(props.moduleCode || '').toUpperCase()) load()
}

function onS4LayoutSavedLegacy() {
  if (String(props.moduleCode || '').toUpperCase() === 'S4') load()
}

function onCardClick(e) {
  emit('click', e)
}

watch(
  () => [props.moduleCode, props.factoryId, props.extra],
  () => {
    load()
  },
  { deep: true }
)

onMounted(() => {
  load()
  if (typeof window !== 'undefined') {
    window.addEventListener(AIDOP_LAYOUT_SAVED, onLayoutSaved)
    window.addEventListener(AIDOP_S4_LAYOUT_SAVED, onS4LayoutSavedLegacy)
  }
})

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    window.removeEventListener(AIDOP_LAYOUT_SAVED, onLayoutSaved)
    window.removeEventListener(AIDOP_S4_LAYOUT_SAVED, onS4LayoutSavedLegacy)
  }
})

defineExpose({ reload: load })
</script>

<style scoped>
.dash-card {
  display: flex;
  flex-direction: column;
  background: rgba(30, 41, 59, 0.55);
  border: 1px solid #334155;
  border-radius: 8px;
  padding: 8px 10px;
  cursor: pointer;
  transition: border-color 0.2s, box-shadow 0.2s;
  min-height: 0;
  overflow: hidden;
}

.dash-card:hover {
  border-color: #64748b;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35);
}

.dash-card__head {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 6px;
  width: 100%;
  margin-bottom: 6px;
  padding-bottom: 6px;
  border-bottom: 1px solid #334155;
}

.dash-card__module-icon {
  margin-left: auto;
  flex-shrink: 0;
  color: #5eead4;
  filter: drop-shadow(0 0 8px rgba(94, 234, 212, 0.45));
}

.dash-card__code {
  font-size: 13px;
  font-weight: 800;
  color: #60a5fa;
  letter-spacing: 0.5px;
}

.dash-card__title {
  font-size: 13px;
  font-weight: 700;
  color: #e2e8f0;
}

.dash-card__body {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  gap: 6px;
  overflow: hidden;
}

.s4-body {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  padding: 2px 10px 4px;
  box-sizing: border-box;
}

.s4-kpi-grid {
  flex: 1;
  min-height: 0;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 8px 12px;
  align-content: stretch;
}

.s4-kpi-grid--dense {
  grid-template-columns: repeat(4, minmax(0, 1fr));
  grid-template-rows: repeat(2, minmax(0, 1fr));
}

.s4-kpi-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  gap: 6px;
  padding: 6px 8px;
  min-height: 0;
  background: rgba(0, 0, 0, 0.22);
  border-radius: 6px;
  border: 1px solid rgba(51, 65, 85, 0.35);
}

.s4-kpi-label {
  font-size: 11px;
  color: #94a3b8;
  line-height: 1.3;
  font-weight: 500;
}

.s4-kpi-label--formula {
  cursor: help;
  border-bottom: 1px dashed rgba(148, 163, 184, 0.55);
}

.s4-kpi-body {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
  min-width: 0;
}

.s4-kpi-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 3px;
}

.s4-kpi-value-row {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 4px 6px;
}

.s4-kpi-target {
  font-size: 11px;
  font-weight: 500;
  color: #94a3b8;
  line-height: 1.3;
}

.s4-kpi-value {
  font-size: clamp(18px, 3.8vw, 24px);
  font-weight: 800;
  color: #ffffff;
  line-height: 1.05;
  letter-spacing: 0.02em;
}

.s4-kpi-unit {
  font-size: 11px;
  color: #e2e8f0;
  font-weight: 500;
}

.s4-kpi-trend {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  font-size: 11px;
  font-weight: 700;
  flex-shrink: 0;
  align-self: center;
}

.s4-kpi-trend__arrow {
  font-size: 9px;
  line-height: 1;
  transform: translateY(0.5px);
}

.s4-kpi-trend--good {
  color: #4ade80;
}

.s4-kpi-trend--warn {
  color: #facc15;
}

.s4-kpi-trend--bad {
  color: #fb923c;
}

.home-kpi-card__empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
  font-size: 11px;
  padding: 8px;
  text-align: center;
  line-height: 1.4;
}
</style>
