<template>
  <div class="p-2 report-page">
    <el-card shadow="hover">
      <el-tabs v-model="activeReport">
        <el-tab-pane label="能耗报表" name="energy">
          <div class="report-layout">
            <aside class="report-tree-panel">
              <el-form label-position="top">
                <el-form-item label="设备类型">
                  <el-select v-model="query.deviceType" placeholder="请选择设备类型" clearable @change="handleDeviceTypeChange">
                    <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="选择方式">
                  <el-radio-group v-model="selectMode" @change="handleSelectModeChange">
                    <el-radio-button label="single">单选</el-radio-button>
                    <el-radio-button label="multiple">多选</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="selectMode === 'multiple'" label="父子联动">
                  <el-switch v-model="cascadeChecked" active-text="开启" inactive-text="关闭" @change="resetTreeChecked" />
                </el-form-item>
              </el-form>

              <el-tree
                ref="deviceTreeRef"
                class="device-tree"
                :data="filteredTree"
                node-key="id"
                :props="{ label: 'name', children: 'children' }"
                :show-checkbox="selectMode === 'multiple'"
                :check-strictly="!cascadeChecked"
                :highlight-current="selectMode === 'single'"
                default-expand-all
                @node-click="handleNodeClick"
                @check="handleTreeCheck"
              >
                <template #default="{ data }">
                  <span class="tree-node">
                    <span>{{ data.name }}</span>
                    <el-tag v-if="data.isDevice === '1'" size="small" type="success">设备</el-tag>
                    <el-tag v-else-if="data.isDeviceGroup === '1'" size="small" type="warning">设备组</el-tag>
                  </span>
                </template>
              </el-tree>
            </aside>

            <section class="report-content">
              <el-form :inline="true" class="report-toolbar">
                <el-form-item label="时间类型">
                  <el-segmented v-model="query.timeType" :options="timeTypeOptions" @change="handleTimeTypeChange" />
                </el-form-item>
                <el-form-item
                  v-if="query.timeType === 'hour'"
                  label="日期"
                >
                  <el-date-picker v-model="query.date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" @change="loadEnergyReport" />
                </el-form-item>
                <el-form-item v-if="query.timeType === 'day'" label="日期范围">
                  <el-date-picker
                    v-model="dayRange"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="handleDayRangeChange"
                  />
                </el-form-item>
                <el-form-item v-if="query.timeType === 'month'" label="月份范围">
                  <el-date-picker
                    v-model="monthRange"
                    type="monthrange"
                    value-format="YYYY-MM"
                    range-separator="至"
                    start-placeholder="开始月份"
                    end-placeholder="结束月份"
                    @change="handleMonthRangeChange"
                  />
                </el-form-item>
                <el-form-item v-if="query.timeType === 'shift'" label="班组日期范围">
                  <el-date-picker
                    v-model="shiftRange"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="handleShiftRangeChange"
                  />
                </el-form-item>
                <template v-if="query.timeType === 'year'">
                  <el-form-item label="起始年份">
                    <el-date-picker v-model="startYearDate" type="year" value-format="YYYY" placeholder="起始年份" @change="handleYearRangeChange" />
                  </el-form-item>
                  <el-form-item label="结束年份">
                    <el-date-picker v-model="endYearDate" type="year" value-format="YYYY" placeholder="结束年份" @change="handleYearRangeChange" />
                  </el-form-item>
                </template>
                <el-form-item v-if="query.timeType === 'latest'" label="条数">
                  <el-input-number
                    v-model="query.latestCount"
                    :min="1"
                    :max="100"
                    :step="1"
                    step-strictly
                    controls-position="right"
                    @change="loadEnergyReport"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="loadEnergyReport">查询</el-button>
                </el-form-item>
              </el-form>

              <el-table v-loading="loading" :data="rows" border height="calc(100vh - 250px)">
                <el-table-column prop="name" label="名称" fixed min-width="180" />
                <el-table-column v-for="column in columns" :key="column.field" :label="column.label" align="center">
                  <el-table-column
                    v-for="child in column.children"
                    :key="child.prop"
                    :prop="child.prop"
                    :label="child.label"
                    align="center"
                    min-width="92"
                  >
                    <template #default="scope">
                      {{ formatValue(scope.row[child.prop]) }}
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </section>
          </div>
        </el-tab-pane>
        <el-tab-pane label="分时报表" name="minute">
          <el-empty description="分时报表待接入" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup name="ReportIndex" lang="ts">
import { getEnergyReport } from '@/api/report';
import { EnergyReportColumn, EnergyReportQuery, EnergyReportRow } from '@/api/report/types';
import { listFloorInfo } from '@/api/system/floor';
import { FloorInfoVO } from '@/api/system/floor/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { device_type } = toRefs<any>(proxy?.useDict('device_type'));

const activeReport = ref('energy');
const deviceTreeRef = ref<ElTreeInstance>();
const loading = ref(false);
const treeData = ref<FloorInfoVO[]>([]);
const filteredTree = ref<FloorInfoVO[]>([]);
const columns = ref<EnergyReportColumn[]>([]);
const rows = ref<EnergyReportRow[]>([]);
const selectMode = ref<'single' | 'multiple'>('single');
const cascadeChecked = ref(false);
const currentNode = ref<FloorInfoVO>();
const checkedNodeIds = ref<Array<string | number>>([]);
const currentYear = new Date().getFullYear();
const startYearDate = ref(String(currentYear - 1));
const endYearDate = ref(String(currentYear));
const todayText = proxy?.parseTime(new Date(), '{y}-{m}-{d}') || '';
const dayRange = ref<string[]>([todayText, todayText]);
const shiftRange = ref<string[]>([todayText, todayText]);
const monthRange = ref<string[]>([`${currentYear}-01`, `${currentYear}-12`]);

const query = reactive<EnergyReportQuery>({
  deviceType: undefined,
  nodeIds: '',
  timeType: 'hour',
  date: todayText,
  beginDate: todayText,
  endDate: todayText,
  beginMonth: `${currentYear}-01`,
  endMonth: `${currentYear}-12`,
  startYear: currentYear - 1,
  endYear: currentYear,
  latestCount: 10
});

const timeTypeOptions = [
  { label: '时', value: 'hour' },
  { label: '日', value: 'day' },
  { label: '月', value: 'month' },
  { label: '年', value: 'year' },
  { label: '班组', value: 'shift' },
  { label: '最新', value: 'latest' }
];

const hasMatchedDevice = (node: FloorInfoVO, deviceType: string | number | undefined): boolean => {
  if (!deviceType) {
    return true;
  }
  if (node.isDevice === '1' && String(node.deviceType ?? '') === String(deviceType)) {
    return true;
  }
  return (node.children || []).some((child) => hasMatchedDevice(child, deviceType));
};

const filterTreeByDeviceType = (list: FloorInfoVO[]): FloorInfoVO[] => {
  return list
    .filter((node) => hasMatchedDevice(node, query.deviceType))
    .map((node) => ({
      ...node,
      children: filterTreeByDeviceType(node.children || [])
    }));
};

const getSingleNodeIds = () => {
  if (!currentNode.value) {
    return [];
  }
  return [currentNode.value.id, ...(currentNode.value.children || []).map((node) => node.id)];
};

const syncNodeIds = () => {
  query.nodeIds = selectMode.value === 'single' ? getSingleNodeIds().join(',') : checkedNodeIds.value.join(',');
};

const resetReportData = () => {
  columns.value = [];
  rows.value = [];
};

const loadTree = async () => {
  const res = await listFloorInfo({});
  treeData.value = res.rows || [];
  filteredTree.value = filterTreeByDeviceType(treeData.value);
};

const loadEnergyReport = async () => {
  syncNodeIds();
  if (!query.deviceType || !query.nodeIds) {
    resetReportData();
    return;
  }

  loading.value = true;
  try {
    const res = await getEnergyReport(query);
    columns.value = res.data.columns || [];
    rows.value = res.data.rows || [];
  } finally {
    loading.value = false;
  }
};

const handleDeviceTypeChange = async () => {
  currentNode.value = undefined;
  checkedNodeIds.value = [];
  deviceTreeRef.value?.setCurrentKey(undefined);
  resetTreeChecked();
  filteredTree.value = filterTreeByDeviceType(treeData.value);
  await loadEnergyReport();
};

const handleSelectModeChange = () => {
  currentNode.value = undefined;
  checkedNodeIds.value = [];
  deviceTreeRef.value?.setCurrentKey(undefined);
  resetTreeChecked();
  loadEnergyReport();
};

const resetTreeChecked = () => {
  deviceTreeRef.value?.setCheckedKeys([]);
};

const handleNodeClick = (data: FloorInfoVO) => {
  if (selectMode.value !== 'single') {
    return;
  }
  currentNode.value = data;
  loadEnergyReport();
};

const handleTreeCheck = () => {
  if (selectMode.value !== 'multiple') {
    return;
  }
  checkedNodeIds.value = (deviceTreeRef.value?.getCheckedKeys() || []) as Array<string | number>;
  loadEnergyReport();
};

const handleTimeTypeChange = () => {
  if (query.timeType === 'hour') {
    query.date = todayText;
    query.beginDate = undefined;
    query.endDate = undefined;
  } else if (query.timeType === 'day') {
    dayRange.value = [todayText, todayText];
    query.date = undefined;
    query.beginDate = dayRange.value[0];
    query.endDate = dayRange.value[1];
  } else if (query.timeType === 'month') {
    monthRange.value = [`${currentYear}-01`, `${currentYear}-12`];
    query.date = undefined;
    query.beginMonth = monthRange.value[0];
    query.endMonth = monthRange.value[1];
  } else if (query.timeType === 'shift') {
    shiftRange.value = [todayText, todayText];
    query.date = undefined;
    query.beginDate = shiftRange.value[0];
    query.endDate = shiftRange.value[1];
  } else if (query.timeType === 'latest') {
    query.date = undefined;
    query.beginDate = undefined;
    query.endDate = undefined;
    query.beginMonth = undefined;
    query.endMonth = undefined;
    query.latestCount = query.latestCount || 10;
  }
  loadEnergyReport();
};

const handleDayRangeChange = () => {
  query.beginDate = dayRange.value?.[0];
  query.endDate = dayRange.value?.[1];
  loadEnergyReport();
};

const handleMonthRangeChange = () => {
  query.beginMonth = monthRange.value?.[0];
  query.endMonth = monthRange.value?.[1];
  loadEnergyReport();
};

const handleShiftRangeChange = () => {
  query.beginDate = shiftRange.value?.[0];
  query.endDate = shiftRange.value?.[1];
  loadEnergyReport();
};

const handleYearRangeChange = () => {
  query.startYear = Number(startYearDate.value);
  query.endYear = Number(endYearDate.value);
  loadEnergyReport();
};

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

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

<style scoped>
.report-layout {
  display: grid;
  grid-template-columns: 300px minmax(0, 1fr);
  gap: 12px;
}

.report-tree-panel {
  border-right: 1px solid var(--el-border-color-light);
  padding-right: 12px;
}

.device-tree {
  height: calc(100vh - 300px);
  overflow: auto;
}

.tree-node {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
}

.report-content {
  min-width: 0;
}

.report-toolbar {
  margin-bottom: 10px;
}

@media (max-width: 900px) {
  .report-layout {
    grid-template-columns: 1fr;
  }

  .report-tree-panel {
    border-right: 0;
    border-bottom: 1px solid var(--el-border-color-light);
    padding-right: 0;
    padding-bottom: 12px;
  }

  .device-tree {
    height: 280px;
  }
}
</style>
