<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="monitorId">
                                      <el-input
                                              v-model="queryParams.monitorId"
                                              placeholder="请输入计量设备编号"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="温度" prop="temperature">
                                      <el-input
                                              v-model="queryParams.temperature"
                                              placeholder="请输入温度"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="湿度" prop="humidity">
                                      <el-input
                                              v-model="queryParams.humidity"
                                              placeholder="请输入湿度"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="照度" prop="illuminance">
                                      <el-input
                                              v-model="queryParams.illuminance"
                                              placeholder="请输入照度"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="噪声" prop="noise">
                                      <el-input
                                              v-model="queryParams.noise"
                                              placeholder="请输入噪声"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="硫化氢浓度" prop="concentration">
                                      <el-input
                                              v-model="queryParams.concentration"
                                              placeholder="请输入硫化氢浓度"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="振动-速度(mm/s)" prop="vibrationSpeed">
                                      <el-input
                                              v-model="queryParams.vibrationSpeed"
                                              placeholder="请输入振动-速度(mm/s)"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="振动-位移(um)" prop="vibrationDisplacement">
                                      <el-input
                                              v-model="queryParams.vibrationDisplacement"
                                              placeholder="请输入振动-位移(um)"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="振动-加速度(g)" prop="vibrationAcceleration">
                                      <el-input
                                              v-model="queryParams.vibrationAcceleration"
                                              placeholder="请输入振动-加速度(g)"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>
                                  <el-form-item label="振动-温度(℃)" prop="vibrationTemp">
                                      <el-input
                                              v-model="queryParams.vibrationTemp"
                                              placeholder="请输入振动-温度(℃)"
                                              clearable
                                              @keyup.enter="handleQuery"
                                      />
                                  </el-form-item>-->
          <!--                        <el-form-item label="采集时间" prop="collectTime">
                                      <el-date-picker clearable
                                                      v-model="queryParams.collectTime"
                                                      type="date"
                                                      value-format="yyyy-MM-dd"
                                                      placeholder="请选择采集时间">
                                      </el-date-picker>
                                  </el-form-item>-->
          <!--                        <el-form-item label="记录时间" prop="recodeTime">
                                      <el-date-picker clearable
                                                      v-model="queryParams.recodeTime"
                                                      type="date"
                                                      value-format="yyyy-MM-dd"
                                                      placeholder="请选择记录时间">
                                      </el-date-picker>
                                  </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-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-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['ems/record:recordVibrationInstant:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['ems/record:recordVibrationInstant:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['ems/record:recordVibrationInstant:remove']"
            >删除</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['ems/record:recordVibrationInstant:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="recordIotenvInstantList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="计量设备" align="center" prop="monitorName" min-width="150"> </el-table-column>

          <!-- 振动设备专用列：根据选中参数动态显示单列 -->
          <el-table-column v-if="selectedVibrationParam === 'vibrationSpeed'" label="振动速度(mm/s)" align="center" prop="vibrationSpeed" width="150">
          </el-table-column>
          <el-table-column
            v-if="selectedVibrationParam === 'vibrationDisplacement'"
            label="振动位移(μm)"
            align="center"
            prop="vibrationDisplacement"
            width="150"
          >
          </el-table-column>
          <el-table-column
            v-if="selectedVibrationParam === 'vibrationAcceleration'"
            label="振动加速度(g)"
            align="center"
            prop="vibrationAcceleration"
            width="150"
          >
          </el-table-column>
          <el-table-column v-if="selectedVibrationParam === 'vibrationTemp'" label="振动温度(℃)" align="center" prop="vibrationTemp" width="150">
          </el-table-column>

          <!-- 记录时间列，给足够的宽度 -->
          <el-table-column label="记录时间" align="center" prop="recodeTime" width="200"> </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
            <template #default="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['ems/record:recordIotenvInstant:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['ems/record:recordIotenvInstant:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改物联网数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="计量设备编号" prop="monitorId">
          <el-input v-model="form.monitorId" placeholder="请输入计量设备编号" />
        </el-form-item>
        <!-- <el-form-item label="温度" prop="temperature">
          <el-input v-model="form.temperature" placeholder="请输入温度" />
        </el-form-item>
        <el-form-item label="湿度" prop="humidity">
          <el-input v-model="form.humidity" placeholder="请输入湿度" />
        </el-form-item>
        <el-form-item label="照度" prop="illuminance">
          <el-input v-model="form.illuminance" placeholder="请输入照度" />
        </el-form-item>
        <el-form-item label="噪声" prop="noise">
          <el-input v-model="form.noise" placeholder="请输入噪声" />
        </el-form-item>
        <el-form-item label="硫化氢浓度" prop="concentration">
          <el-input v-model="form.concentration" placeholder="请输入硫化氢浓度" />
        </el-form-item> -->
        <el-form-item label="振动-速度(mm/s)" prop="vibrationSpeed">
          <el-input v-model="form.vibrationSpeed" placeholder="请输入振动-速度(mm/s)" />
        </el-form-item>
        <el-form-item label="振动-位移(um)" prop="vibrationDisplacement">
          <el-input v-model="form.vibrationDisplacement" placeholder="请输入振动-位移(um)" />
        </el-form-item>
        <el-form-item label="振动-加速度(g)" prop="vibrationAcceleration">
          <el-input v-model="form.vibrationAcceleration" placeholder="请输入振动-加速度(g)" />
        </el-form-item>
        <el-form-item label="振动-温度(℃)" prop="vibrationTemp">
          <el-input v-model="form.vibrationTemp" placeholder="请输入振动-温度(℃)" />
        </el-form-item>
        <!-- <el-form-item label="采集时间" prop="collectTime">
          <el-date-picker clearable
                          v-model="form.collectTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择采集时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="记录时间" prop="recodeTime">
          <el-date-picker clearable v-model="form.recodeTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择记录时间"> </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  listRecordIotenvInstant,
  getRecordIotenvInstant,
  delRecordIotenvInstant,
  addRecordIotenvInstant,
  updateRecordIotenvInstant
} from '@/api/ems/record/recordIotenvInstant';
import { handleTree, parseTime } from '@/utils/ruoyi';
import { getMonitorInfoTree, listBaseMonitorInfo } from '@/api/ems/base/baseMonitorInfo';
import { getCurrentInstance, ref } from 'vue';

defineOptions({
  name: 'RecordIotenvInstant'
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const formRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const treeRef = ref<ElTreeInstance>();

// 这里统一通过工厂函数重建表单，避免弹窗在新增/编辑切换时残留上一条业务数据。
const createFormData = () => ({
  objid: null,
  monitorId: null,
  temperature: null,
  humidity: null,
  illuminance: null,
  noise: null,
  concentration: null,
  vibrationSpeed: null,
  vibrationDisplacement: null,
  vibrationAcceleration: null,
  vibrationTemp: null,
  collectTime: null,
  recodeTime: null
});

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  // 选中的振动参数（默认振动速度）
  selectedVibrationParam: 'vibrationSpeed',
  workUnitName: null,
  //下拉树List
  baseMonitorInfoOptions: [],
  //左侧树结构List
  monitorInfoOptions: [],
  //能原类型信息
  baseMonitorInfoList: [],
  monitorProps: {
    children: 'children',
    label: 'label'
  },
  // 记录时间时间范围
  daterangeRecordTime: [],
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 物联网数据表格数据
  recordIotenvInstantList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    params: {},
    pageNum: 1,
    pageSize: 10,
    monitorId: null,
    temperature: null,
    humidity: null,
    illuminance: null,
    noise: null,
    concentration: null,
    vibrationSpeed: null,
    vibrationDisplacement: null,
    vibrationAcceleration: null,
    vibrationTemp: null,
    collectTime: null,
    recodeTime: null,
    monitorIds: [],
    monitorName: null
  },
  // 表单参数
  form: createFormData(),
  // 表单校验
  rules: {}
} as any);

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

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

const getTreeMonitorInfo = () => {
  listBaseMonitorInfo({
    monitorType: 10
  }).then((response) => {
    baseMonitorInfoOptions.value = [];
    const data = {
      objId: 0,
      monitorName: '顶级节点',
      children: []
    };
    data.children = handleTree(response.data, 'objId', 'parentId');
    baseMonitorInfoOptions.value.push(data);
  });
};

const getAllMonitorIds = (nodes) => {
  let ids = [];
  if (!nodes || nodes.length === 0) return ids;
  nodes.forEach((node) => {
    if (node.code) {
      ids.push(node.code);
    }
    if (node.children && node.children.length > 0) {
      ids = ids.concat(getAllMonitorIds(node.children));
    }
  });
  console.log(ids);
  return ids;
};

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

const handleNodeClick = (data) => {
  // 清空之前的查询条件
  queryParams.value.monitorIds = [];
  queryParams.value.monitorId = null;

  // 判断是否为父节点（有children属性）
  if (data.children && data.children.length > 0) {
    // 父节点：收集所有子节点的code
    queryParams.value.monitorIds = data.children.map((child) => child.code);
    console.log('点击振动设备父节点:', data.label, '子节点codes:', queryParams.value.monitorIds);
  } else {
    // 子节点：使用单个设备code
    queryParams.value.monitorId = data.code;
    console.log('点击振动设备子节点:', data.label, 'code:', data.code);
  }
  handleQuery();
};

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

  // 如果没有选中具体设备且没有设备ID列表，则不执行查询
  if (!queryParams.value.monitorId && queryParams.value.monitorIds.length === 0) {
    recordIotenvInstantList.value = [];
    total.value = 0;
    loading.value = false;
    console.log('没有振动设备数据可查询');
    return;
  }

  // 传递选中的振动参数到后端，让SQL根据该参数过滤
  queryParams.value.vibrationParam = selectedVibrationParam.value;
  listRecordIotenvInstant(queryParams.value).then((response) => {
    // 后端已根据vibrationParam过滤，前端再做一次保险过滤
    const filteredRows = response.rows.filter((row) => {
      const value = parseFloat(row[selectedVibrationParam.value]);
      return !isNaN(value) && value > 0 && value < 80;
    });
    recordIotenvInstantList.value = filteredRows;
    total.value = response.total; // 使用后端返回的总数
    loading.value = false;
  });
};

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

const reset = () => {
  form.value = {
    objid: null,
    monitorId: null,
    temperature: null,
    humidity: null,
    illuminance: null,
    noise: null,
    concentration: null,
    vibrationSpeed: null,
    vibrationDisplacement: null,
    vibrationAcceleration: null,
    vibrationTemp: null,
    collectTime: null,
    recodeTime: null
  };
  formRef.value?.resetFields();
};

const handleQuery = () => {
  console.log('查询参数:', daterangeRecordTime.value);
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  daterangeRecordTime.value = [];

  // 重置查询条件，重新获取所有振动设备ID
  queryParams.value.monitorId = null;
  queryParams.value.monitorIds = getAllMonitorIds(monitorInfoOptions.value);
  console.log('重置后振动设备IDs:', queryParams.value.monitorIds);
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.objid);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加物联网数据';
};

const handleUpdate = (row) => {
  reset();
  const objid = row.objid || ids.value;
  getRecordIotenvInstant(objid).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改物联网数据';
  });
};

const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.value.objid != null) {
        updateRecordIotenvInstant(form.value).then((response) => {
          proxy?.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addRecordIotenvInstant(form.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
};

const handleDelete = (row) => {
  const objids = row.objid || ids.value;
  proxy?.$modal
    .confirm('是否确认删除物联网数据编号为"' + objids + '"的数据项？')
    .then(function () {
      return delRecordIotenvInstant(objids);
    })
    .then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

const handleExport = () => {
  // 校验时间范围是否已选择
  if (!daterangeRecordTime.value || daterangeRecordTime.value.length !== 2) {
    proxy?.$modal.msgWarning('请先选择记录时间范围再导出');
    return;
  }
  // 校验是否已选择设备
  if (!queryParams.value.monitorId && (!queryParams.value.monitorIds || queryParams.value.monitorIds.length === 0)) {
    proxy?.$modal.msgWarning('请先在左侧树中选择设备再导出');
    return;
  }
  // 设置时间范围参数
  queryParams.value.params['beginRecordTime'] = daterangeRecordTime.value[0];
  queryParams.value.params['endRecordTime'] = daterangeRecordTime.value[1];
  // 振动页面固定传递monitorTypes=10，确保后端只导出振动相关列
  queryParams.value.params['monitorTypes'] = '10';
  // 传递选中的振动参数，后端只导出该参数列
  queryParams.value.params['vibrationParam'] = selectedVibrationParam.value;

  // 参数中文名映射
  const paramNameMap = {
    vibrationSpeed: '振动速度',
    vibrationDisplacement: '振动位移',
    vibrationAcceleration: '振动加速度',
    vibrationTemp: '振动温度'
  };
  const paramName = paramNameMap[selectedVibrationParam.value] || '振动数据';
  proxy?.download(
    'ems/record/recordIotenvInstant/export',
    {
      ...queryParams.value
    },
    `${paramName}_${daterangeRecordTime.value[0].substring(0, 10)}_${daterangeRecordTime.value[1].substring(0, 10)}.xlsx`
  );
};

const getTreeselect = () => {
  getMonitorInfoTree({
    monitorType: 10
  }).then((response) => {
    monitorInfoOptions.value = response.data;
  });
};

const initVibrationDevices = async () => {
  try {
    const response = await getMonitorInfoTree({
      monitorType: 10
    });
    monitorInfoOptions.value = response.data;

    // 获取所有振动设备的ID用于初始查询
    queryParams.value.monitorIds = getAllMonitorIds(monitorInfoOptions.value);
    console.log('初始化振动设备IDs:', queryParams.value.monitorIds);

    // 设置完设备ID后再执行查询
    getList();
  } catch (error) {
    console.error('获取振动设备树结构失败:', error);
    loading.value = false;
  }
};

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

onMounted(async () => {
  // 设置时间范围
  const nowDate = new Date();
  const today = parseTime(new Date(), '{y}-{m}-{d}');
  const lastDate = new Date();
  lastDate.setDate(nowDate.getDate() - 1);
  const yesterday = parseTime(lastDate, '{y}-{m}-{d}');
  daterangeRecordTime.value[0] = yesterday + ' 08:00:00';
  daterangeRecordTime.value[1] = today + ' 08:00:00';

  // 先获取树结构数据（用于新增功能）
  getTreeMonitorInfo();

  // 获取振动设备树结构并初始化查询
  await initVibrationDevices();
});
</script>
