<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="areaName" placeholder="请输入区域名称" clearable size="small" prefix-icon="el-icon-search"
                    style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container" style="height: 100vh; overflow: hidden; position: relative;">
          <el-tree :data="treeAreaOptions" :props="defaultProps" :expand-on-click-node="false"
                   :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                   @node-click="handleNodeClick" style="height: calc(100vh - 50px); overflow-y: auto;"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-tabs v-model="queryParams.deviceCategory" @tab-click="deviceCategoryChange">
          <el-tab-pane label="产能设备" name="E"></el-tab-pane>
          <el-tab-pane label="储能设备" name="C"></el-tab-pane>
          <el-tab-pane label="输配设备" name="W"></el-tab-pane>
          <el-tab-pane label="用能设备" name="Z"></el-tab-pane>
        </el-tabs>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px"
        >
          <el-form-item label="设备分类" prop="deviceSubCategory">
            <el-select v-model="queryParams.deviceSubCategory">
              <el-option v-for="item in subCategoryOptions" placeholder="设备分类" :label="item.name" :value="item.code"
                         :key="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="归属设施" prop="refFacs">
            <el-select v-model="queryParams.refFacs">
              <el-option v-for="item in facsOptions" :label="item.facsName" :value="item.facsCode"
                         :key="item.facsCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="归属系统" prop="subsystemCode">
            <el-select v-model="queryParams.subsystemCode">
              <el-option v-for="item in subsystemOptions" :label="item.systemName" :value="item.systemCode"
                         :key="item.systemCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="deviceList">
          <el-table-column label="设备名称" align="left" prop="deviceName"/>
          <el-table-column label="归属区域" align="left" prop="areaPath" width="280px"/>
          <el-table-column label="设备分类" align="center" prop="deviceCategoryName"/>
          <el-table-column label="归属设施" align="center" prop="refFacsName"/>
          <el-table-column label="归属系统" align="center" prop="subsystemName"/>
          <el-table-column label="设备状态" align="center" prop="deviceStatus">
            <template slot-scope="scope">
              <span :style="{
                padding: '6px 12px',
                borderRadius: '4px',
                display: 'inline-block',
                textAlign: 'center',
                cursor: 'pointer',
                color: getDeviceStatusTextColor(scope.row.deviceStatus),
                backgroundColor: getDeviceStatusBgColor(scope.row.deviceStatus),
                minWidth: '70px',
                height: '35px',
                textAlign: 'center'
              }"
              >
                {{ getDeviceStatusText(scope.row.deviceStatus) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-info" @click="handleDetail(scope.row)">详情</el-button>
              <!-- 下拉菜单 -->
              <el-dropdown trigger="click">
                <el-button type="text" size="mini" @click="loadAbilities(scope.row)">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <template v-if="abilityDevice && abilityDevice.length > 0">
                    <el-dropdown-item
                      v-for="ability in abilityDevice"
                      :key="ability.abilityKey"
                      @click.native="handleDeviceOperate(ability, scope.row)"
                    >
                      {{ ability.abilityName }}
                    </el-dropdown-item>
                  </template>
                  <el-dropdown-item v-else>
                    无
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList"
        />

        <!-- 调用日志详情弹窗 -->
        <el-dialog :visible.sync="callLogDetailDialog" title="调用日志详情" width="50%">
          <div v-if="callLogDetailData">
            <p><strong>对象代码：</strong>{{ callLogDetailData.objCode }}</p>
            <p><strong>对象类型：</strong>{{ formatObjType(callLogDetailData.objType) }}</p>
            <p><strong>模型代码：</strong>{{ callLogDetailData.modelCode }}</p>
            <p><strong>能力标识：</strong>{{ callLogDetailData.abilityKey }}</p>
            <p><strong>调用时间：</strong>{{ callLogDetailData.callTime }}</p>
            <p><strong>响应时间：</strong>{{ callLogDetailData.resTime }}</p>
            <p><strong>调用结果：</strong>{{ formatCallStatus(callLogDetailData.callStatus) }}</p>
            <p><strong>调用载体：</strong></p>
            <pre style="white-space: pre-wrap; background-color: #f5f5f5; padding: 10px; border-radius: 4px;"
            >{{ callLogDetailData.callPayload }}</pre>
            <p><strong>响应载体：</strong></p>
            <pre style="white-space: pre-wrap; background-color: #f5f5f5; padding: 10px; border-radius: 4px;"
            >{{ callLogDetailData.resPayload }}</pre>
          </div>
        </el-dialog>

        <!-- 设备日志详情弹窗 -->
        <el-dialog :visible.sync="reportDetailDialog" title="设备日志详情" width="50%">
          <div v-if="reportDetailData">
            <p><strong>对象代码：</strong>{{ reportDetailData.objCode }}</p>
            <p><strong>对象类型：</strong>{{ formatObjType(reportDetailData.objType) }}</p>
            <p><strong>消息描述：</strong>{{ reportDetailData.msgDesc }}</p>
            <p><strong>上报时间：</strong>{{ reportDetailData.reportTime }}</p>
            <p><strong>上报载体：</strong></p>
            <pre style="white-space: pre-wrap; background-color: #f5f5f5; padding: 10px; border-radius: 4px;"
            >{{ reportDetailData.reportPayload }}</pre>
          </div>
        </el-dialog>

        <!-- 事件日志详情弹框 -->
        <el-dialog :visible.sync="eventLogDetailDialog" title="事件日志详情" width="50%">
          <div v-if="eventLogDetailData">
            <p><strong>对象编号：</strong>{{ eventLogDetailData.objCode }}</p>
            <p><strong>对象名称：</strong>{{ eventLogDetailData.objName }}</p>
            <p><strong>事件名称：</strong>{{ eventLogDetailData.eventName }}</p>
            <p><strong>事件时间：</strong>{{ eventLogDetailData.eventTime }}</p>
            <p><strong>事件描述：</strong>{{ eventLogDetailData.eventDetail }}</p>
          </div>
        </el-dialog>

       <!--详情 -->
        <el-dialog :visible.sync="open" title="设备状态详情" custom-class="detail-dialog">
          <div v-if="curRow">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="设备基本信息" name="basic"></el-tab-pane>
              <el-tab-pane label="设备参数" name="attr"></el-tab-pane>
              <el-tab-pane label="设备能力" name="ability"></el-tab-pane>
              <el-tab-pane label="调用日志" name="callLog"></el-tab-pane>
              <el-tab-pane label="设备日志" name="reportLog"></el-tab-pane>
              <el-tab-pane label="事件日志" name="eventLog"></el-tab-pane>
            </el-tabs>

            <!-- 设备基本信息 -->
            <div v-if="activeTab === 'basic'">
              <el-card class="box-card">
                <div>
                  <p><span class="bold">设备名称：</span>{{ curRow.deviceName }}</p>
                  <p><span class="bold">设备代码：</span>{{ curRow.deviceCode }}</p>
                  <p><span class="bold">设备分类：</span>{{ curRow.deviceCategoryName + getPsName(curRow.psName) }}</p>
                  <p><span class="bold">归属设施：</span>{{ curRow.refFacsName }}</p>
                  <p><span class="bold">归属区域：</span>{{ buildRefAreaName(curRow) }}</p>
                  <p><span class="bold">安装位置：</span>{{ curRow.location === null ? '无' : curRow.location }}</p>
                  <p><span class="bold">归属系统：</span>{{ curRow.subsystemName === null ? '无' : curRow.subsystemName }}</p>
                  <p>
                    <span class="bold">设备状态：</span>
                    <span :class="getDeviceStatusClass(curRow.deviceStatus)">
                       {{ getDeviceStatus(curRow.deviceStatus) }}
                    </span>
                  </p>
                </div>
              </el-card>
            </div>

            <!-- 设备参数 -->
            <div v-if="activeTab === 'attr'">
              <el-card class="box-card">
                <div v-for="(tableData, tableName) in attrTables" :key="tableName">
                  <p class="section-title">{{ tableData.title }}</p>
                  <el-table :data="tableData.data" style="width: 100%" :show-header="true" :empty-text="'暂无数据'">
                    <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                    <el-table-column label="属性名称" prop="attrName"></el-table-column>
                    <el-table-column label="属性标识" prop="attrKey"></el-table-column>
                    <el-table-column label="属性值" align="center">
                      <template slot-scope="scope">
                <span v-if="tableData.title === '状态属性'">
                  {{ scope.row.attrValueName || getAttrValueText(scope.row.attrValue) }}
                  <span v-if="scope.row.attrUnit">{{ scope.row.attrUnit }}</span>
                </span>
                        <span v-else>
                  {{ scope.row.attrValue }}
                </span>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-card>
            </div>

            <!-- 设备能力 -->
            <div v-if="activeTab === 'ability'">
              <el-card class="box-card">
                <el-table :data="abilityData" style="width: 100%" :show-header="true" :empty-text="'暂无数据'">
                  <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                  <el-table-column label="能力名称" prop="abilityName"></el-table-column>
                  <el-table-column label="能力描述" prop="abilityDesc"></el-table-column>
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button size="mini" type="text" icon="el-icon-info" @click="handleOperate(scope.row)">执行</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>

            <!-- 事件日志 -->
            <div v-if="activeTab === 'eventLog'">
              <el-form inline>
                <el-form-item label="记录时间">
                  <el-date-picker
                    v-model="logDaterangeTime"
                    style="width: 240px"
                    value-format="yyyy-MM-dd HH:mm"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="事件名称">
                  <el-select v-model="eventLogQueryParams.eventName" clearable>
                    <el-option
                      v-for="item in eventData"
                      :key="item.eventKey"
                      :label="item.eventName"
                      :value="item.eventKey"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleEventLogQuery">查询</el-button>
                  <el-button @click="resetEventLogQuery">重置</el-button>
                </el-form-item>
              </el-form>
              <el-table :data="eventLogData" style="width: 100%" :show-header="true" :empty-text="'暂无数据'">
                <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                <el-table-column label="对象编号" prop="objCode"></el-table-column>
                <el-table-column label="对象名称" prop="objName"></el-table-column>
                <el-table-column label="事件名称" prop="eventName"></el-table-column>
                <el-table-column label="事件时间" prop="eventTime"></el-table-column>
                <el-table-column label="操作" align="center" width="100">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" icon="el-icon-info" @click="handleEventLogDetail(scope.row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="eventLogQueryTotal > 0"
                :total="eventLogQueryTotal"
                :page.sync="eventLogQueryParams.pageNum"
                :limit.sync="eventLogQueryParams.pageSize"
                @pagination="handleEventLogQuery"
              />
            </div>
            <!-- 调用日志 -->
            <div v-if="activeTab === 'callLog'">
              <el-form inline>
                <el-form-item label="记录时间">
                  <el-date-picker
                    v-model="callDaterangeTime"
                    style="width: 240px"
                    value-format="yyyy-MM-dd HH:mm"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="能力标识">
                  <el-select v-model="callLogQueryParams.abilityKey" placeholder="请选择能力标识" clearable>
                    <el-option
                      v-for="item in abilityData"
                      :key="item.abilityKey"
                      :label="item.abilityName"
                      :value="item.abilityKey"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="调用状态">
                  <el-select v-model="callLogQueryParams.callStatus" placeholder="请选择调用状态" clearable>
                    <el-option
                      v-for="(value, key) in callStatusOptions"
                      :key="key"
                      :label="value"
                      :value="key"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleCallLogQuery">查询</el-button>
                  <el-button @click="resetCallLogQuery">重置</el-button>
                </el-form-item>
              </el-form>
              <el-table :data="callLogData" style="width: 100%" :show-header="true" :empty-text="'暂无数据'">
                <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                <el-table-column label="对象编号" prop="objCode"></el-table-column>
                <el-table-column label="对象名称" prop="objName"></el-table-column>
                <el-table-column label="对象能力" prop="abilityName"></el-table-column>
                <el-table-column label="调用时间" prop="callTime"></el-table-column>
                <el-table-column label="调用结果" align="center" width="100">
                  <template slot-scope="scope">
                    <span>{{ formatCallStatus(scope.row.callStatus) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="100">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" icon="el-icon-info" @click="handleCallLogDetail(scope.row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="callLogQueryTotal > 0"
                :total="callLogQueryTotal"
                :page.sync="callLogQueryParams.pageNum"
                :limit.sync="callLogQueryParams.pageSize"
                @pagination="handleCallLogQuery"
              />
            </div>

            <!-- 设备日志 -->
            <div v-if="activeTab === 'reportLog'">
              <el-form inline>
                <el-form-item label="记录时间">
                  <el-date-picker
                    v-model="logDaterangeTime"
                    style="width: 240px"
                    value-format="yyyy-MM-dd HH:mm"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleLogQuery">查询</el-button>
                  <el-button @click="resetLogQuery">重置</el-button>
                </el-form-item>
              </el-form>
              <el-table :data="reportLogData" style="width: 100%" :show-header="true" :empty-text="'暂无数据'">
                <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                <el-table-column label="对象编号" prop="objCode"></el-table-column>
                <el-table-column label="对象名称" prop="objName"></el-table-column>
                <el-table-column label="消息类型" prop="msgDesc"></el-table-column>
                <el-table-column label="上报时间" prop="reportTime" width="180"></el-table-column>
                <el-table-column label="操作" align="center" width="100">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" icon="el-icon-info" @click="handleReportLogDetail(scope.row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="logQueryTotal > 0"
                :total="logQueryTotal"
                :page.sync="logQueryParams.pageNum"
                :limit.sync="logQueryParams.pageSize"
                @pagination="handleLogQuery"
              />
            </div>


          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listDevRecursionByArea } from '@/api/device/device'
import { areaTreeSelect } from '@/api/basecfg/area'
import { getFacsCategorygetByCode, listAllFacs } from '@/api/basecfg/emsfacs'
import { listSubsystemAll } from '@/api/adapter/subsystem'
import { getModelByCode } from '@/api/basecfg/objModel'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listcallAbility } from '@/api/basecfg/objAbility'
import { getObjAttr } from '@/api/basecfg/objAttribute'
import { listReportLog, getReportLog, listCallLog, getCallLog,listEventLog,getEventLog } from '@/api/basecfg/objLog'

export default {
  name: 'Device',
  dicts: ['sys_device_stat'],
  components: { Treeselect },
  data() {
    return {
      activeTab: 'basic',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 能源设备表格数据
      deviceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 区域名称
      areaName: undefined,
      // 区域树选项
      treeAreaOptions: undefined,
      // 设施选项
      facsOptions: undefined,
      // 设备分类
      devcTypeOptions: undefined,
      subsystemOptions: undefined,
      subCategoryOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      curRow: {},
      attrData: [],
      abilityData: [],
      abilityDevice: [],
      eventData: [],
      BaseData: [],
      ProtocolData: [],
      StateData: [],
      MeasureData: [],
      attrTables: {
        Base: { title: '基础属性', data: [] },
        Protocol: { title: '协议属性', data: [] },
        State: { title: '状态属性', data: [] },
        Measure: { title: '计量属性', data: [] }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceSubCategory: '',
        deviceCategory: 'E',
        locationRef: null,
        refFacs: null,
        subsystemCode: null
      },
      callDaterangeTime: [],
      logDaterangeTime: [],
      logQueryParams: {
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10
      },
      logQueryTotal: 0,
      callLogQueryParams: {
        abilityKey: '',
        callStatus: '',
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10
      },
      callLogQueryTotal: 0,
      eventLogDialog: false,
      eventLogData: [],
      eventLogQueryParams: {
        eventKey:'',
        eventName:'',
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10
      },
      eventLogQueryTotal: 0,
      eventLogDetailDialog: false,
      eventLogDetailData: {},
      callStatusOptions: {
        0: '成功',
        1: '进行中',
        2: '失败'
      },
      callLogDetailDialog: false,
      callLogDetailData: {},
      reportDetailDialog: false,
      reportDetailData: {},
      callLog: false,
      reportLog: false,
      callLogData: [],
      reportLogData: []

    }
  },
  created() {
    this.getList()
    this.getAreaTree('0', 2)
    this.getFacsOptions()
    this.getSubsystem()
    this.getSubCategorygetByCode()
    const now = new Date()
    const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
    const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
    this.logQueryParams.startTime = this.formatDate(startOfDay)
    this.logQueryParams.endTime = this.formatDate(endOfDay)
    this.callLogQueryParams.startTime = this.formatDate(startOfDay)
    this.callLogQueryParams.endTime = this.formatDate(endOfDay)
    // 设置默认日期范围
    this.callDaterangeTime = [this.formatDate(startOfDay), this.formatDate(endOfDay)]
    this.logDaterangeTime = [this.formatDate(startOfDay), this.formatDate(endOfDay)]

  },
  methods: {
    formatDate(date) {
      if (!date) return ''
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    formatObjType(value) {
      const objTypeMap = {
        2: '设备'
      }
      return objTypeMap[value] || '未知类型'
    },
    formatCallStatus(status) {
      const statusMap = {
        0: '成功',
        1: '进行中',
        2: '失败'
      }
      return statusMap[status] || '未知状态'
    },

   /** 查询事件日志*/
    handleEventLogQuery() {
      if (this.curRow) {
        const startTime = this.logDaterangeTime[0];
        const endTime = this.logDaterangeTime[1];
        const eventKey = this.eventLogQueryParams.eventName;
        this.getEventLog(this.curRow.deviceCode, eventKey,startTime, endTime)
      }
    },
/** 获取事件日志数据*/
    getEventLog(deviceCode, eventKey,startTime, endTime) {
      const query = {
        objCode: deviceCode,
        startRecTime: startTime,
        endRecTime: endTime,
        eventKey: eventKey,
        pageNum: this.eventLogQueryParams.pageNum,
        pageSize: this.eventLogQueryParams.pageSize
      };
      listEventLog(query).then(response => {
        this.eventLogData = response.rows || [];
        this.eventLogQueryTotal = response.total;
      });
    },
   /** 重置事件日志查询*/
    resetEventLogQuery() {
      this.logDaterangeTime = [];
      this.eventLogQueryParams.eventName=''
      this.eventLogQueryParams.pageNum = 1;
      this.eventLogQueryParams.pageSize = 10;
      this.handleEventLogQuery();
    },
   /** 事件日志详情*/
    handleEventLogDetail(row) {
      getEventLog(row.id).then(response => {
        this.eventLogDetailData = response.data || {};
        this.eventLogDetailDialog = true;
      });
    },
    /**重置调用日志*/
    resetCallLogQuery() {
      this.callDaterangeTime = []
      this.callLogQueryParams.pageNum = 1
      this.callLogQueryParams.pageSize = 10
      this.callLogQueryParams.abilityKey = ''
      this.callLogQueryParams.callStatus = ''
      this.handleCallLogQuery()
    },
    /**查询调用日志*/
    handleCallLogQuery() {
      if (this.curRow) {
        const startTime = this.callDaterangeTime[0]
        const endTime = this.callDaterangeTime[1]
        const abilityKey = this.callLogQueryParams.abilityKey
        const callStatus = this.callLogQueryParams.callStatus
        this.getCallLog(this.curRow.deviceCode, startTime, endTime, abilityKey, callStatus)
      }
    },
    /**调用日志表格*/
    getCallLog(deviceCode, startTime, endTime, abilityKey, callStatus) {
      const query = {
        objCode: deviceCode,
        objType: '2',
        startRecTime: startTime,
        endRecTime: endTime,
        abilityKey: abilityKey,
        callStatus: callStatus,
        pageNum: this.callLogQueryParams.pageNum,
        pageSize: this.callLogQueryParams.pageSize
      }
      listCallLog(query).then(response => {
        this.callLogData = response.rows || []
        this.callLogQueryTotal = response.total
      })
    },
    /**调用日志详情*/
    handleCallLogDetail(row) {
      getCallLog(row.id).then(response => {
        this.callLogDetailData = response.data || {}
        this.callLogDetailDialog = true
      })
    },

    /**重置设备日志*/
    resetLogQuery() {
      this.logDaterangeTime = []
      this.logQueryParams.pageNum = 1
      this.logQueryParams.pageSize = 10
      this.handleLogQuery() // 重新查询
    },
    /** 查询设备日志*/
    handleLogQuery() {
      if (this.curRow) {
        const startTime = this.logDaterangeTime[0]
        const endTime = this.logDaterangeTime[1]
        this.getReportLog(this.curRow.deviceCode, startTime, endTime)
      }
    },
    /**设备日志表格*/
    getReportLog(deviceCode, startTime, endTime) {
      const query = {
        objCode: deviceCode,
        objType: '2',
        startRecTime: startTime,
        endRecTime: endTime,
        pageNum: this.logQueryParams.pageNum,
        pageSize: this.logQueryParams.pageSize

      }
      listReportLog(query).then(response => {
        this.reportLogData = response.rows || []
        this.logQueryTotal = response.total
      })
    },
    /**设备日志详情*/
    handleReportLogDetail(row) {
      getReportLog(row.id).then(response => {
        this.reportDetailData = response.data || {}
        this.reportDetailDialog = true

      })
    },
    loadAbilities(row) {
      if (!this.curRow) {
        this.$message.warning('请选择一条设备记录')
        return
      }
      getModelByCode(row.deviceModel).then(response => {
        this.abilityDevice = response.data?.abilityList.filter(item => item.hiddenFlag === 1) || []


      })
    },
    /**设备能力-执行按钮*/
    handleDeviceOperate(row, curRow) {
      listcallAbility({
        abilityKey: row.abilityKey,
        objCode: curRow.deviceCode,
        objType: '2',
        modeCode: row.modeCode,
        abilityParam: row.abilityParam
      }).then(response => {
        this.$message({ message: '设备能力执行成功', type: 'success' })
      })
    },
    // 根据区域代码获取区域名称
    buildRefAreaName(curRow) {
      if (!this.treeAreaOptions) {
        return '未知区域'; // 或者返回一个默认值
      }
      const area = this.treeAreaOptions.find(a => a.id === curRow.areaCode);
      const areaName = area ? area.label : '未知区域';

      if (curRow.locationRef !== curRow.areaCode) {
        return areaName + ' - ' + curRow.locationRefName;
      }
      return areaName;
    },
    handleOperate(row) {
      listcallAbility({
        abilityKey: row.abilityKey,
        objCode: this.curRow.deviceCode,
        objType: '2',
        modeCode: row.modeCode,
        abilityParam: row.abilityParam
      }).then(response => {
        this.$message({ message: '设备能力执行成功', type: 'success' })
      })
    },
    getPsName(psName) {
      return psName === null ? '' : ' - '+psName;
    },
    getDeviceStatus(status) {
      return status === 1 ? '在线' : '离线'
    },
    getDeviceStatusClass(status) {
      return status === 1 ? 'status-online' : 'status-offline'
    },

    getDeviceStatusText(status) {
      const statusMap = {
        0: '离线',
        1: '在线'
      }
      return statusMap[status] || ''
    },
    getAttrValueText(attrValue) {
      const valueMap = {
        0: '关闭',
        1: '开启',
        2: '通电'
      }
      return valueMap[attrValue] || attrValue
    },
    getDeviceStatusTextColor(status) {
      if (status === 0) return '#FF0000'
      if (status === 1) return '#00FF00'
      return '#000000' // 默认黑色文字
    },
    getDeviceStatusBgColor(status) {
      if (status === 0) return '#FFDDDD'
      if (status === 1) return '#DDFFDD'
      return 'transparent' // 默认无背景色
    },
    /** 查询能源设备列表 */
    getList() {
      this.loading = true
      listDevRecursionByArea(this.queryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false

      })
    },
    /** 查询区域树结构 */
    getAreaTree(areaCode, layer) {
      areaTreeSelect(areaCode, layer).then(response => {
        this.treeAreaOptions = [{
          id: null,
          label: '全部',
          children: []
        }].concat(response.data)
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.locationRef = data.id
      this.handleQuery()
    },
    cancel() {
      this.open = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.locationRef = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /**设备状态详情*/
    handleDetail(row) {
      this.reset()
      this.curRow = row
      console.log('设备this.curRow', this.curRow)
      getModelByCode(this.curRow.deviceModel).then(response => {
        this.open = true
        this.abilityData = response.data?.abilityList.filter(item => item.hiddenFlag === 1) || []
        this.attrData = response.data?.attrList || []
        this.eventData = response.data?.eventList || []
      })
      getObjAttr(2, this.curRow.deviceCode).then(response => {
        this.attrTables.Base.data = response.data?.Base || []
        this.attrTables.Protocol.data = response.data?.Protocol || []
        this.attrTables.State.data = response.data?.State || []
        this.attrTables.Measure.data = response.data?.Measure || []
      })
      this.activeTab = 'basic'
    },
    getFacsOptions() {
      const getFacsParams = {
        facsCategory: this.queryParams.deviceCategory,
        subCategory: this.queryParams.deviceSubCategory
      }
      listAllFacs(getFacsParams).then(response => {
        this.facsOptions = response.data
      })
    },
    getSubsystem() {
      listSubsystemAll().then(response => {
        this.subsystemOptions = response.data
      })
    },
    getSubCategorygetByCode() {
      getFacsCategorygetByCode(this.queryParams.deviceCategory).then(response => {
        this.subCategoryOptions = response.data.subtypeList || []
      })
    },
    deviceCategoryChange() {
      this.reset()
      this.getAreaTree('0', 2)
      this.getSubCategorygetByCode()
      this.getFacsOptions()
      this.handleQuery()
    },
    reset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.deviceSubCategory = ''
      this.queryParams.refFacs = null
      this.queryParams.subsystemCode = null

    }
  }
}
</script>

<style lang="scss" scoped>
.detail-dialog .el-dialog {
  width: 80%;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 20px;
  margin-bottom: 10px;

}

.status-highlight {
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 10px;
}

.status-online {
  color: #00FF00; /* 在线状态颜色 */
  background-color: #DDFFDD;
  padding: 2px 6px;
  border-radius: 4px;
}

.status-offline {
  color: #FF0000; /* 离线状态颜色 */
  background-color: #FFDDDD;
  padding: 2px 6px;
  border-radius: 4px;
}

</style>
