<template>
  <div class="connectAnalysis">
    <div class="filter-area">
      <Row style="width:100%">
        <Col :span="6">
          <div class="filter-section param-section">
            <span class="filter-label">查询煤矿：</span>
            <div class="param-selector">
              <Select ref="select" v-model:value="selectedParamsText" placeholder="请选择煤矿" style="width: 300px">
                <SelectOption value="jack">Jack</SelectOption>
              </Select>
            </div>
          </div>
        </Col>
        <Col :span="6">
          <!-- 所属执法处 -->
          <div class="filter-section param-section">
            <span class="filter-label">所属执法处：</span>
            <div class="param-selector">
              <Select ref="select" v-model:value="sszfc" placeholder="请选择煤矿" style="width: 300px">
                <SelectOption v-for="(item, index) in deviceOptions1" :key="index">{{ item.value }}</SelectOption>
              </Select>
            </div>
          </div>
        </Col>
        <Col :span="6">
          <!-- 所属区域 -->
          <div class="filter-section param-section">
            <span class="filter-label">所属区域：</span>
            <div class="param-selector">
              <Select ref="select" v-model:value="ssqy" placeholder="请选择煤矿" style="width: 300px">
                <SelectOption v-for="(item, index) in deviceOptions1" :key="index">{{ item.value }}</SelectOption>
              </Select>
            </div>
          </div>
        </Col>
        <Col :span="6">
          <!-- 煤矿名称 -->
          <div class="filter-section param-section">
            <span class="filter-label">煤矿名称：</span>
            <div class="param-selector">
              <Input v-model="selectedParamsText" placeholder="请选择所属区域" readonly style="width: 300px" />
            </div>
          </div>
        </Col>
      </Row>

      <Row style="width:100%">
        <Col :span="6">
          <!-- 煤矿简称 -->
          <div class="filter-section param-section">
            <span class="filter-label">煤矿简称：</span>
            <div class="param-selector">
              <Input v-model="selectedParamsText" placeholder="请选择所属区域" readonly style="width: 300px" />
            </div>
          </div>
        </Col>
        <Col :span="6">
          <!-- 时间选择 -->
          <div class="filter-section param-section">
            <span class="filter-label">时间选择：</span>
            <RangePicker v-model="dateRange" format="YYYY-MM-DD HH:mm:ss" :placeholder="['开始时间', '结束时间']"
              style="width: 300px" :show-time="{ format: 'HH:mm:ss' }" />
          </div>
        </Col>
        <Col :span="6">
          <!-- 参数选择 -->
          <div class="filter-section param-section">
            <span class="filter-label">参数选择：</span>
            <div class="param-selector">
              <Input v-model="selectedParamsText" placeholder="请选择监测参数" readonly style="width: 300px" />
              <Button type="primary" @click="showTree = !showTree">+</Button>
              <div class="tree-popup" v-if="showTree">
                <BasicTree :treeData="treeData" :checkable="true" defaultExpandAll @check="handleTreeCheck"
                  :checkedKeys="checkedTreeKeys" />
              </div>
            </div>
          </div>
        </Col>
        <Col :span="6">
          <!-- 生成按钮 -->
          <div class="filter-section">
            <Button type="primary" @click="generateChart">生成</Button>
          </div>
        </Col>
      </Row>









    </div>
    <!-- 动态图表区域-->
    <div class="chart-area">
      <div class="chart-item" style="flex: 1 1 100%;">
        <div class="chart-placeholder">
          <template v-if="generatedChartData.length">
            <CustomChart :chart-data="generatedChartData" :chart-config="generatedChartConfig"
              style="height: 100%; width: 100%" />
          </template>
          <template v-else-if="isChartGenerated">
            <div class="empty-chart">暂无匹配数据，请调整筛选条件</div>
          </template>
          <template v-else>
            <div class="empty-chart">请选择时间范围和参数，点击"生成"查看数据</div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween'; // 引入 isBetween 插件
import { treeData, historicalMockChartData } from './connectAnalysis.data'; // 引入模拟数据
import { Row, Col, Select, SelectOption, DatePicker, Button, message, Input } from 'ant-design-vue';
import { BasicTree } from '/@/components/Tree/index';
import CustomChart from '/@/components/Configurable/detail/CustomChart.vue';
import { getMineData, getProvinceAlarm } from '../fireAreaJudgeAnalysis/fireAreaJudge.api';

// 关键：使用 dayjs 插件
dayjs.extend(isBetween);
// 组件注册
const RangePicker = DatePicker.RangePicker;
// 筛选相关响应式数据
const dateRange = ref([dayjs().subtract(1, 'day').toDate(), dayjs().toDate()]); // 默认时间范围（近1天）
const selectedParamsText = ref(''); // 参数选择框显示文本
const showTree = ref(false); // 控制树形选择器显示/隐藏
const checkedTreeKeys = ref([]); // 树形选中的key
const selectedParams = ref([]); // 选中的参数（实际用于图表）
const generatedChartData = ref<any[]>([]); // 生成的图表数据
const generatedChartConfig = ref({}); // 生成的图表配置
const isChartGenerated = ref(false); // 是否已点击生成

const cxmk = ref('')
const sszfc = ref('')
const ssqy = ref('')
//煤矿列表数据
const deviceOptions = ref([]);
const deviceOptions1 = ref([
  { label: '执法一处', value: '0' },
  { label: '执法二处', value: '1' },
  { label: '执法三处', value: '2' },
])

// Tree Key 与参数名映射（关键：关联树形节点和实际参数）
const treeKeyToParamMap = computed(() => ({
  '0-0-0': 'CO',
  '0-0-1': 'CH4',
  '0-0-2': 'C2H4',
  '0-0-3': 'C2H2',
  '0-0-4': 'CO2',
  '0-0-5': 'O2',
  '1-1-0': 'innerPressure',
  '1-1-1': 'outerPressure',
  '1-1-2': 'pressureDiff',
  '2-2': 'temperature',
}));
// 参数标签映射（图表系列名称）
const paramLabelMap = computed(() => ({
  'CO': 'CO浓度(ppm)',
  'CH4': 'CH4浓度(%)',
  'C2H4': 'C2H4浓度(ppm)',
  'C2H2': 'C2H2浓度(ppm)',
  'CO2': 'CO2浓度(%)',
  'O2': 'O2浓度(%)',
  'innerPressure': '内压力(kPa)',
  'outerPressure': '外压力(kPa)',
  'pressureDiff': '压差(kPa)',
  'temperature': '温度(℃)',
}));
// 参数颜色映射
const paramColorMap = computed(() => ({
  'CO': '#f5222d',    // 红色
  'CH4': '#1890ff',   // 蓝色
  'C2H4': '#faad14',  // 橙色
  'C2H2': '#52c41a',  // 绿色
  'CO2': '#722ed1',   // 紫色
  'O2': '#13c2c2',    // 青色
  'innerPressure': '#ff4d4f', // 浅红
  'outerPressure': '#40a9ff',// 浅蓝
  'pressureDiff': '#fa8c16', // 浅橙
  'temperature': '#9254de',  // 浅紫
}));

// 树形选择事件处理
const handleTreeCheck = (checkedKeys) => {
  checkedTreeKeys.value = checkedKeys;
  // 转换为实际参数名
  const params = checkedKeys
    .map(key => treeKeyToParamMap.value[key])
    .filter(param => param); // 过滤无效参数
  selectedParams.value = params;

  // 更新输入框显示文本
  const paramLabels = params.map(param => paramLabelMap.value[param]);
  selectedParamsText.value = paramLabels.join('、');
};

// 生成折线图核心逻辑
const generateChart = () => {
  // 校验筛选条件
  if (!dateRange.value[0] || !dateRange.value[1]) {
    message.warning('请选择完整的时间范围');
    return;
  }
  if (selectedParams.value.length === 0) {
    message.warning('请至少选择一个监测参数');
    return;
  }

  isChartGenerated.value = true;
  const start = dayjs(dateRange.value[0]); // 转为 dayjs 实例
  const end = dayjs(dateRange.value[1]);   // 转为 dayjs 实例

  // 1. 筛选时间范围内的模拟数据（修复核心漏洞）
  const filteredData = historicalMockChartData.filter(item => {
    const itemTime = dayjs(item.time); // 解析 item.time 为 dayjs 实例
    // 修复 isBetween 用法：明确指定 unit 为 'second'，包容性为 '[]'
    return itemTime.isBetween(start, end, 'second', '[]');
  });

  // 2. 构建图表数据结构（适配 CustomChart 的 line 类型）
  const timeMap = new Map();
  // 修复变量名：filteredRawData → filteredData（之前未定义）
  filteredData.forEach((item) => {
    const timeStr = dayjs(item.time).format('YYYY-MM-DD HH:mm:ss');
    if (!timeMap.has(timeStr)) {
      timeMap.set(timeStr, { time: timeStr });
    }
    // 只保留选中的参数数据
    selectedParams.value.forEach(param => {
      if (item[param] !== undefined) {
        timeMap.get(timeStr)[param] = item[param];
      }
    });
  });

  // 转换为数组并按时间排序
  const chartData = Array.from(timeMap.values()).sort((a, b) => {
    return dayjs(a.time).valueOf() - dayjs(b.time).valueOf();
  });
  generatedChartData.value = chartData;

  // 3. 构建图表配置（折线图类型，完善适配逻辑）
  generatedChartConfig.value = {
    type: 'line', // 折线图
    clear: true, // 每次生成清空之前的图表
    legend: { show: true, top: 10, right: 10 },
    xAxis: [
      {
        type: 'category',
        axisLabel: {
          rotate: 30,
          formatter: (value) => dayjs(value).format('HH:mm:ss'),
          interval: Math.max(1, Math.floor(chartData.length / 10)) // 控制x轴标签密度
        }
      }
    ],
    yAxis: selectedParams.value.map(param => ({
      type: 'value',
      name: paramLabelMap.value[param].split('(')[1].replace(')', ''), // 显示单位
      nameTextStyle: { color: paramColorMap.value[param] },
      axisLine: { lineStyle: { color: paramColorMap.value[param] } },
      splitLine: { lineStyle: { opacity: 0.1 } }
    })),
    series: selectedParams.value.map((param, index) => ({
      name: paramLabelMap.value[param],
      type: 'line',
      readFrom: '', // 适配 CustomChart 的 baseSeries 读取逻辑
      label: paramLabelMap.value[param],
      xprop: 'time', // 对应图表数据的 x 字段（时间）
      yprop: param, // 对应图表数据的 y 字段（参数值）
      color: paramColorMap.value[param],
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      yAxisIndex: index,
    })),
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      formatter: (params) => {
        let tooltipHtml = `<div>${dayjs(params[0].axisValue).format('YYYY-MM-DD HH:mm:ss')}</div>`;
        params.forEach(param => {
          tooltipHtml += `<div style="color: ${param.color}">${param.seriesName}: ${param.value[1]} ${param.seriesName.split('(')[1].replace(')', '')}</div>`;
        });
        return tooltipHtml;
      }
    },
    grid: { left: 60, top: 40, right: 60, bottom: 60 }
  };

  // 无数据提示
  if (chartData.length === 0) {
    message.info('当前筛选条件下无数据');
  }
};

const getMineDataList = async () => {
  const params = {
    pageNo: 1,
    pageSize: 50,
  };
  const response = await getMineData(params);
  deviceOptions.value = response.records.map((item, index) => {
    return {
      label: item['mineName'],
      value: item['mineCode'],
    };
  });
};

onMounted(() => {
  // 页面挂载时的逻辑
  getMineDataList();
});

</script>

<style lang="less" scoped>
.connectAnalysis {
  padding: 16px;

  .filter-area {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 20px;
    padding: 20px;
    border: 1px solid #f0f0f0;
    border-radius: 10px;
    background: #f8f9fc;
    align-items: center;
  }

  .filter-section {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .filter-label {
    color: #666;
    min-width: 80px;
    flex-shrink: 0;
    font-weight: 500;
  }

  .param-section {
    flex: 1;
    // min-width: 300px;
  }

  .param-selector {
    display: flex;
    align-items: center;
    gap: 8px;
    position: relative;
  }

  .tree-popup {
    position: absolute;
    top: 100%;
    left: 0;
    margin-top: 8px;
    width: 300px;
    max-height: 300px;
    overflow-y: auto;
    background: #fff;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    z-index: 100;
    padding: 8px;
  }

  .chart-area {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    padding: 20px;
    border: 1px solid #f0f0f0;
    border-radius: 10px;
    background: #f8f9fc;
  }

  .chart-item {
    flex: 1;
    min-width: 200px;
  }

  .chart-placeholder {
    width: 100%;
    height: 300px;
    border-radius: 4px;
    overflow: hidden;
    background: #333;
    border: 1px solid #eee;
  }

  .empty-chart {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
    font-size: 14px;
  }
}
</style>
