<template>
  <div class="app-container page-shell">
    <section class="page-hero">
      <div class="hero-copy">
        <span class="hero-eyebrow">IOT DEVICE CENTER</span>
        <h2 class="hero-title">计量设备与阈值联动看板</h2>
        <p class="hero-desc">围绕点位档案、安装位置与采集接入做统一可视化整理，让运维在同一页面快速完成查询、维护与阈值联动。</p>
      </div>
      <div class="hero-stats">
        <article v-for="item in overviewStats" :key="item.label" class="stat-card">
          <span class="stat-label">{{ item.label }}</span>
          <strong class="stat-value">{{ item.value }}</strong>
          <span class="stat-hint">{{ item.hint }}</span>
        </article>
      </div>
    </section>

    <section v-show="showSearch" class="panel-shell search-shell">
      <div class="panel-head">
        <div>
          <h3>快速筛选</h3>
          <p>按设备、能源类型、状态和安装位置快速定位目标点位。</p>
        </div>
        <span class="panel-badge">档案检索</span>
      </div>
      <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" label-width="100px" class="query-form">
        <!--      <el-form-item label="计量设备编号" prop="monitorCode">-->
        <!--        <el-input v-model="queryParams.monitorCode" placeholder="请输入计量设备编号" clearable-->
        <!--          @keyup.enter="handleQuery" />-->
        <!--      </el-form-item>-->
        <el-form-item label="计量设备名称" prop="monitorName">
          <el-input v-model="queryParams.monitorName" placeholder="请输入计量设备名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="能源类型" prop="monitorType">
          <el-select v-model="queryParams.monitorType" placeholder="请选择能源类型">
            <el-option v-for="item in energyTypeList" :key="item.energyTypeId" :label="item.energyName" :value="item.energyTypeId"></el-option>
          </el-select>
        </el-form-item>
        <!--      <el-form-item label="计量设备位置" prop="monitorAddr">-->
        <!--        <el-input v-model="queryParams.monitorAddr" placeholder="请输入计量设备位置" clearable-->
        <!--          @keyup.enter="handleQuery" />-->
        <!--      </el-form-item>-->
        <el-form-item label="计量设备状态" prop="monitorStatus">
          <el-select v-model="queryParams.monitorStatus" placeholder="请选择计量设备状态" clearable>
            <el-option v-for="dict in dict.type.monitor_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="点位类型" prop="pointType">
          <el-input v-model="queryParams.pointType" placeholder="请输入点位类型" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="安装位置" prop="locationName">
          <el-input v-model="queryParams.locationName" placeholder="请输入安装位置" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <!--      <el-form-item label="采集设备编号" prop="collectDeviceId">-->
        <!--        <el-input v-model="queryParams.collectDeviceId" placeholder="请输入采集设备编号" clearable-->
        <!--          @keyup.enter="handleQuery" />-->
        <!--      </el-form-item>-->
        <!--      <el-form-item label="是否虚拟" prop="isAmmeter">-->
        <!--        <el-select v-model="queryParams.isAmmeter" placeholder="请选择是否虚拟" clearable>-->
        <!--          <el-option v-for="dict in dict.type.is_ammeter" :key="dict.value" :label="dict.label" :value="dict.value" />-->
        <!--        </el-select>-->
        <!--      </el-form-item>-->
        <el-form-item class="query-actions">
          <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>
    </section>

    <section class="panel-shell table-shell">
      <div class="panel-head">
        <div>
          <h3>设备结构总览</h3>
          <p>树形结构展示设备层级，支持直接维护阈值、档案与挂接关系。</p>
        </div>
        <span class="panel-badge warm">树形维护</span>
      </div>

      <el-row :gutter="10" class="toolbar-row">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ems/base:baseMonitorInfo:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
        </el-col>
        <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
      </el-row>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="baseMonitorInfoList"
        row-key="objId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table"
        border
        stripe
      >
        <!-- 设备名称放第一列，树形展开箭头会自动出现在此列 -->
        <el-table-column label="设备名称" prop="monitorName" min-width="200" show-overflow-tooltip />
        <el-table-column label="设备编号" align="center" prop="monitorCode" min-width="120" show-overflow-tooltip />
        <el-table-column label="能源类型" align="center" prop="energyName" min-width="90" />
        <el-table-column label="点位类型" align="center" prop="pointType" min-width="90" />
        <el-table-column label="单位" align="center" prop="unitName" width="70" />
        <el-table-column label="安装位置" align="center" prop="locationName" min-width="110" show-overflow-tooltip />
        <el-table-column label="采集设备" align="center" prop="collectDeviceName" min-width="110" show-overflow-tooltip />
        <el-table-column label="是否虚拟" align="center" prop="isAmmeter" width="80">
          <template #default="scope">
            <dict-tag :options="dict.type.is_ammeter" :value="scope.row.isAmmeter" />
          </template>
        </el-table-column>
        <el-table-column label="设备状态" align="center" prop="monitorStatus" width="90">
          <template #default="scope">
            <dict-tag :options="dict.type.monitor_status" :value="scope.row.monitorStatus" />
          </template>
        </el-table-column>
        <el-table-column label="报警" align="center" prop="alarmEnable" width="70">
          <template #default="scope">
            <dict-tag :options="dict.type.is_flag" :value="scope.row.alarmEnable" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
          <template #default="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/base:baseMonitorInfo:edit']"
              >修改</el-button
            >
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)" v-hasPermi="['ems/base:baseMonitorInfo:add']"
              >新增</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-setting"
              @click="handleThreshold(scope.row)"
              v-hasPermi="['ems/record:recordAlarmRule:list']"
              v-if="scope.row.isAmmeter !== '0'"
              >阈值</el-button
            >
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:baseMonitorInfo:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </section>

    <!-- 添加或修改计量设备信息对话框 -->
    <el-dialog :title="title" v-model="open" width="960px" append-to-body class="themed-dialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" class="dialog-form">
        <!-- ===== 基本信息 ===== -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="上级节点" prop="parentId">
              <EmsTreeSelect v-model="form.parentId" :options="baseMonitorInfoOptions" :normalizer="normalizer" placeholder="请选择上级节点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="monitorCode">
              <el-input v-model="form.monitorCode" placeholder="请输入计量设备编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="monitorName">
              <el-input v-model="form.monitorName" placeholder="请输入计量设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="能源类型" prop="monitorType">
              <el-select v-model="form.monitorType" placeholder="请选择能源类型" style="width: 100%">
                <el-option v-for="item in energyTypeList" :key="item.energyTypeId" :label="item.energyName" :value="item.energyTypeId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备位置" prop="monitorAddr">
              <el-input v-model="form.monitorAddr" placeholder="请输入计量设备位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="monitorStatus">
              <el-radio-group v-model="form.monitorStatus">
                <el-radio v-for="dict in dict.type.monitor_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- ===== 采集配置 ===== -->
        <el-divider content-position="left">采集配置</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="采集设备" prop="collectDeviceId">
              <el-select v-model="form.collectDeviceId" placeholder="请选择采集设备" style="width: 100%">
                <el-option v-for="item in collectDeviceList" :key="item.collectDeviceId" :label="item.collectDeviceName" :value="item.collectDeviceId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="点位类型" prop="pointType">
              <el-input v-model="form.pointType" placeholder="点位类型" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单位" prop="unitName">
              <el-input v-model="form.unitName" placeholder="单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- ===== 安装信息 ===== -->
        <el-divider content-position="left">安装信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="安装位置" prop="locationName">
              <el-input v-model="form.locationName" placeholder="安装位置" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属柜体" prop="cabinetName">
              <el-input v-model="form.cabinetName" placeholder="所属柜体" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属回路" prop="circuitName">
              <el-input v-model="form.circuitName" placeholder="所属回路" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="相别" prop="phaseNo">
              <el-input v-model="form.phaseNo" placeholder="相别" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备序列号" prop="deviceSn">
              <el-input v-model="form.deviceSn" placeholder="设备序列号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="展示排序" prop="displaySort">
              <el-input-number v-model="form.displaySort" placeholder="排序" :precision="0" :controls="false" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- ===== 传感器参数 ===== -->
        <el-divider content-position="left">传感器参数</el-divider>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="传感器类型" prop="sensorType">
              <el-input v-model="form.sensorType" placeholder="传感器类型" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="测量精度" prop="measurePrecision">
              <el-input-number v-model="form.measurePrecision" placeholder="精度" :precision="4" :controls="false" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否虚拟" prop="isAmmeter">
              <el-radio-group v-model="form.isAmmeter">
                <el-radio v-for="dict in dict.type.is_ammeter" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="量程下限" prop="rangeMin">
              <el-input-number v-model="form.rangeMin" placeholder="下限" :precision="4" :controls="false" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="量程上限" prop="rangeMax">
              <el-input-number v-model="form.rangeMax" placeholder="上限" :precision="4" :controls="false" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- ===== 功能开关 ===== -->
        <el-divider content-position="left">功能开关</el-divider>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="启用报警" prop="alarmEnable">
              <el-radio-group v-model="form.alarmEnable">
                <el-radio v-for="dict in dict.type.is_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用曲线" prop="curveEnable">
              <el-radio-group v-model="form.curveEnable">
                <el-radio v-for="dict in dict.type.is_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </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="thresholdTitle" v-model="thresholdOpen" width="1200px" append-to-body class="themed-dialog threshold-dialog">
      <div class="threshold-container">
        <!-- 设备信息展示 -->
        <el-card class="device-info-card" shadow="never">
          <template v-slot:header>
            <div class="clearfix">
              <span>设备信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">设备编号：</span>
                <span class="value">{{ currentDevice.monitorCode }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">设备名称：</span>
                <span class="value">{{ currentDevice.monitorName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">能源类型：</span>
                <span class="value">{{ getMonitorTypeLabel(currentDevice.monitorType) }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 阈值规则管理 -->
        <el-card class="threshold-rules-card" shadow="never">
          <template v-slot:header>
            <div class="clearfix">
              <span>阈值规则管理</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="handleAddThreshold">
                <i class="el-icon-plus"></i> 新增规则
              </el-button>
            </div>
          </template>

          <!-- 规则列表 -->
          <el-table v-loading="thresholdLoading" :data="thresholdRuleList" size="small">
            <el-table-column label="规则名称" align="center" prop="ruleName" />
            <el-table-column label="触发规则" align="center" prop="triggerRule">
              <template #default="scope">
                <dict-tag :options="dict.type.trigger_rule" :value="scope.row.triggerRule" />
              </template>
            </el-table-column>
            <el-table-column label="监测字段" align="center" prop="monitorField">
              <template #default="scope">
                <dict-tag :options="dict.type.monitor_field" :value="scope.row.monitorField" />
              </template>
            </el-table-column>
            <el-table-column label="告警上限" align="center" prop="alarmUpper" />
            <el-table-column label="告警下限" align="center" prop="alarmLower" />
            <el-table-column label="恢复上限" align="center" prop="recoverUpper" />
            <el-table-column label="恢复下限" align="center" prop="recoverLower" />
            <el-table-column label="回差" align="center" prop="hysteresis" />
            <el-table-column label="持续秒数" align="center" prop="durationSec" />
            <el-table-column label="告警级别" align="center" prop="alarmLevel" />
            <el-table-column label="启用状态" align="center" prop="isEnable">
              <template #default="scope">
                <dict-tag :options="dict.type.is_flag" :value="scope.row.isEnable" />
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="cause" show-overflow-tooltip />
            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditThreshold(scope.row)"> 修改 </el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteThreshold(scope.row)"> 删除 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="thresholdOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 阈值规则编辑对话框 -->
    <el-dialog :title="thresholdFormTitle" v-model="thresholdFormOpen" width="500px" append-to-body class="themed-dialog">
      <div class="dialog-tip soft">
        <span class="tip-dot"></span>
        阈值规则与点位技术字段自动联动，页面只暴露运维真正需要维护的业务项，减少误配概率。
      </div>
      <el-form ref="thresholdFormRef" :model="thresholdForm" :rules="thresholdRules" label-width="120px" class="dialog-form">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="thresholdForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="触发规则" prop="triggerRule">
          <el-radio-group v-model="thresholdForm.triggerRule">
            <el-radio v-for="dict in dict.type.trigger_rule" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="监测字段" prop="monitorField">
          <el-select v-model="thresholdForm.monitorField" placeholder="请选择监测字段">
            <el-option v-for="dict in dict.type.monitor_field" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="告警上限" prop="alarmUpper">
          <el-input-number v-model="thresholdForm.alarmUpper" placeholder="请输入告警上限" :precision="4" />
        </el-form-item>
        <el-form-item label="告警下限" prop="alarmLower">
          <el-input-number v-model="thresholdForm.alarmLower" placeholder="请输入告警下限" :precision="4" />
        </el-form-item>
        <el-form-item label="恢复上限" prop="recoverUpper">
          <el-input-number v-model="thresholdForm.recoverUpper" placeholder="请输入恢复上限" :precision="4" />
        </el-form-item>
        <el-form-item label="恢复下限" prop="recoverLower">
          <el-input-number v-model="thresholdForm.recoverLower" placeholder="请输入恢复下限" :precision="4" />
        </el-form-item>
        <el-form-item label="回差" prop="hysteresis">
          <el-input-number v-model="thresholdForm.hysteresis" placeholder="请输入回差" :precision="4" />
        </el-form-item>
        <el-form-item label="持续秒数" prop="durationSec">
          <el-input-number v-model="thresholdForm.durationSec" placeholder="请输入持续秒数" :precision="0" />
        </el-form-item>
        <el-form-item label="告警级别" prop="alarmLevel">
          <el-input v-model="thresholdForm.alarmLevel" placeholder="请输入告警级别" />
        </el-form-item>
        <el-form-item label="启用状态" prop="isEnable">
          <el-radio-group v-model="thresholdForm.isEnable">
            <el-radio v-for="dict in dict.type.is_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="cause">
          <el-input v-model="thresholdForm.cause" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitThresholdForm">确 定</el-button>
          <el-button @click="thresholdFormOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useDict } from '@/utils/dict';
import {
  listBaseMonitorInfo,
  getBaseMonitorInfo,
  delBaseMonitorInfo,
  addBaseMonitorInfo,
  updateBaseMonitorInfo
} from '@/api/ems/base/baseMonitorInfo';
import {
  listRecordAlarmRule,
  getRecordAlarmRule,
  delRecordAlarmRule,
  addRecordAlarmRule,
  updateRecordAlarmRule
} from '@/api/ems/record/recordAlarmRule';
import EmsTreeSelect from '@/views/ems/components/EmsTreeSelect.vue';
import { getBaseEnergyTypeList } from '@/api/ems/base/baseEnergyType';
import { getCollectDeviceInfo } from '@/api/ems/base/baseCollectDeviceInfo';
import { handleTree } from '@/utils/ruoyi';

defineOptions({
  name: 'BaseMonitorInfo',
  dicts: ['is_ammeter', 'monitor_status', 'monitor_type', 'trigger_rule', 'monitor_field', 'is_flag']
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dict = reactive({
  type: useDict('is_ammeter', 'monitor_status', 'monitor_type', 'trigger_rule', 'monitor_field', 'is_flag')
});

const formRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const thresholdFormRef = ref<ElFormInstance>();

// 这里统一通过工厂函数重建表单，避免弹窗在新增/编辑切换时残留上一条业务数据。
const createFormData = () => ({
  objId: null,
  parentId: null,
  monitorCode: null,
  monitorName: null,
  energyType: null,
  monitorAddr: null,
  monitorType: null,
  monitorStatus: null,
  collectDeviceId: null,
  ancestors: null,
  grade: null,
  meterTypeId: null,
  correctValue: null,
  pt: null,
  ct: null,
  isAmmeter: null,
  isKeyMonitor: null,
  isCircuit: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  publicShareType: null,
  monitorHierarchy: null,
  tenantId: null,
  pointType: null,
  metricCode: null,
  unitName: null,
  collectChannel: null,
  registerAddress: null,
  registerType: null,
  dataType: null,
  byteOrder: null,
  bitOffset: null,
  nodeId: null,
  deviceSn: null,
  locationCode: null,
  locationName: null,
  cabinetName: null,
  circuitName: null,
  phaseNo: null,
  sensorType: null,
  measurePrecision: null,
  rangeMin: null,
  rangeMax: null,
  alarmEnable: null,
  curveEnable: null,
  displaySort: null
});

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  // 遮罩层
  loading: true,
  // 显示搜索条件
  showSearch: true,
  // 计量设备信息表格数据
  baseMonitorInfoList: [],
  // 计量设备信息树选项
  baseMonitorInfoOptions: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 是否展开，默认全部展开
  isExpandAll: true,
  // 重新渲染表格状态
  refreshTable: true,
  // 查询对象补齐最新字段，页面只展示业务字段，技术字段继续留在内部承载和导出参数中。
  queryParams: {
    parentId: null,
    monitorCode: null,
    monitorName: null,
    energyType: null,
    monitorAddr: null,
    monitorType: null,
    monitorStatus: null,
    collectDeviceId: null,
    ancestors: null,
    grade: null,
    meterTypeId: null,
    correctValue: null,
    pt: null,
    ct: null,
    isAmmeter: null,
    isKeyMonitor: null,
    isCircuit: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    publicShareType: null,
    monitorHierarchy: null,
    tenantId: null,
    pointType: null,
    metricCode: null,
    unitName: null,
    collectChannel: null,
    registerAddress: null,
    registerType: null,
    dataType: null,
    byteOrder: null,
    bitOffset: null,
    nodeId: null,
    deviceSn: null,
    locationCode: null,
    locationName: null,
    cabinetName: null,
    circuitName: null,
    phaseNo: null,
    sensorType: null,
    measurePrecision: null,
    rangeMin: null,
    rangeMax: null,
    alarmEnable: null,
    curveEnable: null,
    displaySort: null
  },
  // 表单参数
  form: createFormData(),
  // 表单校验
  rules: {
    // objId: [
    //   { required: true, message: "自增标识不能为空", trigger: "blur" }
    // ],
    monitorCode: [
      {
        required: true,
        message: '计量设备编号不能为空',
        trigger: 'blur'
      }
    ],
    monitorType: [
      {
        required: true,
        message: '能源类型不能为空',
        trigger: 'blur'
      }
    ],
    monitorName: [
      {
        required: true,
        message: '计量设备名称不能为空',
        trigger: 'blur'
      }
    ],
    isAmmeter: [
      {
        required: true,
        message: '是否为虚拟能为空',
        trigger: 'blur'
      }
    ]
  },
  //能源类型选项
  energyTypeList: [],
  // 采集设备下拉只展示名称，技术 ID 仍保留在提交参数中。
  collectDeviceList: [],
  // 阈值管理相关数据
  thresholdOpen: false,
  thresholdTitle: '',
  thresholdLoading: false,
  thresholdRuleList: [],
  currentDevice: {},
  // 阈值规则表单相关
  thresholdFormOpen: false,
  thresholdFormTitle: '',
  thresholdForm: {},
  thresholdRules: {
    ruleName: [
      {
        required: true,
        message: '规则名称不能为空',
        trigger: 'blur'
      }
    ],
    triggerRule: [
      {
        required: true,
        message: '触发规则不能为空',
        trigger: 'change'
      }
    ],
    alarmUpper: [
      {
        required: true,
        message: '告警上限不能为空',
        trigger: 'blur'
      }
    ]
  }
} as any);

const {
  baseMonitorInfoList,
  baseMonitorInfoOptions,
  currentDevice,
  energyTypeList,
  collectDeviceList,
  form,
  isExpandAll,
  loading,
  open,
  queryParams,
  refreshTable,
  rules,
  showSearch,
  thresholdForm,
  thresholdFormOpen,
  thresholdFormTitle,
  thresholdLoading,
  thresholdOpen,
  thresholdRuleList,
  thresholdRules,
  thresholdTitle,
  title
} = toRefs(state);

const flattenDeviceTree = (nodes = []) => {
  return nodes.reduce((acc, node) => {
    acc.push(node);
    if (node.children?.length) {
      acc.push(...flattenDeviceTree(node.children));
    }
    return acc;
  }, []);
};

const flatDeviceList = computed(() => flattenDeviceTree(baseMonitorInfoList.value));

// 这里用展示型统计卡强化运维感知，不参与任何接口入参与业务判断，确保只提升视觉层体验。
const overviewStats = computed(() => {
  const devices = flatDeviceList.value;
  const total = devices.length;
  const withCollector = devices.filter((item) => item.collectDeviceId || item.collectDeviceName).length;
  const withLocation = devices.filter((item) => item.locationName).length;
  const withSensor = devices.filter((item) => item.sensorType).length;

  return [
    {
      label: '设备总量',
      value: total,
      hint: '当前树形档案节点'
    },
    {
      label: '已挂接采集',
      value: withCollector,
      hint: '已关联采集设备'
    },
    {
      label: '位置已维护',
      value: withLocation,
      hint: '安装位置信息完整'
    },
    {
      label: '传感已标注',
      value: withSensor,
      hint: '便于运维识别类型'
    }
  ];
});

const getMonitorTypeLabel = (monitorType) => {
  if (!monitorType || !dict.type.monitor_type) {
    return '未设置';
  }
  const typeItem = dict.type.monitor_type.find((e) => e.value == monitorType);
  return typeItem ? typeItem.label : '未知类型';
};

const getList = () => {
  loading.value = true;
  listBaseMonitorInfo(queryParams.value).then((response) => {
    const source = response.rows ?? response.data ?? [];
    baseMonitorInfoList.value = handleTree(source, 'objId', 'parentId');
    loading.value = false;
  });
};

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

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

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

const reset = () => {
  // 统一重建默认对象，避免详情回填后隐藏技术字段在再次新增时串到下一条记录。
  form.value = createFormData();
  formRef.value?.resetFields();
};

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

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleAdd = (row) => {
  reset();
  getTreeselect();
  if (row != null && row.objId) {
    form.value.parentId = row.objId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = '添加计量设备信息';
};

const toggleExpandAll = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};

const handleUpdate = (row) => {
  reset();
  getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getBaseMonitorInfo(row.objId).then((response) => {
    form.value = {
      ...createFormData(),
      ...(response.data ?? {})
    };
    open.value = true;
    title.value = '修改计量设备信息';
  });
};

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

const handleDelete = (row) => {
  proxy?.$modal
    .confirm('是否确认删除计量设备信息编号为"' + row.objId + '"的数据项？')
    .then(function () {
      return delBaseMonitorInfo(row.objId);
    })
    .then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

const handleThreshold = (row) => {
  currentDevice.value = {
    ...row
  };
  thresholdTitle.value = `设备阈值管理 - ${row.monitorName}`;
  thresholdOpen.value = true;
  getThresholdRuleList();
};

const getThresholdRuleList = () => {
  thresholdLoading.value = true;
  const queryParams = {
    monitorId: currentDevice.value.monitorCode,
    pageNum: 1,
    pageSize: 1000
  };
  listRecordAlarmRule(queryParams)
    .then((response) => {
      thresholdRuleList.value = response.rows || [];
      thresholdLoading.value = false;
    })
    .catch(() => {
      thresholdLoading.value = false;
    });
};

const handleAddThreshold = () => {
  resetThresholdForm();
  thresholdForm.value.monitorId = currentDevice.value.monitorCode;
  // 规则新增时同步保留隐藏技术字段，避免页面不展示后被前端对象重置掉。
  thresholdForm.value.tenantId = currentDevice.value.tenantId ?? null;
  thresholdFormTitle.value = '新增阈值规则';
  thresholdFormOpen.value = true;
};

const handleEditThreshold = (row) => {
  resetThresholdForm();
  getRecordAlarmRule(row.objId).then((response) => {
    thresholdForm.value = {
      ...response.data
    };
    thresholdFormTitle.value = '修改阈值规则';
    thresholdFormOpen.value = true;
  });
};

const handleDeleteThreshold = (row) => {
  proxy?.$modal
    .confirm(`是否确认删除规则"${row.ruleName}"？`)
    .then(() => {
      return delRecordAlarmRule(row.objId);
    })
    .then(() => {
      getThresholdRuleList();
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

const submitThresholdForm = () => {
  thresholdFormRef.value?.validate((valid) => {
    if (valid) {
      // 确保设备编号正确设置
      thresholdForm.value.monitorId = currentDevice.value.monitorCode;
      // 这些字段属于规则和点位之间的技术透传字段，页面不展示但提交时必须带齐。
      thresholdForm.value.tenantId = currentDevice.value.tenantId ?? thresholdForm.value.tenantId;
      thresholdForm.value.metricCode = currentDevice.value.metricCode ?? thresholdForm.value.metricCode;
      thresholdForm.value.energyType = currentDevice.value.monitorType ?? thresholdForm.value.energyType;
      if (thresholdForm.value.triggerRule === 0 && thresholdForm.value.alarmUpper != null) {
        thresholdForm.value.triggerValue = thresholdForm.value.alarmUpper;
      }
      if (thresholdForm.value.triggerRule === 1 && thresholdForm.value.alarmLower != null) {
        thresholdForm.value.triggerValue = thresholdForm.value.alarmLower;
      }
      thresholdForm.value.isEnable = thresholdForm.value.isEnable ?? '0';
      if (thresholdForm.value.objId != null) {
        updateRecordAlarmRule(thresholdForm.value).then((response) => {
          proxy?.$modal.msgSuccess('修改成功');
          thresholdFormOpen.value = false;
          getThresholdRuleList();
        });
      } else {
        addRecordAlarmRule(thresholdForm.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          thresholdFormOpen.value = false;
          getThresholdRuleList();
        });
      }
    }
  });
};

const resetThresholdForm = () => {
  thresholdForm.value = {
    objId: null,
    ruleId: null,
    ruleName: null,
    monitorId: null,
    collectTime: null,
    energyType: null,
    triggerRule: null,
    monitorField: null,
    timeRange: null,
    triggerValue: null,
    notifyUser: null,
    cause: null,
    tenantId: null,
    metricCode: null,
    alarmUpper: null,
    alarmLower: null,
    recoverUpper: null,
    recoverLower: null,
    hysteresis: null,
    durationSec: null,
    alarmLevel: null,
    // 阈值初始化时不再前置通知组，避免配置页继续透出扩展通知能力。
    // notifyGroupId: null,
    isEnable: '0'
  };
  nextTick(() => {
    if (thresholdFormRef.value) {
      thresholdFormRef.value.clearValidate();
    }
  });
};

onMounted(() => {
  getBaseEnergyTypeList({}).then((response) => {
    energyTypeList.value = response.data;
  });
  getCollectDeviceInfo({}).then((response) => {
    collectDeviceList.value = response.rows || response.data || [];
  });
  getList();
});
</script>

<style scoped lang="scss">
.page-shell {
  min-height: 100%;
  padding: 20px;
  background:
    radial-gradient(circle at top left, rgba(14, 165, 233, 0.18), transparent 32%),
    radial-gradient(circle at top right, rgba(34, 197, 94, 0.14), transparent 28%), linear-gradient(180deg, #f3f8ff 0%, #eef4f7 48%, #f7f9fc 100%);
}

.page-hero {
  display: grid;
  grid-template-columns: minmax(0, 1.35fr) minmax(320px, 1fr);
  gap: 18px;
  margin-bottom: 18px;
  padding: 28px 30px;
  border-radius: 28px;
  background: linear-gradient(135deg, rgba(7, 63, 86, 0.96) 0%, rgba(16, 106, 125, 0.92) 52%, rgba(40, 166, 146, 0.9) 100%);
  box-shadow: 0 24px 50px rgba(17, 75, 95, 0.18);
  color: #fff;
  position: relative;
  overflow: hidden;
}

.page-hero::after {
  content: '';
  position: absolute;
  inset: auto -100px -120px auto;
  width: 260px;
  height: 260px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.08);
  filter: blur(4px);
}

.hero-copy {
  position: relative;
  z-index: 1;
}

.hero-eyebrow {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.12);
  font-size: 12px;
  letter-spacing: 0.18em;
}

.hero-title {
  margin: 18px 0 12px;
  font-size: 30px;
  line-height: 1.2;
  font-weight: 700;
}

.hero-desc {
  max-width: 700px;
  margin: 0;
  color: rgba(255, 255, 255, 0.82);
  line-height: 1.75;
}

.hero-stats {
  position: relative;
  z-index: 1;
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 14px;
}

.stat-card {
  padding: 18px;
  border-radius: 22px;
  background: rgba(255, 255, 255, 0.12);
  border: 1px solid rgba(255, 255, 255, 0.16);
  backdrop-filter: blur(10px);
}

.stat-label,
.stat-hint {
  display: block;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
}

.stat-value {
  display: block;
  margin: 10px 0 8px;
  font-size: 30px;
  line-height: 1;
  font-weight: 700;
}

.stat-hint {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

.panel-shell {
  margin-bottom: 18px;
  padding: 20px 22px;
  border: 1px solid rgba(199, 211, 223, 0.55);
  border-radius: 24px;
  background: rgba(255, 255, 255, 0.84);
  box-shadow: 0 18px 40px rgba(42, 63, 95, 0.08);
  backdrop-filter: blur(14px);
}

.panel-head {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  align-items: center;
  margin-bottom: 18px;
}

.panel-head h3 {
  margin: 0 0 6px;
  color: #163047;
  font-size: 20px;
}

.panel-head p {
  margin: 0;
  color: #6b7a90;
  line-height: 1.6;
}

.panel-badge {
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
  padding: 8px 14px;
  border-radius: 999px;
  background: linear-gradient(135deg, #dbeafe, #ecfeff);
  color: #0f5f8d;
  font-size: 12px;
  font-weight: 600;
}

.panel-badge.warm {
  background: linear-gradient(135deg, #fef3c7, #ffedd5);
  color: #a16207;
}

.query-form {
  padding: 18px;
  border-radius: 20px;
  background: linear-gradient(180deg, rgba(248, 251, 255, 0.96) 0%, rgba(255, 255, 255, 0.92) 100%);
}

.query-actions {
  :deep(.el-form-item__content) {
    gap: 10px;
  }
}

.toolbar-row {
  margin-bottom: 14px;
  padding: 14px 16px;
  border-radius: 18px;
  background: linear-gradient(90deg, rgba(16, 185, 129, 0.08), rgba(59, 130, 246, 0.08));
}

.data-table {
  :deep(.el-table) {
    --el-table-border-color: rgba(208, 219, 229, 0.7);
  }

  :deep(.el-table__header-wrapper th) {
    background: #f4f9ff;
    color: #17324a;
    font-weight: 700;
  }

  :deep(.el-table__row td) {
    transition: background-color 0.2s ease;
  }

  :deep(.el-table__body tr:hover > td) {
    background: rgba(37, 99, 235, 0.06) !important;
  }
}

.dialog-tip {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 18px;
  padding: 12px 14px;
  border-radius: 16px;
  background: linear-gradient(90deg, rgba(14, 165, 233, 0.1), rgba(16, 185, 129, 0.08));
  color: #28506c;
  line-height: 1.65;
}

.dialog-tip.soft {
  background: linear-gradient(90deg, rgba(59, 130, 246, 0.08), rgba(244, 114, 182, 0.08));
}

.tip-dot {
  width: 10px;
  height: 10px;
  flex-shrink: 0;
  border-radius: 50%;
  background: linear-gradient(135deg, #0ea5e9, #22c55e);
  box-shadow: 0 0 0 5px rgba(14, 165, 233, 0.12);
}

.dialog-form {
  padding: 18px;
  border-radius: 18px;
  background: #f9fbff;
}

.threshold-container {
  padding: 0;
}

.device-info-card,
.threshold-rules-card {
  border: none;
  border-radius: 22px;
  background: linear-gradient(180deg, #ffffff 0%, #f7fbff 100%);
  box-shadow: 0 16px 30px rgba(42, 63, 95, 0.08);
}

.device-info-card {
  margin-bottom: 20px;
}

.device-info-card :deep(.el-card__header),
.threshold-rules-card :deep(.el-card__header) {
  padding: 18px 20px;
  border-bottom: 1px solid rgba(208, 219, 229, 0.75);
}

.device-info-card :deep(.el-card__body),
.threshold-rules-card :deep(.el-card__body) {
  padding: 18px 20px;
}

.info-item {
  margin-bottom: 10px;
  padding: 14px 16px;
  border-radius: 16px;
  background: linear-gradient(135deg, #f7fbff, #f2f7f6);
}

.info-item .label {
  font-weight: 700;
  color: #66758d;
}

.info-item .value {
  color: #17324a;
  margin-left: 5px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

:deep(.themed-dialog .el-dialog) {
  border-radius: 26px;
  overflow: hidden;
  box-shadow: 0 28px 60px rgba(15, 23, 42, 0.2);
}

:deep(.themed-dialog .el-dialog__header) {
  padding: 22px 24px 14px;
  background: linear-gradient(135deg, rgba(11, 94, 129, 0.96), rgba(26, 142, 126, 0.92));
}

:deep(.themed-dialog .el-dialog__title),
:deep(.themed-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
}

:deep(.themed-dialog .el-dialog__body) {
  padding: 22px 24px;
  background: linear-gradient(180deg, #f8fbff 0%, #ffffff 100%);
}

:deep(.themed-dialog .el-dialog__footer) {
  padding: 0 24px 24px;
  background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
}

@media (max-width: 992px) {
  .page-hero {
    grid-template-columns: 1fr;
  }

  .hero-stats {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 768px) {
  .page-shell {
    padding: 12px;
  }

  .page-hero,
  .panel-shell {
    padding: 18px;
    border-radius: 20px;
  }

  .panel-head {
    flex-direction: column;
    align-items: flex-start;
  }

  .hero-stats {
    grid-template-columns: 1fr;
  }
}
</style>
