<template>
  <div class="app-container">
    <el-row :gutter="28">
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workUnitName"
            placeholder="请输入计量设备名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="monitorInfoOptions"
            :props="monitorProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="treeRef"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="100px">
          <!--          <el-form-item label="计量设备编号" prop="monitorCode">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.monitorCode"-->
          <!--              placeholder="请输入计量设备编号"-->
          <!--              clearable-->
          <!--              @keyup.enter="handleQuery"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item label="记录时间">
            <el-date-picker
              v-model="daterangeRecordTime"
              style="width: 340px"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="采样间隔">
            <el-input-number v-model="queryParams.samplingInterval" :min="1" :max="1440" placeholder="分钟" style="width: 120px"></el-input-number>
            <span style="margin-left: 5px; color: #909399">分钟/点</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="warning" plain icon="el-icon-data-analysis" size="mini" @click="openReportPage"> 多维报表 </el-button>
          </el-form-item>
        </el-form>

        <!-- 根据设备类型显示对应的图表 -->
        <!-- type=5: 只显示温度 -->
        <Chart v-if="selectedDeviceType === 5" ref="Chart2" class="chart-single" />

        <!-- type=6: 显示温度和湿度 -->
        <div v-if="selectedDeviceType === 6">
          <Chart ref="Chart1" class="chart-half" />
          <Chart ref="Chart2" class="chart-half" />
        </div>

        <!-- type=7: 只显示噪声 -->
        <Chart v-if="selectedDeviceType === 7" ref="Chart4" class="chart-single" />

        <!-- 未选择设备或其他类型时显示提示 -->
        <div v-if="!selectedDeviceType" class="no-data-tip">
          <p>请在左侧树中选择具体设备节点查看数据曲线</p>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { useDict } from '@/utils/dict';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { parseTime } from '@/utils/ruoyi';
import Chart from '@/components/Charts/Chart';
import * as echarts from 'echarts';
import { getRecordIotenvInstantList } from '@/api/ems/record/recordIotenvInstant';

defineOptions({
  name: 'currentIOTCurve',
  dicts: ['collect_type']
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dict = reactive({
  type: useDict('collect_type')
});

interface CurveChartExpose {
  chart?: echarts.ECharts;
  setData: (option: echarts.EChartsOption) => void;
}

const Chart1 = ref<CurveChartExpose | null>(null);
const Chart2 = ref<CurveChartExpose | null>(null);
const Chart4 = ref<CurveChartExpose | null>(null);
const queryFormRef = ref<ElFormInstance>();
const treeRef = ref<ElTreeInstance>();

// 这里统一通过工厂函数重建表单，避免弹窗在新增/编辑切换时残留上一条业务数据。
const createFormData = () => ({
  objId: null,
  monitorId: null,
  speed: null,
  displacement: null,
  acceleration: null,
  temperature: null,
  recodeTime: null,
  remark: null
});

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  //下拉树List
  baseMonitorInfoOptions: [],
  //左侧树结构List
  monitorInfoOptions: [],
  workUnitName: undefined,
  //左侧树结构 检索设备名称
  selectMonitorName: null,
  //计量设备信息
  baseMonitorInfoList: [],
  // 选中设备的类型，用于控制图表显示
  selectedDeviceType: null,
  // 采集方式时间范围
  daterangeRecordTime: [],
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 电实时数据表格数据
  dataList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    objId: null,
    monitorId: null,
    collectTime: null,
    speed: null,
    displacement: null,
    acceleration: null,
    temperature: null,
    recodeTime: null,
    remark: null,
    monitorIds: [],
    samplingInterval: 1 // 采样间隔，默认1分钟（不采样）
  },
  // 表单参数
  form: createFormData(),
  // 报表入口允许父节点、多设备甚至全量对比，所以单独保存报表选择上下文。
  reportSelection: {
    mode: 'all',
    monitorId: '',
    monitorIds: [],
    monitorName: ''
  },
  monitorProps: {
    children: 'children',
    label: 'label'
  },
  // 表单校验
  rules: {
    objId: [
      {
        required: true,
        message: '编号不能为空',
        trigger: 'blur'
      }
    ]
  }
  // columns: [
  //   { key: 0, label: `主键标识`, visible: false },
  //   { key: 1, label: `采集时间`, visible: true },
  //   { key: 2, label: `振动传感器编号编号`, visible: true },
  //   { key: 3, label: `速度(mm/s)`, visible: true },
  //   { key: 4, label: `位移(um)`, visible: true },
  //   { key: 5, label: `加速度(g)`, visible: true },
  //   { key: 6, label: `温度(℃)`, visible: true },
  //   { key: 7, label: `记录时间`, visible: true },
  //   { key: 8, label: `备注`, visible: true },
  // ]
} as any);

const {
  baseMonitorInfoList,
  baseMonitorInfoOptions,
  dataList,
  daterangeRecordTime,
  form,
  ids,
  loading,
  monitorInfoOptions,
  monitorProps,
  multiple,
  open,
  queryParams,
  reportSelection,
  rules,
  selectMonitorName,
  selectedDeviceType,
  showSearch,
  single,
  title,
  total,
  workUnitName
} = toRefs(state);

const normalizer = (node) => {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.monitorCode,
    label: node.monitorName,
    children: node.children
  };
};

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

const buildReportSelectionByNodes = (nodes, defaultName) => {
  const leafNodes = getLeafMonitorNodes(nodes);
  const monitorIds = leafNodes.map((item) => item.code);
  const typeSet = leafNodes.map((item) => item.type).filter((item) => item !== null && item !== undefined && item !== '');
  return {
    mode: monitorIds.length > 1 ? 'group' : 'single',
    monitorId: monitorIds.length === 1 ? monitorIds[0] : '',
    monitorIds,
    monitorName: defaultName,
    monitorType: Array.from(new Set(typeSet)).join(','),
    deviceDisplayMap: leafNodes.reduce((accumulator, item) => {
      accumulator[item.code] = {
        label: item.label,
        type: item.type
      };
      return accumulator;
    }, {})
  };
};

const resolveReportSelection = () => {
  if (reportSelection.value.monitorId || (reportSelection.value.monitorIds && reportSelection.value.monitorIds.length > 0)) {
    return reportSelection.value;
  }
  const allSelection = buildReportSelectionByNodes(monitorInfoOptions.value, '当前页面全部物联设备');
  allSelection.mode = allSelection.monitorIds.length > 1 ? 'all' : allSelection.mode;
  return allSelection;
};

const getList = () => {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeRecordTime.value && '' != daterangeRecordTime.value) {
    queryParams.value.params['beginRecordTime'] = daterangeRecordTime.value[0];
    queryParams.value.params['endRecordTime'] = daterangeRecordTime.value[1];
  }
  getChart();
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    objId: null,
    monitorId: null,
    speed: null,
    displacement: null,
    acceleration: null,
    temperature: null,
    recodeTime: null,
    remark: null
  };
  form.value?.resetFields();
};

const handleQuery = () => {
  getList();
};

const resetQuery = () => {
  queryParams.value.monitorCode = null;
  queryParams.value.monitorId = null;
  queryParams.value.samplingInterval = 1; // 重置采样间隔为默认值
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleExport = () => {
  proxy?.download(
    'ems/record/recordVibrationInstant/export',
    {
      ...queryParams.value
    },
    `recordVibrationInstant_${new Date().getTime()}.xlsx`
  );
};

const getTreeselect = () => {
  getMonitorInfoTree({
    monitorTypeList: [5, 6, 7, 8, 9]
  }).then((response) => {
    monitorInfoOptions.value = response.data;
    reportSelection.value = resolveReportSelection();
  });
};

const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const handleNodeClick = (data) => {
  if (data.children && data.children.length > 0) {
    reportSelection.value = buildReportSelectionByNodes(data.children, data.label);
    reportSelection.value.mode = 'group';
    ElMessage.info('父节点已用于多设备报表对比；曲线仍需选择具体设备节点查看');
    return;
  }

  // 点击节点时清空monitorIds，只使用选中的monitorId
  queryParams.value.monitorIds = [];
  queryParams.value.monitorId = data.code;
  selectMonitorName.value = data.label;
  reportSelection.value = {
    mode: 'single',
    monitorId: data.code,
    monitorIds: [data.code],
    monitorName: data.label,
    monitorType: String(data.type || ''),
    deviceDisplayMap: {
      [data.code]: {
        label: data.label,
        type: data.type
      }
    }
  };

  // 存储选中设备的类型，用于控制图表显示
  selectedDeviceType.value = data.type;
  console.log('选中设备:', data.label, 'type:', data.type);
  handleQuery();
};

const getChart = async () => {
  if (queryParams.value.monitorId == null || !selectedDeviceType.value) {
    return;
  }
  const query = JSON.parse(JSON.stringify(queryParams.value));
  const { data } = await getRecordIotenvInstantList(query);
  console.log('数据条数:', data.length);

  // 根据设备类型创建对应的图表配置
  createChartByType(data);
};

const createChartByType = (data) => {
  switch (selectedDeviceType.value) {
    case 5:
      // 温度传感器：只显示温度
      createTemperatureChart(data);
      break;
    case 6:
      // 温湿度传感器：显示温度和湿度
      createHumidityChart(data);
      createTemperatureChart(data);
      linkCharts([Chart1, Chart2]);
      break;
    case 7:
      // 噪声传感器：只显示噪声
      createNoiseChart(data);
      break;
    default:
      console.warn('未知的设备类型:', selectedDeviceType.value);
  }
};

const openReportPage = () => {
  if (!daterangeRecordTime.value || daterangeRecordTime.value.length !== 2) {
    ElMessage.warning('请先选择完整的记录时间范围');
    return;
  }
  const reportSelection = resolveReportSelection();
  if (!reportSelection.monitorId && (!reportSelection.monitorIds || reportSelection.monitorIds.length === 0)) {
    ElMessage.warning('当前没有可用于报表分析的设备');
    return;
  }
  const selectionKey = 'recordIotenvInstantDashboardSelection';
  // 报表页优先展示树上的设备真实名称，避免只显示编码影响业务识别。
  window.sessionStorage.setItem(
    selectionKey,
    JSON.stringify({
      deviceDisplayMap: reportSelection.deviceDisplayMap || {},
      selectionLabel: reportSelection.monitorName,
      monitorType: reportSelection.monitorType || String(selectedDeviceType.value || '')
    })
  );
  // 显式透传当前查询上下文，避免报表页重新猜设备与时间造成统计口径不一致。
  proxy?.$router.push({
    path: '/ems/report/recordIotenvInstantDashboard/index',
    query: {
      selectionKey,
      source: 'iot',
      compareScope: reportSelection.mode,
      monitorId: reportSelection.monitorId,
      monitorIds: (reportSelection.monitorIds || []).join(','),
      monitorName: reportSelection.monitorName,
      selectionLabel: reportSelection.monitorName,
      monitorType: reportSelection.monitorType || String(selectedDeviceType.value || ''),
      samplingInterval: String(queryParams.value.samplingInterval || 1),
      beginRecordTime: daterangeRecordTime.value[0],
      endRecordTime: daterangeRecordTime.value[1]
    }
  });
};

const createHumidityChart = (data) => {
  const option = {
    title: {
      text: selectMonitorName.value + ' 湿度曲线',
      x: 'center'
    },
    grid: {
      top: '15%',
      bottom: '10%',
      left: '10%',
      right: '3%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true
        }
      }
    },
    dataZoom: [
      {
        type: 'slider'
      }
    ],
    legend: {
      right: 0
    },
    xAxis: {
      data: data.map((e) => e.recodeTime),
      axisLine: {
        show: true,
        lineStyle: {
          color: '#000000'
        }
      },
      axisTick: {
        show: true
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#000000'
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '湿度(%)',
        nameTextStyle: {
          color: '#000000'
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000000'
          }
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000000'
          }
        }
      }
    ],
    series: [
      {
        name: '湿度',
        connectNulls: true,
        type: 'line',
        smooth: true,
        showAllSymbol: true,
        symbol: 'circle',
        symbolSize: 10,
        data: data.map((e) => e.humidity)
      }
    ]
  };
  Chart1.value.setData(option);
};

const createTemperatureChart = (data) => {
  const option = {
    title: {
      text: selectMonitorName.value + ' 温度曲线',
      x: 'center'
    },
    grid: {
      top: '15%',
      bottom: '10%',
      left: '10%',
      right: '3%'
    },
    dataZoom: [
      {
        type: 'slider'
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true
        }
      }
    },
    legend: {
      right: 0
    },
    xAxis: {
      data: data.map((e) => e.recodeTime),
      axisLine: {
        show: true,
        lineStyle: {
          color: '#000000'
        }
      },
      axisTick: {
        show: true
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#000000'
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '温度(℃)',
        nameTextStyle: {
          color: '#000000'
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000000'
          }
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000000'
          }
        }
      }
    ],
    series: [
      {
        name: '温度(℃)',
        connectNulls: true,
        type: 'line',
        smooth: true,
        showAllSymbol: true,
        symbol: 'circle',
        symbolSize: 10,
        data: data.map((e) => e.temperature)
      }
    ]
  };
  Chart2.value.setData(option);
};

const createNoiseChart = (data) => {
  const option = {
    title: {
      text: selectMonitorName.value + ' 噪声曲线',
      x: 'center'
    },
    grid: {
      top: '15%',
      bottom: '10%',
      left: '10%',
      right: '3%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true
        }
      }
    },
    dataZoom: [
      {
        type: 'slider'
      }
    ],
    legend: {
      right: 0
    },
    xAxis: {
      data: data.map((e) => e.recodeTime),
      axisLine: {
        show: true,
        lineStyle: {
          color: '#000000'
        }
      },
      axisTick: {
        show: true
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#000000'
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '噪声(dB)',
        nameTextStyle: {
          color: '#000000'
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000000'
          }
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000000'
          }
        }
      }
    ],
    series: [
      {
        name: '噪声',
        connectNulls: true,
        type: 'line',
        smooth: true,
        showAllSymbol: true,
        symbol: 'circle',
        symbolSize: 10,
        data: data.map((e) => e.noise)
      }
    ]
  };
  Chart4.value.setData(option);
};

const linkCharts = (chartRefs: Array<Ref<CurveChartExpose | null>>) => {
  if (chartRefs.length < 2) return;

  // 连接图表
  const charts = chartRefs.map((item) => item.value?.chart).filter((item): item is echarts.ECharts => Boolean(item));
  echarts.connect(charts);

  // 设置缩放联动
  chartRefs.forEach((chartRef, index) => {
    chartRef.value?.chart?.on('datazoom', (event) => {
      const zoomEvent = event as { start: number; end: number };
      chartRefs.forEach((otherRef, otherIndex) => {
        if (index !== otherIndex) {
          // 更新其他图表的缩放
          otherRef.value?.chart?.dispatchAction({
            type: 'dataZoom',
            start: zoomEvent.start,
            end: zoomEvent.end
          });
        }
      });
    });
  });
};

watch(workUnitName, (val) => {
  treeRef.value?.filter(val);
});

onMounted(() => {
  const nowDate = parseTime(new Date(), '{y}-{m}-{d}');
  daterangeRecordTime.value[0] = nowDate + ' 09:00:00';
  daterangeRecordTime.value[1] = nowDate + ' 09:10:00';
  getTreeselect();
  getList();
});
</script>
<style scoped>
/* 单个图表样式（type=5温度 或 type=7噪声） */
.chart-single {
  width: 100%;
  height: 60vh;
  margin: 20px 0;
}

/* 双图表样式（type=6温湿度） */
.chart-half {
  width: 50%;
  height: 45vh;
  display: inline-block;
  margin: 10px 0;
}

/* 提示信息样式 */
.no-data-tip {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 16px;
}

/* 保留原有样式以防兼容性问题 */
.chart1 {
  width: 50%;
  height: 40vh;
  display: inline-block;
}
.chart2 {
  width: 50%;
  height: 40vh;
  display: inline-block;
}
.chart3 {
  width: 50%;
  height: 40vh;
  display: inline-block;
}
.chart4 {
  width: 50%;
  display: inline-block;
  height: 40vh;
}
.chart5 {
  width: 50%;
  display: inline-block;
  height: 40vh;
}
</style>
