<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>
            <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:recordIOTInstant: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:recordIOTInstant: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:recordIOTInstant:remove']"
            >删除</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="openExportDialog"
              v-hasPermi="['ems/record:recordIOTInstant: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" stripe border style="width: 100%">
          <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>

          <!-- 根据设备类型显示对应的传感器数据列 -->
          <!-- type=5: 只显示温度 -->
          <el-table-column
            v-if="!selectedNodeType || selectedNodeType === 5 || selectedNodeType === 6"
            label="温度(℃)"
            align="center"
            prop="temperature"
            width="100"
          >
          </el-table-column>

          <!-- type=6: 显示温度和湿度 -->
          <el-table-column v-if="!selectedNodeType || selectedNodeType === 6" label="湿度(%)" align="center" prop="humidity" width="100">
          </el-table-column>

          <!-- 照度列（暂时隐藏，如需要可根据type显示） -->
          <!-- <el-table-column v-if="!selectedNodeType"
                           label="照度(lx)" align="center" prop="illuminance" width="100">
          </el-table-column> -->

          <!-- type=7: 显示噪声 -->
          <el-table-column v-if="!selectedNodeType || selectedNodeType === 7" label="噪声(dB)" align="center" prop="noise" width="100">
          </el-table-column>

          <!-- 记录时间列，确保始终显示并格式化时间 -->
          <el-table-column label="记录时间" align="center" prop="recodeTime" min-width="180" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.recodeTime || '--' }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 未选择设备时显示提示信息 -->
        <div v-if="!hasSelectedDevice" class="no-device-tip">
          <el-empty description="请在左侧树中选择具体设备节点查看数据">
            <i class="el-icon-info" style="font-size: 48px; color: #409eff; margin-bottom: 20px"></i>
          </el-empty>
        </div>
      </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>

    <!-- 导出对话框 -->
    <el-dialog title="导出物联网数据" v-model="exportDialogVisible" width="700px" append-to-body>
      <el-form ref="exportFormRef" :model="exportForm" label-width="100px">
        <!-- 时间范围选择 -->
        <el-form-item label="时间范围" prop="timeRange" required>
          <el-date-picker
            v-model="exportForm.timeRange"
            style="width: 100%"
            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="设备选择">
          <div style="margin-bottom: 10px">
            <el-button type="primary" size="mini" @click="selectAllDevices">全选设备</el-button>
            <el-button type="info" size="mini" @click="clearAllDevices">清空选择</el-button>
            <span style="margin-left: 15px; color: #909399">
              已选择 <span style="color: #409eff; font-weight: bold">{{ selectedDevicesCount }}</span> 个设备
            </span>
          </div>

          <!-- 按能源类型分组显示设备 -->
          <div class="device-select-container">
            <el-checkbox-group v-model="exportForm.selectedDeviceCodes" @change="handleDeviceSelectionChange">
              <!-- 温度设备 (type=5) -->
              <div v-if="deviceGroups.temperature.length > 0" class="device-group">
                <div class="device-group-header">
                  <span class="device-group-title">温度设备</span>
                  <el-button type="text" size="mini" @click="selectGroupDevices('temperature')">
                    {{ isGroupAllSelected('temperature') ? '取消全选' : '全选该类型' }}
                  </el-button>
                </div>
                <el-row :gutter="10">
                  <el-col :span="12" v-for="device in deviceGroups.temperature" :key="device.monitorCode">
                    <el-checkbox :label="device.monitorCode" :disabled="device.isAmmeter === '0'">
                      {{ device.monitorName }}
                      <span v-if="device.isAmmeter === '0'" style="color: #f56c6c; font-size: 12px">(虚拟)</span>
                    </el-checkbox>
                  </el-col>
                </el-row>
              </div>

              <!-- 温湿度设备 (type=6) -->
              <div v-if="deviceGroups.humidity.length > 0" class="device-group">
                <div class="device-group-header">
                  <span class="device-group-title">温湿度设备</span>
                  <el-button type="text" size="mini" @click="selectGroupDevices('humidity')">
                    {{ isGroupAllSelected('humidity') ? '取消全选' : '全选该类型' }}
                  </el-button>
                </div>
                <el-row :gutter="10">
                  <el-col :span="12" v-for="device in deviceGroups.humidity" :key="device.monitorCode">
                    <el-checkbox :label="device.monitorCode" :disabled="device.isAmmeter === '0'">
                      {{ device.monitorName }}
                      <span v-if="device.isAmmeter === '0'" style="color: #f56c6c; font-size: 12px">(虚拟)</span>
                    </el-checkbox>
                  </el-col>
                </el-row>
              </div>

              <!-- 噪声设备 (type=7) -->
              <div v-if="deviceGroups.noise.length > 0" class="device-group">
                <div class="device-group-header">
                  <span class="device-group-title">噪声设备</span>
                  <el-button type="text" size="mini" @click="selectGroupDevices('noise')">
                    {{ isGroupAllSelected('noise') ? '取消全选' : '全选该类型' }}
                  </el-button>
                </div>
                <el-row :gutter="10">
                  <el-col :span="12" v-for="device in deviceGroups.noise" :key="device.monitorCode">
                    <el-checkbox :label="device.monitorCode" :disabled="device.isAmmeter === '0'">
                      {{ device.monitorName }}
                      <span v-if="device.isAmmeter === '0'" style="color: #f56c6c; font-size: 12px">(虚拟)</span>
                    </el-checkbox>
                  </el-col>
                </el-row>
              </div>

              <!-- 其他设备 -->
              <div v-if="deviceGroups.other.length > 0" class="device-group">
                <div class="device-group-header">
                  <span class="device-group-title">其他设备</span>
                  <el-button type="text" size="mini" @click="selectGroupDevices('other')">
                    {{ isGroupAllSelected('other') ? '取消全选' : '全选该类型' }}
                  </el-button>
                </div>
                <el-row :gutter="10">
                  <el-col :span="12" v-for="device in deviceGroups.other" :key="device.monitorCode">
                    <el-checkbox :label="device.monitorCode" :disabled="device.isAmmeter === '0'">
                      {{ device.monitorName }}
                      <span v-if="device.isAmmeter === '0'" style="color: #f56c6c; font-size: 12px">(虚拟)</span>
                    </el-checkbox>
                  </el-col>
                </el-row>
              </div>

              <!-- 空状态处理：当所有设备组都为空时显示 -->
              <div
                v-if="
                  deviceGroups.temperature.length === 0 &&
                  deviceGroups.humidity.length === 0 &&
                  deviceGroups.noise.length === 0 &&
                  deviceGroups.other.length === 0
                "
                class="no-devices-empty"
              >
                <i class="el-icon-info"></i>
                <span>暂无可用设备，请先配置物联网采集设备</span>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmExport">确定导出</el-button>
          <el-button @click="exportDialogVisible = false">取消</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';

defineOptions({
  name: 'RecordIotenvInstant'
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const exportFormRef = ref<ElFormInstance>();
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({
  workUnitName: null,
  //下拉树List
  baseMonitorInfoOptions: [],
  //左侧树结构List
  monitorInfoOptions: [],
  //能原类型信息
  baseMonitorInfoList: [],
  monitorProps: {
    children: 'children',
    label: 'label'
  },
  // 选中节点的类型，用于控制显示字段
  selectedNodeType: null,
  // 记录时间时间范围
  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: {},
  // 导出对话框相关
  exportDialogVisible: false,
  exportForm: {
    timeRange: [],
    selectedDeviceCodes: []
  },
  // 所有设备列表（用于导出选择）
  allDevicesList: [],
  // 设备列表缓存（避免重复请求）
  allDevicesListCache: null,
  cacheTimestamp: 0,
  // 按类型分组的设备（不含振动设备，振动在专用页面处理）
  deviceGroups: {
    temperature: [],
    // 温度设备 (type=5)
    humidity: [],
    // 温湿度设备 (type=6)
    noise: [],
    // 噪声设备 (type=7)
    other: [] // 其他设备 (8,9等，不含振动10)
  }
} as any);

const {
  allDevicesList,
  allDevicesListCache,
  baseMonitorInfoList,
  baseMonitorInfoOptions,
  cacheTimestamp,
  daterangeRecordTime,
  deviceGroups,
  exportDialogVisible,
  exportForm,
  form,
  ids,
  loading,
  monitorInfoOptions,
  monitorProps,
  multiple,
  open,
  queryParams,
  recordIotenvInstantList,
  rules,
  selectedNodeType,
  showSearch,
  single,
  title,
  total,
  workUnitName
} = toRefs(state);

const hasSelectedDevice = computed(() => selectedNodeType.value !== null && selectedNodeType.value !== undefined);

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({
    monitorTypeList: [5, 6, 7, 8, 9]
  }).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.filter((child) => child.code).map((child) => child.code);

    // 父节点的type应该与子节点一致，取第一个有效子节点的type
    const firstValidChild = data.children.find((child) => child.type);
    selectedNodeType.value = firstValidChild ? firstValidChild.type : data.type;
    console.log('点击父节点:', data.label, '节点type:', data.type, '子节点codes:', queryParams.value.monitorIds, '使用type:', selectedNodeType.value);
  } else {
    // 子节点：使用单个设备code
    queryParams.value.monitorId = data.code;
    selectedNodeType.value = data.type;
    console.log('点击子节点:', data.label, 'code:', data.code, 'type:', selectedNodeType.value);
  }
  handleQuery();
};

const getList = () => {
  loading.value = true;

  // 检查是否已选择设备，未选择时不查询数据
  if (!hasSelectedDevice.value) {
    recordIotenvInstantList.value = [];
    total.value = 0;
    loading.value = false;
    return;
  }
  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 || queryParams.value.monitorIds.length === 0)) {
    queryParams.value.monitorIds = getAllMonitorIds(monitorInfoOptions.value);
  }
  listRecordIotenvInstant(queryParams.value).then((response) => {
    recordIotenvInstantList.value = response.rows;
    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();

  // 重置时间范围为默认值（昨天8:00:00到今天8:00:00）
  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 = [yesterday + ' 08:00:00', today + ' 08:00:00'];

  // 重置选中节点类型和查询条件
  selectedNodeType.value = null;
  queryParams.value.monitorId = null;
  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 openExportDialog = () => {
  // 初始化导出表单
  exportForm.value.timeRange = daterangeRecordTime.value ? [...daterangeRecordTime.value] : [];
  exportForm.value.selectedDeviceCodes = [];

  // 加载所有设备列表
  loadAllDevicesForExport();
  exportDialogVisible.value = true;
};

const loadAllDevicesForExport = () => {
  // 缓存5分钟有效（300000毫秒）
  const now = Date.now();
  if (allDevicesListCache.value && now - cacheTimestamp.value < 300000) {
    // 使用缓存数据
    allDevicesList.value = allDevicesListCache.value;
    groupDevicesByType();
    return;
  }

  // 缓存失效，重新加载（不含振动设备type=10）
  listBaseMonitorInfo({
    monitorTypeList: [5, 6, 7, 8, 9]
  }).then((response) => {
    allDevicesList.value = response.data;
    allDevicesListCache.value = response.data;
    cacheTimestamp.value = now;
    groupDevicesByType();
  });
};

const groupDevicesByType = () => {
  // 重置分组
  deviceGroups.value = {
    temperature: [],
    // 温度设备 (type=5)
    humidity: [],
    // 温湿度设备 (type=6)
    noise: [],
    // 噪声设备 (type=7)
    other: [] // 其他设备 (8,9等，不含振动10)
  };
  allDevicesList.value.forEach((device) => {
    // 跳过虚拟设备
    if (device.isAmmeter === '0') return;
    // 跳过振动设备（振动设备在专用页面处理）
    if (device.monitorType === 10) return;
    switch (device.monitorType) {
      case 5:
        deviceGroups.value.temperature.push(device);
        break;
      case 6:
        deviceGroups.value.humidity.push(device);
        break;
      case 7:
        deviceGroups.value.noise.push(device);
        break;
      default:
        deviceGroups.value.other.push(device);
        break;
    }
  });
};

const selectAllDevices = () => {
  // 获取所有非虚拟、非振动设备的设备编号
  const allCodes = allDevicesList.value.filter((device) => device.isAmmeter !== '0' && device.monitorType !== 10).map((device) => device.monitorCode);
  exportForm.value.selectedDeviceCodes = allCodes;
};

const clearAllDevices = () => {
  exportForm.value.selectedDeviceCodes = [];
};

const handleDeviceSelectionChange = () => {
  // 可以在这里添加额外的逻辑，比如更新显示等
};

const isGroupAllSelected = (groupName) => {
  const group = deviceGroups.value[groupName] || [];
  // 获取该组非虚拟设备的编码列表
  const validCodes = group.filter((device) => device.isAmmeter !== '0').map((device) => device.monitorCode);
  if (validCodes.length === 0) return false;
  // 检查是否全部在已选列表中
  return validCodes.every((code) => exportForm.value.selectedDeviceCodes.includes(code));
};

const selectGroupDevices = (groupName) => {
  const group = deviceGroups.value[groupName] || [];
  // 获取该组非虚拟设备的编码列表
  const validCodes = group.filter((device) => device.isAmmeter !== '0').map((device) => device.monitorCode);
  if (isGroupAllSelected(groupName)) {
    // 已全选，则取消该组所有设备
    exportForm.value.selectedDeviceCodes = exportForm.value.selectedDeviceCodes.filter((code) => !validCodes.includes(code));
  } else {
    // 未全选，则添加该组所有设备
    const newCodes = validCodes.filter((code) => !exportForm.value.selectedDeviceCodes.includes(code));
    exportForm.value.selectedDeviceCodes = [...exportForm.value.selectedDeviceCodes, ...newCodes];
  }
};

const confirmExport = () => {
  // 校验时间范围
  if (!exportForm.value.timeRange || exportForm.value.timeRange.length !== 2) {
    proxy?.$modal.msgWarning('请先选择时间范围');
    return;
  }
  // 校验设备选择
  if (exportForm.value.selectedDeviceCodes.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一个设备');
    return;
  }

  // 计算选中的设备类型集合（用于后端动态导出列）
  const selectedMonitorTypes = getSelectedMonitorTypes();

  // 构建导出参数
  const exportParams = {
    params: {
      beginRecordTime: exportForm.value.timeRange[0],
      endRecordTime: exportForm.value.timeRange[1],
      // 传递设备类型，后端根据类型动态选择导出列
      monitorTypes: selectedMonitorTypes.join(',')
    },
    monitorIds: exportForm.value.selectedDeviceCodes,
    monitorId: null // 清空单个设备ID，使用多设备数组
  };

  // 生成文件名（简化格式，移除日期中的横杠以缩短文件名）
  const beginDate = exportForm.value.timeRange[0].substring(0, 10).replace(/-/g, '');
  const endDate = exportForm.value.timeRange[1].substring(0, 10).replace(/-/g, '');
  const deviceCount = exportForm.value.selectedDeviceCodes.length;
  // 文件名包含能源类型信息
  const typeNames = getTypeNamesForFileName(selectedMonitorTypes);
  const fileName = `IOT数据_${typeNames}_${beginDate}_${endDate}_${deviceCount}设备.xlsx`;

  // 执行导出
  proxy?.download('ems/record/recordIotenvInstant/export', exportParams, fileName);
  exportDialogVisible.value = false;
};

const getSelectedMonitorTypes = () => {
  const selectedCodes = exportForm.value.selectedDeviceCodes;
  const types = new Set();

  // 遍历所有设备列表，找出选中设备的类型
  allDevicesList.value.forEach((device) => {
    if (selectedCodes.includes(device.monitorCode) && device.monitorType) {
      types.add(device.monitorType);
    }
  });
  return Array.from(types);
};

const getTypeNamesForFileName = (types) => {
  if (types.length === 0) return '混合';
  if (types.length > 2) return '混合';
  const typeMap = {
    5: '温度',
    6: '温湿度',
    7: '噪声'
  };
  return types.map((t) => typeMap[t] || '其他').join('_');
};

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

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

onMounted(() => {
  //时间范围从昨天8:00:00到今天8:00:00
  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();
  getTreeselect();
  getList();
});
</script>

<style scoped>
.no-device-tip {
  text-align: center;
  padding: 60px 20px;
  background-color: #fafafa;
  border-radius: 8px;
  margin-top: 20px;
}

.no-device-tip .el-empty {
  padding: 0;
}

/* 导出对话框样式 */
.device-select-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.device-group {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.device-group:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.device-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.device-group-title {
  font-weight: bold;
  color: #1f2d3d; /* 提升对比度，便于识别设备类型标题 */
  font-size: 14px;
  padding: 2px 6px;
  border-left: 3px solid #409eff;
  background: #f5f7fa; /* 浅底突出文字 */
  border-radius: 3px;
}

.device-select-container .el-checkbox {
  margin-right: 0;
  margin-bottom: 8px;
  display: block;
}

/* 空状态样式 */
.no-devices-empty {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  font-size: 14px;
}

.no-devices-empty i {
  font-size: 24px;
  margin-right: 8px;
  color: #e6a23c;
}

.device-select-container .el-col {
  margin-bottom: 5px;
}
</style>
