<template>
  <!-- 告警 UI + 轮询聚合，外部仅需监听 alarm-update；样式/布局都内聚在这里 -->
  <div v-if="showUi" class="aw-root" :style="rootStyle">
    <!-- 左侧统计卡（与面板同顶对齐） -->
    <div class="alarm-summary" :style="summaryStyle">
      <div class="as-card critical" @click="onClickCard('Critical')">
        <div class="as-bar"></div>
        <div class="as-body">
          <div class="as-title">{{ t('ALARM_EVENT_CRITICAL') }}</div>
          <div class="as-num">{{ summary.critical }}</div>
        </div>
      </div>
      <div class="as-card major" @click="onClickCard('Major')">
        <div class="as-bar"></div>
        <div class="as-body">
          <div class="as-title">{{ t('ALARM_EVENT_MAJOR') }}</div>
          <div class="as-num">{{ summary.major }}</div>
        </div>
      </div>
      <div class="as-card minor" @click="onClickCard('Minor')">
        <div class="as-bar"></div>
        <div class="as-body">
          <div class="as-title">{{ t('ALARM_EVENT_MINOR') }}</div>
          <div class="as-num">{{ summary.minor }}</div>
        </div>
      </div>
      <!-- 不在位来自外部（快照差异），仅展示数量，不弹出面板 -->
      <div class="as-card absent">
        <div class="as-bar"></div>
        <div class="as-body">
          <div class="as-title">{{ t('STORE_NO_IN_POSITION') }}</div>
          <div class="as-num">{{ Number(absentCount) || 0 }}</div>
        </div>
      </div>
    </div>

    <!-- 明细面板（与统计卡同顶对齐） -->
    <div v-show="panel.open" class="alarm-panel" :style="{ top: panelStyle }">
      <div class="ap-header">
        <div class="ap-title">{{ t(levelKey(panel.level)) }}</div>
        <button class="ap-close" @click="closePanel">×</button>
      </div>

      <div v-if="panel.items.length" class="ap-list">
        <div class="ap-item" v-for="it in panel.items" :key="it.ID">
          <div class="ap-line">
            <span class="ap-k">{{ t('ALARM_EVENT_TYPE') }}</span>
            <span class="ap-v">{{ it.Subject }}</span>
          </div>
          <div class="ap-line">
            <span class="ap-k">{{ t('EVENT_CODE') }}</span>
            <span class="ap-v">{{ it.EventCode }}</span>
          </div>
          <div class="ap-line">
            <span class="ap-k">{{ t('EVENT_ENGENDER_TIME') }}</span>
            <span class="ap-v">{{ it.CreatedTime }}</span>
          </div>
          <div class="ap-content">
            <span class="ap-k">{{ t('EVENT_DESC') }}</span>
            <span class="ap-v">{{ it.Content }}</span>
          </div>
        </div>
      </div>

      <div v-else class="ap-empty">
        {{ t('STORE_NONE') }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, reactive, computed, watchEffect } from 'vue';
import type { CSSProperties } from 'vue';
import { useI18n } from 'vue-i18n';
import * as THREE from 'three';

const { t } = useI18n();

/* ===================== 类型定义 ===================== */
type AlarmLevel = 'Critical' | 'Major' | 'Minor';
export interface AlarmItem {
  HandlingSuggestion: string;
  Subject: string;
  CreatedTime: string;
  Content: string;
  Level: AlarmLevel | string;
  EventCode: string;
  ID: number;
}
interface AlarmResp { TotalCount: number; List: AlarmItem[]; }

/* ===================== 常量/接口 ===================== */
const UI_REST_MAINTENANCE_ALARM = '/UI/Rest/Maintenance/Alarm';
const LEVEL_RANK: Record<AlarmLevel, number> = { Minor: 2, Major: 3, Critical: 4 };

/* ===================== Props / Emits ===================== */
/**
 * 新增两个可选 props：
 * - partMap: threeDui 里的 3D 部件 map（用于找到 mesh）
 * - mapSubjectToParts: 告警 subject -> 相关部件名数组
 */
const props = withDefaults(defineProps<{
  pollMs?: number;
  showUi?: boolean;
  top?: number | string;
  left?: number | string;
  zIndex?: number;
  absentCount?: number;
  topGap?: number;

  partMap?: Record<string, any>;
  mapSubjectToParts?: (subject: string) => string[];
}>(), {
  pollMs: 8000,
  showUi: true,
  top: 56,
  left: 12,
  zIndex: 101,
  topGap: 56,
});

const emit = defineEmits<{
  (e: 'alarm-update', payload: {
    byLevel: Record<AlarmLevel, AlarmItem[]>,
    list: AlarmItem[],
    subjectMap: Record<string, { level: AlarmLevel }>,
  }): void;
}>();

/* ===================== 工具函数 ===================== */
const toPx = (v: number | string | undefined, d = 0) => {
  if (typeof v === 'number') {
    return v;
  }
  const parsed = parseFloat(String(v ?? ''));
  if (Number.isFinite(parsed)) {
    return parsed;
  }
  return d;
};

const levelKey = (l?: AlarmLevel) => {
  if (l === 'Critical') {
    return 'ALARM_EVENT_CRITICAL';
  }
  if (l === 'Major') {
    return 'ALARM_EVENT_MAJOR';
  }
  return 'ALARM_EVENT_MINOR';
};

// 标准化 Level，仅保留三档
function normalizeLevel(x: string | AlarmLevel): AlarmLevel {
  const s = String(x || '').toLowerCase();
  if (s === 'critical') {
    return 'Critical';
  }
  if (s === 'major') {
    return 'Major';
  }
  if (s === 'minor') {
    return 'Minor';
  }
  // 兜底并入 Minor
  return 'Minor';
}

// 主题归一：去首尾空格 + 小写
const normSubject = (s: string) => String(s || '').trim().toLowerCase();

function groupByLevel(list: AlarmItem[]): Record<AlarmLevel, AlarmItem[]> {
  const out: Record<AlarmLevel, AlarmItem[]> = { Critical: [], Major: [], Minor: [] };
  for (const it of list) {
    out[it.Level as AlarmLevel].push(it);
  }
  return out;
}

// 生成 Subject -> 最高等级 映射
function buildSubjectMap(list: AlarmItem[]): Record<string, { level: AlarmLevel }> {
  const map: Record<string, { level: AlarmLevel }> = {};
  for (const a of list) {
    const key = normSubject(a.Subject);
    const lvl = a.Level as AlarmLevel;
    const prev = map[key]?.level;
    if (!prev) {
      map[key] = { level: lvl };
    } else if (LEVEL_RANK[lvl] > LEVEL_RANK[prev]) {
      map[key] = { level: lvl };
    }
  }
  return map;
}

/* ===================== 状态 ===================== */
const timer = ref<number | null>(null);
const lastList = ref<AlarmItem[]>([]);

/* ===================== 3D 高亮 / 闪烁逻辑（内联版） ===================== */
/**
 * 说明：
 *  - 如果没有传入 partMap 或 mapSubjectToParts，则这里全部 no-op
 *  - 只有 props.partMap + props.mapSubjectToParts 都存在时才真正做材质修改
 */
type AnyAlarmLevel = AlarmLevel | string;

const lastSubjectLevel = reactive<Record<string, AnyAlarmLevel>>({});

const LEVEL_COLOR: Record<AlarmLevel, string> = {
  Minor: '#fadb14',
  Major: '#fa8c16',
  Critical: '#ff4d4f',
};

const origMatMap = new WeakMap<any, any>();
const blinkingByName = new Map<string, { colorHex: string }>();
let blinkRAF = 0;
let blinkT0 = 0;
let blinkPeriod = 1300;
let blinkMixMin = 0.15;
let blinkMixMax = 0.85;

function getPartObject(name: string): THREE.Object3D | undefined {
  return props.partMap?.[name] as THREE.Object3D | undefined;
}

function restorePartByName(name: string) {
  const obj = getPartObject(name);
  if (!obj) {
    return;
  }
  obj.traverse((child: any) => {
    if (!child.isMesh) {
      return;
    }
    const orig = origMatMap.get(child);
    if (orig) {
      child.material = orig;
      child.material.needsUpdate = true;
    }
  });
}

function applyBlinkMixToName(name: string, mix: number) {
  if (!props.partMap) {
    return;
  }
  const meta = blinkingByName.get(name);
  if (!meta) {
    return;
  }
  const obj = getPartObject(name);
  if (!obj) {
    return;
  }

  const tint = new THREE.Color(meta.colorHex);

  obj.traverse((child: any) => {
    if (!child.isMesh) {
      return;
    }
    if (!origMatMap.has(child)) {
      origMatMap.set(child, child.material);
    }
    const base = origMatMap.get(child) ?? child.material;

    if (child.material === base) {
      child.material = base.clone();
      child.material.needsUpdate = true;
    }

    const dst = child.material;
    if (dst?.color) {
      const baseColor = (base?.color?.clone?.() ?? new THREE.Color(1, 1, 1));
      dst.color = baseColor.clone().lerp(tint, mix);
    }
    if (dst?.emissive) {
      const baseEm = (base?.emissive?.clone?.() ?? new THREE.Color(0, 0, 0));
      const emTint = tint.clone().multiplyScalar(0.3);
      dst.emissive = baseEm.clone().lerp(emTint, mix);
      dst.emissiveIntensity = Math.min(0.6, (dst.emissiveIntensity ?? 1));
    }
    dst.needsUpdate = true;
  });
}

function startGlobalBlinkLoop() {
  if (!props.partMap) {
    return;
  }
  if (blinkRAF) {
    return;
  }
  blinkT0 = performance.now();
  const step = (now: number) => {
    if (blinkingByName.size === 0) {
      cancelAnimationFrame(blinkRAF);
      blinkRAF = 0;
      return;
    }
    const phase = ((now - blinkT0) % blinkPeriod) / blinkPeriod;
    const amp = (Math.sin(phase * Math.PI * 2) + 1) / 2;
    const mix = blinkMixMin + ((blinkMixMax - blinkMixMin) * amp);

    blinkingByName.forEach((_meta, nm) => applyBlinkMixToName(nm, mix));
    blinkRAF = requestAnimationFrame(step);
  };
  blinkRAF = requestAnimationFrame(step);
}

function startBlinking(
  name: string,
  colorHex: string,
  period = 1300,
  mixMin = 0.15,
  mixMax = 0.85,
) {
  if (!props.partMap) {
    return;
  }
  blinkPeriod = period;
  blinkMixMin = mixMin;
  blinkMixMax = mixMax;
  const prev = blinkingByName.get(name);
  if (!prev || prev.colorHex !== colorHex) {
    blinkingByName.set(name, { colorHex });
  }
  startGlobalBlinkLoop();
}

function stopBlinking(name: string) {
  if (!blinkingByName.has(name)) {
    return;
  }
  blinkingByName.delete(name);
  restorePartByName(name);
  if (blinkingByName.size === 0 && blinkRAF) {
    cancelAnimationFrame(blinkRAF);
    blinkRAF = 0;
  }
}

function stopBlinkingExcept(needed: Set<string>) {
  Array.from(blinkingByName.keys()).forEach(nm => {
    if (!needed.has(nm)) {
      stopBlinking(nm);
    }
  });
}

/** 一键彻底恢复：把所有改过材质的 mesh 统统还原，并停掉所有闪烁 */
function restoreAllTint() {
  if (!props.partMap) {
    return;
  }
  blinkingByName.clear();
  if (blinkRAF) {
    cancelAnimationFrame(blinkRAF);
    blinkRAF = 0;
  }

  Object.values(props.partMap).forEach((obj: any) => {
    if (!obj || !obj.traverse) {
      return;
    }
    obj.traverse((child: any) => {
      if (!child?.isMesh) {
        return;
      }
      const orig = origMatMap.get(child);
      if (orig) {
        child.material = orig;
        child.material.needsUpdate = true;
      }
    });
  });
}

/** 根据 lastSubjectLevel + mapSubjectToParts 计算需要高亮的部件 */
function repaintAlarms() {
  if (!props.partMap || !props.mapSubjectToParts) {
    return;
  }

  const need: Record<string, AnyAlarmLevel> = {};

  for (const [subj, lvl] of Object.entries(lastSubjectLevel)) {
    const rank = LEVEL_RANK[lvl as AlarmLevel] ?? 0;
    if (rank < 2) {
      // 小于 Minor 就不高亮
      continue;
    }
    const names = props.mapSubjectToParts(subj) || [];
    for (const name of names) {
      const cur = need[name];
      if (!cur) {
        need[name] = lvl;
      } else {
        const curRank = LEVEL_RANK[cur as AlarmLevel] ?? 0;
        if (rank > curRank) {
          need[name] = lvl;
        }
      }
    }
  }

  const neededNames = new Set<string>(Object.keys(need));
  stopBlinkingExcept(neededNames);

  for (const [name, lvl] of Object.entries(need)) {
    const color = LEVEL_COLOR[lvl as AlarmLevel] || LEVEL_COLOR.Minor;
    startBlinking(name, color, 1300, 0.15, 0.85);
  }
}

/** 从 subjectMap 刷新 lastSubjectLevel，并触发重绘 */
function updateAlarmVisual(subjectMap: Record<string, { level: AlarmLevel }>) {
  if (!props.partMap || !props.mapSubjectToParts) {
    return;
  }

  Object.keys(lastSubjectLevel).forEach(k => {
    delete lastSubjectLevel[k];
  });
  Object.entries(subjectMap || {}).forEach(([subj, v]) => {
    lastSubjectLevel[subj] = v.level;
  });
  repaintAlarms();
}

/* ===================== 计算样式 ===================== */
const summaryStyle = computed<CSSProperties>(() => {
  const rootTop = toPx(props.top, 56);
  const gap = toPx(props.topGap, 56);
  return { position: 'absolute', top: `${gap - rootTop}px`, left: '0' };
});
const panelStyle = computed(() => {
  const rootTop = toPx(props.top, 56);
  const gap = toPx(props.topGap, 56);
  return `${gap - rootTop}px`;
});
const rootStyle = computed<CSSProperties>(() => ({
  position: 'absolute',
  top: typeof props.top === 'number' ? `${props.top}px` : String(props.top),
  left: typeof props.left === 'number' ? `${props.left}px` : String(props.left),
  zIndex: props.zIndex,
  pointerEvents: 'none',
}));

/* ===================== 拉取与分发 ===================== */
async function fetchOnce() {
  try {
    const res = await fetch(UI_REST_MAINTENANCE_ALARM, { method: 'GET', credentials: 'include', cache: 'no-store' });
    if (!res.ok) {
      throw new Error(`Alarm API ${res.status} ${res.statusText}`);
    }
    const data: AlarmResp = await res.json();

    // 标准化 Level
    const list = (data?.List ?? []).map(a => ({
      ...a,
      Level: normalizeLevel(a.Level) as AlarmLevel,
    }));
    lastList.value = list;

    const byLevel = groupByLevel(list);
    const subjectMap = buildSubjectMap(list);

    updateAlarmVisual(subjectMap);

    emit('alarm-update', { byLevel, list, subjectMap });
  } catch (e) {
    lastList.value = [];
    updateAlarmVisual({});
    emit('alarm-update', {
      byLevel: { Critical: [], Major: [], Minor: [] },
      list: [],
      subjectMap: {},
    });
  }
}

/* ===================== 统计卡 & 面板 ===================== */
const summary = reactive({ critical: 0, major: 0, minor: 0 });
watchEffect(() => {
  let c = 0;
  let m = 0;
  let mi = 0;
  for (const a of lastList.value) {
    if (a.Level === 'Critical') {
      c++;
    } else if (a.Level === 'Major') {
      m++;
    } else if (a.Level === 'Minor') {
      mi++;
    } else {
      // no-op
    }
  }
  summary.critical = c;
  summary.major = m;
  summary.minor = mi;
});

const panel = reactive({ open: false, level: 'Minor' as AlarmLevel, items: [] as AlarmItem[] });
function refreshPanelItems() {
  panel.items = (lastList.value || []).filter(a => a.Level === panel.level);
}
function onClickCard(lvl: AlarmLevel) {
  if (panel.open && panel.level === lvl) {
    panel.open = false;
    return;
  }
  panel.level = lvl;
  refreshPanelItems();
  panel.open = true;
}
function closePanel() {
  panel.open = false;
}

/* ===================== 生命周期 ===================== */
onMounted(() => {
  fetchOnce();
  timer.value = window.setInterval(fetchOnce, props.pollMs);
});
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  restoreAllTint();
});

/* ===================== 对外暴露 ===================== */
defineExpose({
  refresh: fetchOnce,
  openPanel: (lvl: AlarmLevel) => {
    panel.level = lvl;
    refreshPanelItems();
    panel.open = true;
  },
  closePanel,
  restoreAllTint,
});
</script>

<style scoped>
/* —— 让子元素可点击 —— */
.aw-root :deep(*) {
  pointer-events: auto;
}

/* ========== 告警统计卡片 ========== */
.alarm-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
  --as-width: 100px;
  --as-height: 64px;
}

.as-card {
  width: var(--as-width);
  height: var(--as-height);
  display: grid;
  grid-template-columns: 6px 1fr;
  align-items: center;
  border-radius: 12px;
  background: rgba(255, 255, 255, .9);
  box-shadow: 0 3px 10px rgba(0, 0, 0, .15);
  overflow: hidden;
  cursor: pointer;
}

.as-card .as-bar {
  width: 6px;
  height: 100%;
}

.as-card .as-body {
  padding: 8px 14px;
}

.as-title {
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
  color: #595959;
}

.as-num {
  margin-top: 2px;
  font-size: 30px;
  font-weight: 900;
  line-height: 1;
  color: #262626;
}

.as-card.critical .as-bar {
  background: linear-gradient(180deg, #ff4d4f, #ff7a45);
}

.as-card.major .as-bar {
  background: linear-gradient(180deg, #fa8c16, #f7a647);
}

.as-card.minor .as-bar {
  background: linear-gradient(180deg, #fadb14, #ffe58f);
}

.as-card.absent .as-bar {
  background: linear-gradient(180deg, #bfbfbf, #d9d9d9);
}

.as-card.critical .as-title,
.as-card.critical .as-num {
  color: #d9363e;
}

.as-card.major .as-title,
.as-card.major .as-num {
  color: #d46b08;
}

.as-card.minor .as-title,
.as-card.minor .as-num {
  color: #8c8c00;
}

.as-card.absent .as-title,
.as-card.absent .as-num {
  color: #595959;
}

/* ========== 告警明细面板 ========== */
.alarm-panel {
  position: absolute;
  top: 0;
  left: 112px;
  width: 420px;
  max-height: 60vh;
  overflow: auto;
  border-radius: 12px;
  background: rgba(0, 0, 0, 0.72);
  color: #fff;
  box-shadow: 0 8px 22px rgba(0, 0, 0, .35);
}

.ap-header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  background: rgba(0, 0, 0, .8);
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}

.ap-title {
  font-weight: 700;
}

.ap-close {
  margin-left: auto;
  background: transparent;
  border: none;
  color: #fff;
  font-size: 18px;
  cursor: pointer;
}

.ap-list {
  padding: 8px 12px;
}

.ap-item {
  border: 1px solid rgba(255, 255, 255, 0.12);
  border-radius: 10px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.05);
}

.ap-item+.ap-item {
  margin-top: 8px;
}

.ap-line {
  display: grid;
  grid-template-columns: 100px 1fr;
  gap: 8px;
  line-height: 1.5;
  margin: 2px 0;
}

.ap-k {
  opacity: .85;
}

.ap-v {
  font-weight: 700;
}

.ap-content {
  margin-top: 6px;
  padding-top: 6px;
  border-top: 1px dashed rgba(255, 255, 255, 0.15);
  display: grid;
  grid-template-columns: 100px 1fr;
  gap: 8px;
  line-height: 1.5;
}

.ap-empty {
  padding: 14px 12px;
  opacity: 0.9;
}
</style>
