<template>
  <div class="app-container report-page">
    <el-row :gutter="18">
      <el-col :xl="5" :lg="6" :md="7" :sm="24" :xs="24">
        <section class="glass-panel tree-panel">
          <div class="panel-head">
            <div>
              <p class="panel-eyebrow">Scope Tree</p>
              <h3>评分范围树</h3>
            </div>
          </div>
          <el-tree
            v-loading="treeLoading"
            :data="treeData"
            node-key="id"
            :props="{ label: 'label', children: 'children' }"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </section>
      </el-col>

      <el-col :xl="19" :lg="18" :md="17" :sm="24" :xs="24">
        <section class="hero-panel">
          <div>
            <p class="panel-eyebrow hero-eyebrow">Efficiency Analysis</p>
            <h2>综合运行能效分析</h2>
            <p class="hero-desc">当前评分严格定义为“运行工况评分”，只用于设备横向比较与状态诊断，不表示财务结算能效。</p>
          </div>
          <el-tag effect="dark">{{ selectionLabel || '未选择范围' }}</el-tag>
        </section>

        <section class="glass-panel">
          <div class="panel-head">
            <div>
              <p class="panel-eyebrow">Query</p>
              <h3>评分筛选</h3>
            </div>
            <el-button type="primary" @click="handleQuery">刷新评分</el-button>
          </div>

          <el-form :inline="true" :model="queryForm" size="small">
            <el-form-item label="分析范围">
              <el-input :model-value="selectionLabel || '请先在左侧选择节点'" readonly style="width: 280px" />
            </el-form-item>
            <el-form-item label="记录时间">
              <el-date-picker
                v-model="timeRange"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 340px"
              />
            </el-form-item>
            <el-form-item label="指标">
              <el-select
                v-model="queryForm.metricCodes"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="自动识别有效指标"
                style="width: 320px"
              >
                <el-option v-for="item in metricOptions" :key="item.metricCode" :label="item.metricName" :value="item.metricCode" />
              </el-select>
            </el-form-item>
          </el-form>
        </section>

        <EfficiencyScoreBoard
          v-if="reportData && reportData.hasData !== false"
          :overall-score="reportData.overallScore"
          :template-name="reportData.templateName"
          :analysis-conclusion="reportData.analysisConclusion"
          :metric-scores="reportData.metricScores || []"
        />

        <section v-loading="loading" class="glass-panel">
          <div class="panel-head">
            <div>
              <p class="panel-eyebrow">Ranking</p>
              <h3>设备评分排行</h3>
            </div>
          </div>

          <el-empty v-if="!reportData || reportData.hasData === false" :description="reportData?.emptyReason || '当前条件下无可分析数据'" />
          <Chart v-else class="chart-host" :chart-option="chartOption" />
        </section>

        <section v-if="reportData?.metricScores?.length" class="glass-panel">
          <div class="panel-head">
            <div>
              <p class="panel-eyebrow">Metrics</p>
              <h3>指标评分明细</h3>
            </div>
          </div>

          <el-table :data="reportData.metricScores" stripe>
            <el-table-column prop="metricName" label="指标" min-width="140" />
            <el-table-column prop="averageValue" label="均值" min-width="100">
              <template #default="{ row }">{{ formatNumber(row.averageValue) }}</template>
            </el-table-column>
            <el-table-column prop="peakValue" label="峰值" min-width="100">
              <template #default="{ row }">{{ formatNumber(row.peakValue) }}</template>
            </el-table-column>
            <el-table-column prop="stabilityScore" label="稳定性" min-width="100">
              <template #default="{ row }">{{ formatNumber(row.stabilityScore) }}</template>
            </el-table-column>
            <el-table-column prop="fluctuationScore" label="波动性" min-width="100">
              <template #default="{ row }">{{ formatNumber(row.fluctuationScore) }}</template>
            </el-table-column>
            <el-table-column prop="thresholdScore" label="越界得分" min-width="100">
              <template #default="{ row }">{{ formatNumber(row.thresholdScore) }}</template>
            </el-table-column>
            <el-table-column prop="score" label="综合得分" min-width="100">
              <template #default="{ row }">{{ formatNumber(row.score) }}</template>
            </el-table-column>
          </el-table>
        </section>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import type { EChartsOption } from 'echarts';
import { ElMessage } from 'element-plus';
import Chart from '@/components/Charts/Chart.vue';
import EfficiencyScoreBoard from '../components/EfficiencyScoreBoard.vue';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { getEfficiencyAnalysisReport } from '@/api/ems/report/iotAdvancedReport';
import type { EfficiencyAnalysisVO, EmsTreeNode, IotMetricOptionVO } from '@/api/ems/types';
import { parseTime } from '@/utils/ruoyi';

defineOptions({
  name: 'ComprehensiveEnergyEfficiencyReport'
});

const treeLoading = ref(false);
const loading = ref(false);
const treeData = ref<EmsTreeNode[]>([]);
const selectionLabel = ref('');
const reportData = ref<EfficiencyAnalysisVO>();

const createDefaultRange = () => {
  const now = new Date();
  const start = new Date(now.getTime() - 24 * 60 * 60 * 1000);
  return [parseTime(start, '{y}-{m}-{d} {h}:{i}:{s}'), parseTime(now, '{y}-{m}-{d} {h}:{i}:{s}')];
};

const timeRange = ref<string[]>(createDefaultRange());

const queryForm = reactive({
  monitorIds: [] as string[],
  metricCodes: [] as string[]
});

const metricOptions = computed<IotMetricOptionVO[]>(() =>
  (reportData.value?.metricScores || []).map((item) => ({
    metricCode: item.metricCode,
    metricName: item.metricName,
    unit: item.unit
  }))
);

const chartOption = computed<EChartsOption>(() => {
  const deviceScores = reportData.value?.deviceScores || [];
  return {
    color: ['#2563eb'],
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      top: 20,
      left: '14%',
      right: '6%',
      bottom: 36
    },
    xAxis: {
      type: 'value',
      max: 100
    },
    yAxis: {
      type: 'category',
      data: deviceScores.map((item) => item.monitorName)
    },
    series: [
      {
        type: 'bar',
        data: deviceScores.map((item) => Number(item.totalScore || 0)),
        itemStyle: {
          borderRadius: [0, 6, 6, 0]
        }
      }
    ]
  };
});

const getLeafNodes = (nodes: EmsTreeNode[]): EmsTreeNode[] => {
  let result: EmsTreeNode[] = [];
  (nodes || []).forEach((item) => {
    if (item.children && item.children.length > 0) {
      result = result.concat(getLeafNodes(item.children));
      return;
    }
    if (item.code) {
      result.push(item);
    }
  });
  return result;
};

const loadTree = async () => {
  treeLoading.value = true;
  try {
    const response = await getMonitorInfoTree({});
    treeData.value = response.data || [];
  } finally {
    treeLoading.value = false;
  }
};

const handleNodeClick = (node: EmsTreeNode) => {
  const targetNodes = node.children && node.children.length > 0 ? getLeafNodes([node]) : [node];
  queryForm.monitorIds = targetNodes.map((item) => String(item.code || '')).filter((item) => item);
  selectionLabel.value = String(node.label || '当前节点');
};

const handleQuery = async () => {
  if (!queryForm.monitorIds.length) {
    ElMessage.warning('请先选择评分范围');
    return;
  }
  if (!timeRange.value || timeRange.value.length !== 2) {
    ElMessage.warning('请选择完整的记录时间范围');
    return;
  }
  loading.value = true;
  try {
    const { data } = await getEfficiencyAnalysisReport({
      monitorIds: queryForm.monitorIds,
      metricCodes: queryForm.metricCodes,
      beginRecordTime: timeRange.value[0],
      endRecordTime: timeRange.value[1]
    });
    reportData.value = data || { hasData: false, emptyReason: '接口未返回有效数据' };
  } finally {
    loading.value = false;
  }
};

const formatNumber = (value: unknown) => {
  if (value === null || value === undefined || value === '') {
    return '--';
  }
  const numberValue = Number(value);
  return Number.isNaN(numberValue) ? '--' : numberValue.toFixed(2);
};

onMounted(async () => {
  await loadTree();
});
</script>

<style scoped>
.report-page {
  min-height: calc(100vh - 84px);
  background:
    radial-gradient(circle at top right, rgba(37, 99, 235, 0.14), transparent 24%),
    radial-gradient(circle at top left, rgba(20, 184, 166, 0.1), transparent 28%), linear-gradient(180deg, #f4f8ff 0%, #f8fafc 100%);
}

.glass-panel,
.hero-panel {
  border-radius: 24px;
  border: 1px solid rgba(148, 163, 184, 0.18);
  background: rgba(255, 255, 255, 0.92);
  box-shadow: 0 18px 48px rgba(15, 23, 42, 0.08);
}

.tree-panel,
.glass-panel {
  padding: 18px 20px;
  margin-bottom: 18px;
}

.hero-panel {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  padding: 24px;
  margin-bottom: 18px;
  background:
    linear-gradient(135deg, rgba(15, 118, 110, 0.96), rgba(37, 99, 235, 0.92)),
    linear-gradient(180deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0));
  color: #ffffff;
}

.hero-eyebrow {
  color: rgba(255, 255, 255, 0.72);
}

.hero-panel h2,
.panel-head h3 {
  margin: 0;
}

.hero-desc {
  margin: 14px 0 0;
  max-width: 760px;
  line-height: 1.75;
  color: rgba(255, 255, 255, 0.84);
}

.panel-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  margin-bottom: 14px;
}

.panel-eyebrow {
  margin: 0 0 6px;
  color: #2563eb;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.12em;
  text-transform: uppercase;
}

.chart-host {
  width: 100%;
  height: 320px;
}

@media (max-width: 992px) {
  .hero-panel {
    display: block;
  }
}
</style>
