<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="tree"
            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="queryForm" 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 label="振动参数">
            <el-select v-model="selectedVibrationParam" placeholder="请选择振动参数" style="width: 150px" @change="handleQuery">
              <el-option label="振动速度" value="vibrationSpeed"></el-option>
              <el-option label="振动位移" value="vibrationDisplacement"></el-option>
              <el-option label="振动加速度" value="vibrationAcceleration"></el-option>
              <el-option label="振动温度" value="vibrationTemp"></el-option>
            </el-select>
          </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>

        <!-- 根据选中参数只显示单个图表 -->
        <Chart ref="VibrationChart" class="vibration-chart" />
      </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 { getRecordIotenvInstantList } from '@/api/ems/record/recordIotenvInstant';

defineOptions({
  name: 'currentVibrationCurve',
  dicts: ['collect_type']
} as any);

const { proxy } = getCurrentInstance() as any;

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

const VibrationChart = ref<any>();
const queryForm = ref<any>();
const tree = ref<any>();

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

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  // 选中的振动参数（默认振动速度）
  selectedVibrationParam: 'vibrationSpeed',
  //下拉树List
  baseMonitorInfoOptions: [],
  //左侧树结构List
  monitorInfoOptions: [],
  workUnitName: undefined,
  //左侧树结构 检索设备名称
  selectMonitorName: null,
  //计量设备信息
  baseMonitorInfoList: [],
  // 采集方式时间范围
  daterangeRecordTime: [],
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 电实时数据表格数据
  dataList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    objId: null,
    collectTime: null,
    monitorId: 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,
  columns,
  dataList,
  daterangeRecordTime,
  form,
  ids,
  loading,
  monitorInfoOptions,
  monitorProps,
  multiple,
  open,
  queryParams,
  reportSelection,
  rules,
  selectMonitorName,
  selectedVibrationParam,
  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);
  return {
    mode: monitorIds.length > 1 ? 'group' : 'single',
    monitorId: monitorIds.length === 1 ? monitorIds[0] : '',
    monitorIds,
    monitorName: defaultName,
    monitorType: '10',
    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; // 重置采样间隔为默认值
  queryForm.value?.resetFields();
  handleQuery();
};

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

const getTreeselect = () => {
  getMonitorInfoTree({
    monitorType: 10
  }).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: '10',
    deviceDisplayMap: {
      [data.code]: {
        label: data.label,
        type: data.type
      }
    }
  };
  handleQuery();
};

const getChart = async () => {
  if (queryParams.value.monitorId == null) {
    return;
  }
  const query = JSON.parse(JSON.stringify(queryParams.value));
  // 传递选中的振动参数到后端，让SQL根据该参数过滤
  query.vibrationParam = selectedVibrationParam.value;
  const { data } = await getRecordIotenvInstantList(query);

  // 参数配置映射
  const paramConfig = {
    vibrationSpeed: {
      name: '速度(mm/s)',
      title: '速度曲线',
      field: 'vibrationSpeed'
    },
    vibrationDisplacement: {
      name: '位移(μm)',
      title: '位移曲线',
      field: 'vibrationDisplacement'
    },
    vibrationAcceleration: {
      name: '加速度(g)',
      title: '加速度曲线',
      field: 'vibrationAcceleration'
    },
    vibrationTemp: {
      name: '温度(℃)',
      title: '温度曲线',
      field: 'vibrationTemp'
    }
  };
  const config = paramConfig[selectedVibrationParam.value];

  // 过滤无效值：小于等于0或大于等于80的数值不显示
  const validPoints = data.filter((e) => {
    const value = parseFloat(e[config.field]);
    return !isNaN(value) && value > 0 && value < 80;
  });
  // 提取有效数据的时间和数值（保持一一对应）
  const timeData = validPoints.map((e) => e.recodeTime);
  const validData = validPoints.map((e) => parseFloat(e[config.field]));
  const option = {
    title: {
      text: selectMonitorName.value + ' ' + config.title,
      x: 'center'
    },
    grid: {
      top: '15%',
      bottom: '15%',
      left: '10%',
      right: '5%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true
        }
      }
    },
    dataZoom: [
      {
        type: 'slider'
      }
    ],
    legend: {
      right: 0
    },
    xAxis: {
      data: timeData,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#000000'
        }
      },
      axisTick: {
        show: true
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#000000'
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: config.name,
        min: 0,
        nameTextStyle: {
          color: '#000000'
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed'
          }
        },
        axisTick: {
          show: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000000'
          }
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000000'
          },
          formatter: function (value) {
            return value.toFixed(2); // 保留2位小数
          }
        }
      }
    ],
    series: [
      {
        name: config.name,
        connectNulls: true,
        // 跳过null值但保持曲线连续光滑
        type: 'line',
        smooth: true,
        // 平滑曲线显示
        showAllSymbol: true,
        symbol: 'circle',
        symbolSize: 8,
        data: validData
      }
    ]
  };
  VibrationChart.value.setData(option);
};

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: '10'
    })
  );
  // 振动报表透传当前主看参数，保证仪表盘和漏斗图与曲线关注维度一致。
  proxy?.$router.push({
    path: '/ems/report/recordIotenvInstantDashboard/index',
    query: {
      selectionKey,
      source: 'vibration',
      compareScope: reportSelection.mode,
      monitorId: reportSelection.monitorId,
      monitorIds: (reportSelection.monitorIds || []).join(','),
      monitorName: reportSelection.monitorName,
      selectionLabel: reportSelection.monitorName,
      monitorType: '10',
      samplingInterval: String(queryParams.value.samplingInterval || 1),
      beginRecordTime: daterangeRecordTime.value[0],
      endRecordTime: daterangeRecordTime.value[1],
      vibrationParam: selectedVibrationParam.value
    }
  });
};

watch(workUnitName, (val) => {
  tree.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>
/* 单个振动曲线图表样式 */
.vibration-chart {
  width: 100%;
  height: 70vh;
  display: block;
}
</style>
