<template>
  <div class="p-2 line-loss-page">
    <el-row :gutter="12">
      <el-col :xs="24" :md="7" :lg="6">
        <el-card shadow="hover" class="side-card">
          <el-tree
            ref="treeRef"
            class="node-tree"
            :data="treeData"
            node-key="id"
            highlight-current
            default-expand-all
            :expand-on-click-node="false"
            :props="{ label: 'name', children: 'children' }"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>

      <el-col :xs="24" :md="17" :lg="18">
        <el-card shadow="hover">
          <el-form :inline="true" class="query-form">
            <el-form-item label="时间类型">
              <el-select v-model="query.timeType" class="type-select" @change="handleTimeTypeChange">
                <el-option label="日" value="day" />
                <el-option label="月" value="month" />
                <el-option label="年" value="year" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间">
              <el-date-picker
                v-model="query.date"
                :type="datePickerType"
                :value-format="dateValueFormat"
                :placeholder="datePlaceholder"
                class="date-picker"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="loadReport">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            border
            row-key="id"
            :data="tableRows"
            :tree-props="{ children: 'children' }"
            class="line-loss-table"
            height="650"
          >
            <el-table-column prop="name" label="名称" fixed min-width="220" show-overflow-tooltip />
            <el-table-column prop="currentEnergy" label="当前支路能耗" align="right" min-width="150">
              <template #default="{ row }">{{ formatEnergy(row.currentEnergy) }}</template>
            </el-table-column>
            <el-table-column prop="childEnergy" label="下级支路能耗" align="right" min-width="150">
              <template #default="{ row }">{{ formatEnergy(row.childEnergy) }}</template>
            </el-table-column>
            <el-table-column prop="lossEnergy" label="损失电量" align="right" min-width="130">
              <template #default="{ row }">{{ formatEnergy(row.lossEnergy) }}</template>
            </el-table-column>
            <el-table-column prop="lossRate" label="线损率" align="right" min-width="120">
              <template #default="{ row }">{{ isLeafRow(row) ? '---' : formatRate(row.lossRate) }}</template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="LineLossAnalysis" lang="ts">
import { getLineLoss } from '@/api/electricityManagement/lineLoss';
import { LineLossRow, LineLossTimeType } from '@/api/electricityManagement/lineLoss/types';
import { listLineInfo } from '@/api/system/line';
import { LineInfoVO } from '@/api/system/line/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const treeRef = ref();
const loading = ref(false);
const treeData = ref<LineInfoVO[]>([]);
const tableRows = ref<LineLossRow[]>([]);
const selectedNode = ref<LineInfoVO>();

const query = reactive({
  timeType: 'day' as LineLossTimeType,
  date: proxy?.parseTime(new Date(), '{y}-{m}-{d}')
});

const datePickerType = computed(() => {
  if (query.timeType === 'year') return 'year';
  if (query.timeType === 'month') return 'month';
  return 'date';
});
const dateValueFormat = computed(() => {
  if (query.timeType === 'year') return 'YYYY';
  if (query.timeType === 'month') return 'YYYY-MM';
  return 'YYYY-MM-DD';
});
const datePlaceholder = computed(() => {
  if (query.timeType === 'year') return '请选择年份';
  if (query.timeType === 'month') return '请选择月份';
  return '请选择日期';
});

function normalizeNormalTree(rows: LineInfoVO[]): LineInfoVO[] {
  return rows
    .filter((row) => row.isDevice !== '1' && row.isDeviceGroup !== '1')
    .map((row) => ({
      ...row,
      children: normalizeNormalTree(row.children || [])
    }));
}

function firstNode(rows: LineInfoVO[]): LineInfoVO | undefined {
  if (!rows.length) return undefined;
  return rows[0];
}

function setDefaultDate() {
  const now = new Date();
  if (query.timeType === 'year') {
    query.date = proxy?.parseTime(now, '{y}') || String(now.getFullYear());
  } else if (query.timeType === 'month') {
    query.date = proxy?.parseTime(now, '{y}-{m}') || `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
  } else {
    query.date = proxy?.parseTime(now, '{y}-{m}-{d}');
  }
}

function handleNodeClick(node: LineInfoVO) {
  selectedNode.value = node;
  loadReport();
}

function handleTimeTypeChange() {
  setDefaultDate();
}

function formatEnergy(value: unknown) {
  const numberValue = Number(value || 0);
  return Number.isFinite(numberValue) ? numberValue.toFixed(3) : '-';
}

function formatRate(value: unknown) {
  const numberValue = Number(value || 0);
  return Number.isFinite(numberValue) ? `${numberValue.toFixed(2)}%` : '-';
}

function isLeafRow(row: LineLossRow) {
  return !row.children || row.children.length === 0;
}

async function loadTree() {
  const res = await listLineInfo();
  const rows = (res as any).rows || (res as any).data || [];
  treeData.value = normalizeNormalTree(rows);
  selectedNode.value = selectedNode.value || firstNode(treeData.value);
  await nextTick();
  if (selectedNode.value) {
    treeRef.value?.setCurrentKey?.(selectedNode.value.id);
  }
}

async function loadReport() {
  if (!selectedNode.value?.id) {
    tableRows.value = [];
    return;
  }
  loading.value = true;
  try {
    const res = await getLineLoss({
      nodeId: selectedNode.value.id,
      timeType: query.timeType,
      date: query.date
    });
    tableRows.value = res.data.rows || [];
  } finally {
    loading.value = false;
  }
}

async function resetQuery() {
  query.timeType = 'day';
  setDefaultDate();
  selectedNode.value = firstNode(treeData.value);
  await nextTick();
  if (selectedNode.value) {
    treeRef.value?.setCurrentKey?.(selectedNode.value.id);
  }
  await loadReport();
}

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

<style scoped>
.line-loss-page {
  min-height: 100%;
}

.side-card {
  margin-bottom: 12px;
}

.node-tree {
  max-height: 760px;
  overflow: auto;
}

.query-form {
  margin-bottom: 12px;
}

.type-select {
  width: 110px;
}

.date-picker {
  width: 170px;
}

.line-loss-table {
  width: 100%;
}
</style>
