<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编码" prop="deviceCode">
        <el-input
            v-model="queryParams.deviceCode"
            placeholder="请输入设备编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus"
            @click="handleAdd"
            v-hasPermi="['driver:basic:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['driver:basic:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['driver:basic:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['driver:basic:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" stripe border :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="设备ID" align="center" prop="id" />-->
      <el-table-column label="设备编码" align="center" prop="deviceCode" width="90"/>
      <el-table-column label="设备名称" align="center" prop="deviceName" width="120"/>
      <el-table-column label="设备类型" align="center" prop="deviceType" />
      <el-table-column label="子系统类型" align="center" prop="subsystemType" width="120"/>
      <el-table-column label="所属空间ID" align="center" prop="spaceId" width="100"/>
      <el-table-column label="所属空间名称" align="center" prop="spaceName" width="110"/>
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="型号" align="center" prop="model" width="90"/>
      <el-table-column label="序列号" align="center" prop="serialNumber" width="120"/>
      <el-table-column label="生产日期" align="center" prop="manufactureDate" width="110" sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装日期" align="center" prop="installDate" width="110">
        <template #default="scope">
          <span>{{ parseTime(scope.row.installDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保修期(月)" align="center" prop="warrantyPeriod" width="90"/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_drivce_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否在线" align="center" prop="isOnline">
        <template #default="scope">
          <dict-tag :options="sys_yes_no_tf" :value="scope.row.isOnline"/>
        </template>
      </el-table-column>
      <el-table-column label="设备描述" align="center" prop="description" width="140"/>
      <el-table-column label="操作" min-width="140" fixed="right" width="200px" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['driver:basic:detail']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['driver:basic:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['driver:basic:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <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="1000px" append-to-body>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select
              v-model="form.deviceType"
              placeholder="请选择设备类型"
              filterable
              clearable
          >
            <el-option
                v-for="dict in sys_device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="设备类型" prop="deviceType">
          <el-input v-model="form.deviceType" placeholder="请输入设备类型" />
        </el-form-item>-->
<!--        <el-form-item label="子系统类型" prop="subsystemType">
          <el-input v-model="form.subsystemType" placeholder="请输入子系统类型" />
        </el-form-item>-->
        <el-form-item label="子系统类型" prop="subsystemType">
          <el-select
              v-model="form.subsystemType"
              placeholder="请选择子系统类型"
              filterable
              clearable
          >
            <el-option
                v-for="dict in sys_subsystem_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属空间ID" prop="spaceId">
          <el-input v-model="form.spaceId" placeholder="请输入所属空间ID" />
        </el-form-item>
        <el-form-item label="所属空间名称" prop="spaceName">
          <el-input v-model="form.spaceName" placeholder="请输入所属空间名称" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="序列号" prop="serialNumber">
          <el-input v-model="form.serialNumber" placeholder="请输入序列号" />
        </el-form-item>
        <el-form-item label="生产日期" prop="manufactureDate">
          <el-date-picker clearable
                          v-model="form.manufactureDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装日期" prop="installDate">
          <el-date-picker clearable
                          v-model="form.installDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择安装日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保修期(月)" prop="warrantyPeriod">
          <el-input v-model="form.warrantyPeriod" placeholder="请输入保修期(月)" />
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_drivce_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否在线" prop="isOnline">
         <el-select v-model="form.isOnline" placeholder="请选择">
            <el-option v-for="dict in sys_yes_no_tf" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </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-drawer
        v-model="detailVisible"
        title="设备监控"
        direction="rtl"
        size="80%"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="设备详情" name="detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="设备编码">{{currentDevice.deviceCode}}</el-descriptions-item>
            <el-descriptions-item label="设备名称">{{currentDevice.deviceName}}</el-descriptions-item>
            <el-descriptions-item label="设备类型">
              {{ sys_device_type.find(item => item.value === currentDevice.deviceType)?.label || currentDevice.deviceType }}
            </el-descriptions-item>
            <el-descriptions-item label="子系统类型">
              {{ sys_subsystem_type.find(item => item.value === currentDevice.subsystemType)?.label || currentDevice.subsystemType }}
            </el-descriptions-item>
            <el-descriptions-item label="所属空间">{{currentDevice.spaceName}}</el-descriptions-item>
            <el-descriptions-item label="品牌">{{currentDevice.brand}}</el-descriptions-item>
            <el-descriptions-item label="型号">{{currentDevice.model}}</el-descriptions-item>
            <el-descriptions-item label="序列号">{{currentDevice.serialNumber}}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="设备组态" name="configuration">
          <div class="configuration-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>设备参数配置</span>
                    </div>
                  </template>
                  <el-form label-width="120px">
                    <el-form-item label="运行模式">
                      <el-select v-model="configData.runMode" placeholder="请选择">
                        <el-option label="自动模式" value="auto"></el-option>
                        <el-option label="手动模式" value="manual"></el-option>
                        <el-option label="节能模式" value="energy"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="温度设定">
                      <el-input-number v-model="configData.tempSetting" :min="16" :max="30" :step="0.5"></el-input-number>
                      <span style="margin-left: 10px;">℃</span>
                    </el-form-item>
                    <el-form-item label="湿度设定">
                      <el-slider v-model="configData.humiditySetting" :min="30" :max="80" show-input></el-slider>
                    </el-form-item>
                    <el-form-item label="风速调节">
                      <el-radio-group v-model="configData.fanSpeed">
                        <el-radio label="low">低速</el-radio>
                        <el-radio label="medium">中速</el-radio>
                        <el-radio label="high">高速</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>设备控制点位</span>
                    </div>
                  </template>
                  <el-table :data="controlPoints" style="width: 100%">
                    <el-table-column prop="pointName" label="点位名称" width="120"></el-table-column>
                    <el-table-column prop="pointType" label="类型" width="80"></el-table-column>
                    <el-table-column prop="currentValue" label="当前值"></el-table-column>
                    <el-table-column label="操作" width="100">
                      <template #default="scope">
                        <el-switch v-if="scope.row.pointType === '开关'" v-model="scope.row.status"></el-switch>
                        <el-input-number v-else size="small" v-model="scope.row.currentValue" :min="0" :max="100"></el-input-number>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="设备告警" name="alarm">
          <div class="alarm-container">
            <el-row class="mb8">
              <el-col :span="24">
                <el-button type="primary" size="small" @click="handleAlarmAck">批量确认</el-button>
                <el-button type="warning" size="small" @click="handleAlarmExport">导出告警</el-button>
                <el-tag class="ml10" type="danger">未处理: {{unhandledAlarms}}</el-tag>
                <el-tag class="ml10" type="warning">处理中: {{processingAlarms}}</el-tag>
                <el-tag class="ml10" type="success">已处理: {{handledAlarms}}</el-tag>
              </el-col>
            </el-row>
            <el-table :data="alarmList" @selection-change="handleAlarmSelection" stripe>
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="alarmTime" label="告警时间" width="160" sortable></el-table-column>
              <el-table-column prop="alarmLevel" label="告警级别" width="100">
                <template #default="scope">
                  <el-tag :type="getAlarmLevelType(scope.row.alarmLevel)">
                    {{scope.row.alarmLevel}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="alarmType" label="告警类型" width="120"></el-table-column>
              <el-table-column prop="alarmContent" label="告警内容" show-overflow-tooltip></el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getAlarmStatusType(scope.row.status)">
                    {{scope.row.status}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click="handleAlarmDetail(scope.row)">详情</el-button>
                  <el-button link type="primary" size="small" @click="handleAlarmConfirm(scope.row)">确认</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="控制记录" name="control">
          <div class="control-container">
            <el-form :inline="true" class="mb8">
              <el-form-item label="时间范围">
                <el-date-picker
                    v-model="controlDateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="queryControlRecords">查询</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="controlRecords" stripe>
              <el-table-column prop="controlTime" label="控制时间" width="160"></el-table-column>
              <el-table-column prop="operator" label="操作人" width="100"></el-table-column>
              <el-table-column prop="controlType" label="控制类型" width="120"></el-table-column>
              <el-table-column prop="controlPoint" label="控制点" width="150"></el-table-column>
              <el-table-column prop="beforeValue" label="控制前值" width="100"></el-table-column>
              <el-table-column prop="afterValue" label="控制后值" width="100"></el-table-column>
              <el-table-column prop="result" label="执行结果" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.result === '成功' ? 'success' : 'danger'">
                    {{scope.row.result}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="实时数据" name="realtime">
          <div class="realtime-container">
            <el-row :gutter="20">
              <el-col :span="8" v-for="(item, index) in realtimeData" :key="index">
                <el-card class="mb20">
                  <div class="realtime-item">
                    <div class="item-header">
                      <i :class="item.icon" :style="{color: item.color}"></i>
                      <span class="item-title">{{item.name}}</span>
                    </div>
                    <div class="item-value">
                      <span class="value">{{item.value}}</span>
                      <span class="unit">{{item.unit}}</span>
                    </div>
                    <div class="item-info">
                      <span :class="['status', item.status]">{{item.statusText}}</span>
                      <span class="update-time">更新时间: {{item.updateTime}}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>实时趋势图</span>
                  <el-button-group style="float: right;">
                    <el-button size="small" @click="changeChartPeriod('5m')">5分钟</el-button>
                    <el-button size="small" @click="changeChartPeriod('30m')">30分钟</el-button>
                    <el-button size="small" @click="changeChartPeriod('1h')">1小时</el-button>
                  </el-button-group>
                </div>
              </template>
              <div id="realtimeChart" style="height: 300px;">
                <!-- 这里应该集成图表库如ECharts -->
                <el-empty description="实时趋势图区域"></el-empty>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="历史数据" name="instant">
          <div class="history-container">
            <el-form :inline="true" class="mb8">
              <el-form-item label="数据点">
                <el-select v-model="historyQuery.dataPoint" placeholder="请选择数据点" multiple>
                  <el-option label="温度" value="temperature"></el-option>
                  <el-option label="湿度" value="humidity"></el-option>
                  <el-option label="电压" value="voltage"></el-option>
                  <el-option label="电流" value="current"></el-option>
                  <el-option label="功率" value="power"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                    v-model="historyDateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="queryHistoryData">查询</el-button>
                <el-button type="success" @click="exportHistoryData">导出</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="historyData" stripe max-height="400">
              <el-table-column prop="recordTime" label="记录时间" width="160" sortable></el-table-column>
              <el-table-column prop="temperature" label="温度(℃)" width="100"></el-table-column>
              <el-table-column prop="humidity" label="湿度(%)" width="100"></el-table-column>
              <el-table-column prop="voltage" label="电压(V)" width="100"></el-table-column>
              <el-table-column prop="current" label="电流(A)" width="100"></el-table-column>
              <el-table-column prop="power" label="功率(kW)" width="100"></el-table-column>
              <el-table-column prop="energy" label="能耗(kWh)" width="100"></el-table-column>
            </el-table>
            <div class="history-chart mt20">
              <el-card>
                <template #header>
                  <span>历史趋势分析</span>
                </template>
                <div id="historyChart" style="height: 300px;">
                  <el-empty description="历史趋势图区域"></el-empty>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="自动抄表" name="meter">
          <div class="meter-container">
            <el-row class="mb8">
              <el-col :span="24">
                <el-button type="primary" @click="handleManualRead">手动抄表</el-button>
                <el-button type="success" @click="handleMeterExport">导出数据</el-button>
                <span style="margin-left: 20px;">
                  自动抄表周期:
                  <el-select v-model="meterConfig.period" size="small" style="width: 120px;">
                    <el-option label="每小时" value="hourly"></el-option>
                    <el-option label="每天" value="daily"></el-option>
                    <el-option label="每周" value="weekly"></el-option>
                    <el-option label="每月" value="monthly"></el-option>
                  </el-select>
                </span>
              </el-col>
            </el-row>
            <el-table :data="meterData" stripe>
              <el-table-column prop="meterTime" label="抄表时间" width="160"></el-table-column>
              <el-table-column prop="meterType" label="表计类型" width="100">
                <template #default="scope">
                  <el-tag>{{scope.row.meterType}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="lastReading" label="上次读数" width="120"></el-table-column>
              <el-table-column prop="currentReading" label="本次读数" width="120"></el-table-column>
              <el-table-column prop="usage" label="用量" width="100">
                <template #default="scope">
                  <span style="color: #409EFF;">{{scope.row.usage}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="80"></el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '正常' ? 'success' : 'warning'">
                    {{scope.row.status}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注"></el-table-column>
            </el-table>
            <el-row :gutter="20" class="mt20">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>能耗统计</span>
                  </template>
                  <el-descriptions :column="2">
                    <el-descriptions-item label="本月电量">12,345 kWh</el-descriptions-item>
                    <el-descriptions-item label="本月水量">456 m³</el-descriptions-item>
                    <el-descriptions-item label="同比增长">+5.2%</el-descriptions-item>
                    <el-descriptions-item label="环比增长">+2.1%</el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>费用预估</span>
                  </template>
                  <el-descriptions :column="2">
                    <el-descriptions-item label="本月电费">¥8,641.5</el-descriptions-item>
                    <el-descriptions-item label="本月水费">¥1,824.0</el-descriptions-item>
                    <el-descriptions-item label="预计总费用">¥10,465.5</el-descriptions-item>
                    <el-descriptions-item label="费用预警">正常</el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="事件记录" name="event">
          <div class="event-container">
            <el-form :inline="true" class="mb8">
              <el-form-item label="事件类型">
                <el-select v-model="eventQuery.type" placeholder="全部类型">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="系统事件" value="system"></el-option>
                  <el-option label="操作事件" value="operation"></el-option>
                  <el-option label="告警事件" value="alarm"></el-option>
                  <el-option label="维护事件" value="maintenance"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                    v-model="eventDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="queryEvents">查询</el-button>
              </el-form-item>
            </el-form>
            <el-timeline>
              <el-timeline-item
                  v-for="(event, index) in eventList"
                  :key="index"
                  :timestamp="event.eventTime"
                  placement="top"
                  :type="getEventType(event.type)"
              >
                <el-card>
                  <h4>{{event.title}}</h4>
                  <p>{{event.content}}</p>
                  <p style="margin-top: 10px;">
                    <el-tag size="small" :type="getEventType(event.type)">{{event.type}}</el-tag>
                    <span style="margin-left: 10px; color: #909399;">操作人: {{event.operator}}</span>
                  </p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script setup name="Device">
import {listBasic, getBasic, delBasic, addBasic, updateBasic} from "@/api/device/basic";
import {show} from "@/api/system/notice.js";

const {proxy} = getCurrentInstance();
const {sys_drivce_status,sys_yes_no_tf,sys_device_type,sys_subsystem_type} = proxy.useDict('sys_drivce_status','sys_yes_no_tf','sys_device_type','sys_subsystem_type');

const deviceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const detailVisible = ref(false);
const activeTab = ref('detail'); // 默认选中第一个标签页
const currentDevice = ref({});

function handleDetail(row) {
  currentDevice.value = row;
  activeTab.value = 'detail'; // 每次点击详情时重置为第一个标签页
  detailVisible.value = true;
}

//================
// 新增的响应式数据
const configData = ref({
  runMode: 'auto',
  tempSetting: 25,
  humiditySetting: 60,
  fanSpeed: 'medium'
});

const controlPoints = ref([
  { pointName: '电源开关', pointType: '开关', currentValue: '开启', status: true },
  { pointName: '温度设定', pointType: '模拟量', currentValue: 25 },
  { pointName: '风速控制', pointType: '模拟量', currentValue: 50 },
  { pointName: '新风阀门', pointType: '开关', currentValue: '关闭', status: false }
]);

const alarmList = ref([
  { alarmTime: '2025-06-12 14:30:25', alarmLevel: '严重', alarmType: '温度异常', alarmContent: '设备温度超过设定阈值，当前温度32℃', status: '未处理' },
  { alarmTime: '2025-06-12 13:15:10', alarmLevel: '警告', alarmType: '通信故障', alarmContent: '设备通信中断超过5分钟', status: '处理中' },
  { alarmTime: '2025-06-12 10:20:30', alarmLevel: '一般', alarmType: '维护提醒', alarmContent: '设备运行时间已达到维护周期', status: '已处理' }
]);

const unhandledAlarms = ref(1);
const processingAlarms = ref(1);
const handledAlarms = ref(1);

const controlDateRange = ref([]);
const controlRecords = ref([
  { controlTime: '2025-06-12 14:00:00', operator: '张三', controlType: '手动控制', controlPoint: '温度设定', beforeValue: '26℃', afterValue: '25℃', result: '成功', remark: '用户反馈温度过高' },
  { controlTime: '2025-06-12 12:30:00', operator: '系统', controlType: '自动调节', controlPoint: '风速控制', beforeValue: '30%', afterValue: '50%', result: '成功', remark: '根据负荷自动调节' }
]);

const realtimeData = ref([
  { name: '室内温度', value: 25.3, unit: '℃', icon: 'el-icon-sunny', color: '#E6A23C', status: 'normal', statusText: '正常', updateTime: '14:35:20' },
  { name: '室内湿度', value: 58, unit: '%', icon: 'el-icon-drop', color: '#409EFF', status: 'normal', statusText: '正常', updateTime: '14:35:20' },
  { name: '设备功率', value: 3.85, unit: 'kW', icon: 'el-icon-lightning', color: '#67C23A', status: 'normal', statusText: '正常', updateTime: '14:35:20' },
  { name: '运行电流', value: 16.5, unit: 'A', icon: 'el-icon-battery-full', color: '#F56C6C', status: 'normal', statusText: '正常', updateTime: '14:35:20' },
  { name: '累计能耗', value: 1256.8, unit: 'kWh', icon: 'el-icon-chart-line', color: '#909399', status: 'normal', statusText: '正常', updateTime: '14:35:20' },
  { name: 'CO2浓度', value: 456, unit: 'ppm', icon: 'el-icon-wind-power', color: '#00CED1', status: 'normal', statusText: '正常', updateTime: '14:35:20' }
]);

const historyQuery = ref({
  dataPoint: []
});

const historyDateRange = ref([]);
const historyData = ref([
  { recordTime: '2025-06-12 14:00:00', temperature: 25.2, humidity: 58, voltage: 220, current: 16.4, power: 3.61, energy: 3.61 },
  { recordTime: '2025-06-12 13:00:00', temperature: 25.5, humidity: 57, voltage: 221, current: 16.6, power: 3.67, energy: 3.67 },
  { recordTime: '2025-06-12 12:00:00', temperature: 26.1, humidity: 55, voltage: 219, current: 17.1, power: 3.74, energy: 3.74 }
]);

const meterConfig = ref({
  period: 'daily'
});

const meterData = ref([
  { meterTime: '2025-06-12 00:00:00', meterType: '电表', lastReading: '12000.5', currentReading: '12095.3', usage: '94.8', unit: 'kWh', status: '正常', remark: '自动抄表' },
  { meterTime: '2025-06-11 00:00:00', meterType: '水表', lastReading: '5420.2', currentReading: '5435.7', usage: '15.5', unit: 'm³', status: '正常', remark: '自动抄表' }
]);

const eventQuery = ref({
  type: ''
});

const eventDateRange = ref([]);
const eventList = ref([
  { eventTime: '2025-06-12 14:30:25', type: '告警事件', title: '温度异常告警', content: '空调设备AHU-01温度超限，已自动调节', operator: '系统' },
  { eventTime: '2025-06-12 12:00:00', type: '维护事件', title: '设备维护完成', content: '完成空调过滤网清洗和制冷剂检查', operator: '李四' },
  { eventTime: '2025-06-12 09:15:30', type: '操作事件', title: '设备参数调整', content: '根据天气预报调整温度设定值', operator: '张三' },
  { eventTime: '2025-06-11 18:00:00', type: '系统事件', title: '设备自动启停', content: '根据排程计划，设备自动停机', operator: '系统' }
]);

// 新增的方法
function getAlarmLevelType(level) {
  const typeMap = {
    '严重': 'danger',
    '警告': 'warning',
    '一般': 'info'
  };
  return typeMap[level] || 'info';
}

function getAlarmStatusType(status) {
  const typeMap = {
    '未处理': 'danger',
    '处理中': 'warning',
    '已处理': 'success'
  };
  return typeMap[status] || 'info';
}

function handleAlarmSelection(selection) {
  // 处理告警选择
}

function handleAlarmAck() {
  proxy.$modal.msgSuccess("批量确认成功");
}

function handleAlarmExport() {
  proxy.$modal.msgSuccess("导出告警数据");
}

function handleAlarmDetail(row) {
  proxy.$modal.msgInfo("查看告警详情");
}

function handleAlarmConfirm(row) {
  proxy.$modal.msgSuccess("告警已确认");
}

function queryControlRecords() {
  proxy.$modal.msgSuccess("查询控制记录");
}

function changeChartPeriod(period) {
  proxy.$modal.msgInfo(`切换到${period}视图`);
}

function queryHistoryData() {
  proxy.$modal.msgSuccess("查询历史数据");
}

function exportHistoryData() {
  proxy.$modal.msgSuccess("导出历史数据");
}

function handleManualRead() {
  proxy.$modal.msgSuccess("手动抄表成功");
}

function handleMeterExport() {
  proxy.$modal.msgSuccess("导出抄表数据");
}

function queryEvents() {
  proxy.$modal.msgSuccess("查询事件记录");
}

function getEventType(type) {
  const typeMap = {
    '系统事件': 'primary',
    '操作事件': 'success',
    '告警事件': 'danger',
    '维护事件': 'warning'
  };
  return typeMap[type] || 'info';
}
//================
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceCode: null,
    deviceName: null,
    deviceType: null,
  },
  rules: {
    deviceCode: [
      {required: true, message: "设备编码不能为空", trigger: "blur"}
    ],
    deviceName: [
      {required: true, message: "设备名称不能为空", trigger: "blur"}
    ],
    device_type: [
      {required: true, message: "设备类型不能为空", trigger: "blur"}
    ],
    deviceType: [
      {required: true, message: "设备类型(空调/新风/配电等)不能为空", trigger: "change"}
    ],
    subsystemType: [
      {required: true, message: "子系统类型不能为空", trigger: "change"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: true, message: "更新时间不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询设备基础信息列表 */
function getList() {
  loading.value = true;
  listBasic(queryParams.value).then(response => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deviceCode: null,
    deviceName: null,
    deviceType: null,
    subsystemType: null,
    spaceId: null,
    spaceName: null,
    brand: null,
    model: null,
    serialNumber: null,
    manufactureDate: null,
    installDate: null,
    warrantyPeriod: null,
    status: null,
    isOnline: null,
    description: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("deviceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备基础信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBasic(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备基础信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBasic(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBasic(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备基础信息编号为"' + _ids + '"的数据项？').then(function () {
    return delBasic(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device/basic/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped>
/* 新增的样式 */
.configuration-container .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.realtime-container .realtime-item {
  text-align: center;
  padding: 20px;
}

.realtime-item .item-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.realtime-item .item-header i {
  font-size: 24px;
  margin-right: 10px;
}

.realtime-item .item-title {
  font-size: 16px;
  color: #303133;
}

.realtime-item .item-value {
  margin: 15px 0;
}

.realtime-item .value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
}

.realtime-item .unit {
  font-size: 14px;
  color: #909399;
  margin-left: 5px;
}

.realtime-item .item-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.realtime-item .status.normal {
  color: #67C23A;
}

.ml10 {
  margin-left: 10px;
}

.mt20 {
  margin-top: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.mb20 {
  margin-bottom: 20px;
}
</style>