<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 label="设备工艺" prop="psCode" v-if="queryParams.deviceCategory === 'W'">
            <el-select v-model="queryParams.psCode">
              <el-option v-for="item in devOptions" :label="item.psName" :value="item.psCode" :key="item.psCode"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

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

        <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="设备名称" align="left" prop="deviceName"/>
          <el-table-column label="安装位置" align="left" prop="areaPath" width="220px"/>
          <el-table-column label="归属设施" align="center" prop="refFacsName"/>
          <el-table-column label="设备分类" align="center" prop="deviceCategoryName"/>
          <el-table-column label="子系统" align="center" prop="subsystemName"/>
          <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="handleDevProcess(scope.row)"
                         v-hasPermi="['basecfg:device:edit']" v-if="shouldShowDevProcessButton(scope.row)"
              >器件
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-s-tools" @click="handleDetail(scope.row)"
                         v-hasPermi="['basecfg:device:edit']"
              >管理
              </el-button>
            </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="callLog" title="调用日志" width="60%">
          <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>
        </el-dialog>

        <!-- 调用日志详情弹窗 -->
        <el-dialog :visible.sync="callLogDetailDialog" title="调用日志详情" width="50%">
          <div v-if="callLogDetailData">
            <p><strong>对象编号：</strong>{{ callLogDetailData.objCode }}</p>
            <p><strong>对象名称：</strong>{{ callLogDetailData.objName }}</p>
            <p><strong>对象类型：</strong>{{ formatObjType(callLogDetailData.objType) }}</p>
            <p><strong>模型代码：</strong>{{ callLogDetailData.modelCode }}</p>
            <p><strong>能力标识：</strong>{{ callLogDetailData.abilityKey }}</p>
            <p><strong>对象能力：</strong>{{ callLogDetailData.abilityName }}</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="reportLog" title="设备日志" width="60%">
          <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>
        </el-dialog>

        <!-- 设备日志详情弹窗 -->
        <el-dialog :visible.sync="reportDetailDialog" title="设备日志详情" width="50%">
          <div v-if="reportDetailData">
            <p><strong>对象编号：</strong>{{ reportDetailData.objCode }}</p>
            <p><strong>对象名称：</strong>{{ reportDetailData.objName }}</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 :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <div>
              <el-form-item label="归属设施" prop="refFacs">
                <el-select v-model="form.refFacs" placeholder="请选择归属设施" @change="handleFacilityChange">
                  <el-option v-for="item in facsOptions" :key="item.facsCode" :label="item.facsName" :value="item.facsCode"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="归属区域" prop="areaCode" v-if="queryParams.deviceCategory === 'W' || queryParams.deviceCategory === 'Z'">
                <el-select v-model="form.areaCode" placeholder="请选择归属区域" @change="handleAreaChange">
                  <el-option v-for="item in areaOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="归属子区" prop="locationRef" v-if="queryParams.deviceCategory === 'W' || queryParams.deviceCategory === 'Z'">
                <el-select v-model="form.locationRef" placeholder="请选择归属子区">
                  <el-option v-for="item in subAreaOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="安装位置" prop="location" v-if="queryParams.deviceCategory === 'W' || queryParams.deviceCategory === 'Z'">
                <el-input v-model="form.location" placeholder="请输入安装位置"></el-input>
              </el-form-item>
              <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="psCode" v-if="queryParams.deviceCategory === 'W'">
                <el-select v-model="form.psCode">
                  <el-option v-for="item in devOptions" :label="item.psName" :value="item.psCode"
                             :key="item.psCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="设备模型" prop="deviceModel">
                <el-select v-model="form.deviceModel" style="width:100%" @change="handleModelChange" clearable>
                  <el-option
                    v-for="item in modelList"
                    :label="item.modelName"
                    :value="item.modelCode"
                    :key="item.modelCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="子系统" prop="subsystemCode">
                <el-select v-model="form.subsystemCode" clearable>
                  <el-option v-for="item in subsystemOptions" :label="item.systemName" :value="item.systemCode"
                             :key="item.systemCode"
                  />
                </el-select>
              </el-form-item>
            </div>
            <!-- 属性名称、属性值 -->
            <div v-if="attrList.length > 0" class="attr-list-container">设备参数:
              <ul>
                <li v-for="attr in attrList" :key="attr.attrKey" class="attr-item">
                  <span class="attr-name">{{ attr.attrName }} ({{ attr.attrUnit }}): </span>
                  <el-input
                    v-model="attrValuesMap[attr.attrKey]"
                    placeholder="点击编辑"
                    size="small"
                    @blur="updateAttrValue(attr.attrKey, attrValuesMap[attr.attrKey])"
                    class="attr-input"
                  />
                </li>
              </ul>
            </div>

            <div v-if="attrList.length > 0" class="attr-list-container">设备自定义参数：
              <el-form-item label="" prop="attrList">
                <el-table class="attr-table" v-loading="loading" :data="form.customAttrs" max-height="280px"
                          key="'customAttrs'"
                >
                  <el-table-column label="标识" align="center" prop="attrKey">
                    <template slot-scope="scope">
                      <el-input size="mini" v-model="scope.row.attrKey" placeholder="请输入标识"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="属性名" align="center" prop="attrName">
                    <template slot-scope="scope">
                      <el-input size="mini" v-model="scope.row.attrName" placeholder="请输入属性名"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="属性值" align="center" prop="attrValue">
                    <template slot-scope="scope">
                      <el-input size="mini" v-model="scope.row.attrValue" placeholder="请输入属性值"/>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作">
                    <template slot="header">
                      <div class="operateBtns" @click="addCustomAttr">
                        <span>添加</span><i class="el-icon-circle-plus-outline"></i>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <i class="el-icon-delete" @click="deleteCustomAttr(scope.$index)"></i>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

        <!--设备器件-->
        <el-drawer :title=ComponentRow.deviceName size="80%" :visible.sync="showDevProcessDrawer" direction="rtl">
          <div class="drawer-content" style="padding-left:50px">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleComponentAdd"
                           v-hasPermi="['ems:component:add']"
                >新增
                </el-button>
              </el-col>
            </el-row>
            <el-table v-loading="loading" :data="ComponentList">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="部件编码" align="center" prop="compoCode"/>
              <el-table-column label="部件标签" align="center" prop="compoTag">
                <template slot-scope="scope">
                  {{ objComTypeMapping[scope.row.compoTag] }}
                </template>
              </el-table-column>
              <el-table-column label="工艺标识代码" align="center" prop="psCode"/>
              <el-table-column label="外系统部件编码" align="center" prop="extCompoCode"/>
              <el-table-column label="部件模型" align="center" prop="compoModel"/>
              <el-table-column label="部件品牌" align="center" prop="compoBrand"/>
              <el-table-column label="部件型号" align="center" prop="compoSpec"/>
              <el-table-column label="祖籍列表" align="center" prop="ancestors"/>
              <el-table-column label="上级部件" align="center" prop="parentEqpt"/>
              <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-edit" @click="handleComponentUpdate(scope.row)"
                             v-hasPermi="['ems:component:edit']"
                  >
                    修改
                  </el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" class="deleteBtn"
                             @click="handleComponentDelete(scope.row)" v-hasPermi="['ems:component:remove']"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total" :page.sync="queryComponentParams.pageNum"
                        :limit.sync="queryComponentParams.pageSize"
                        @pagination="getComponentList"
            />

            <!-- 添加或修改设备器件对话框 -->
            <el-dialog :title="title" :visible.sync="componentOpen" width="600px" append-to-body>
              <el-form ref="componentForm" :model="componentForm" :rules="componentRules" label-width="150px">
                <el-form-item label="部件编码" prop="compoCode">
                  <el-input v-model="componentForm.compoCode" placeholder="请输入部件编码"/>
                </el-form-item>
                <el-form-item label="部件标签" prop="compoTag">
                  <el-select v-model="componentForm.compoTag" placeholder="请输入部件标签">
                    <el-option v-for="item in objComTypeOptions"
                               :label="item.name"
                               :value="item.code"
                               :key="item.code"
                    />

                  </el-select>
                </el-form-item>
                <el-form-item label="工艺标签代码" prop="psCode">
                  <el-select v-model="componentForm.psCode" placeholder="请输入工艺标签代码">
                    <el-option v-for="item in devOptions" :label="item.psCode" :value="item.psCode" :key="item.psCode"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="外系统部件编码" prop="extCompoCode">
                  <el-input v-model="componentForm.extCompoCode" placeholder="请输入外系统部件编码"/>
                </el-form-item>
                <el-form-item label="部件模型" prop="compoModel">
                  <el-select v-model="componentForm.compoModel" placeholder="请输入部件模型">
                    <el-option v-for="item in this.modelList" :label="item.modelCode" :value="item.modelCode"
                               :key="item.modelCode"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="部件品牌" prop="compoBrand">
                  <el-input v-model="componentForm.compoBrand" placeholder="请输入部件品牌"/>
                </el-form-item>
                <el-form-item label="部件型号" prop="compoSpec">
                  <el-input v-model="componentForm.compoSpec" placeholder="请输入部件型号"/>
                </el-form-item>
                <el-form-item label="祖籍列表" prop="ancestors">
                  <el-input v-model="componentForm.ancestors" placeholder="请输入祖籍列表"/>
                </el-form-item>
                <el-form-item label="上级列表" prop="parentCompo">
                  <el-input v-model="componentForm.parentCompo" placeholder="请输入上级列表"/>
                </el-form-item>

              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitComponentForm">确 定</el-button>
                <el-button @click="ComponentCancel">取 消</el-button>
              </div>
            </el-dialog>
          </div>
        </el-drawer>

        <!-- 详情弹框 -->
        <el-dialog :visible.sync="showDrawer" title="设备状态详情" custom-class="detail-dialog">
          <div class="button-group">
            <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="handleUpdate(curRow)"
                       v-hasPermi="['ems:device:edit']"
            >修改
            </el-button>
            <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete(curRow)"
                       v-hasPermi="['ems:device:remove']"
            >删除
            </el-button>
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="showCallLog(curRow)">调用日志
            </el-button>
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="showReportLog(curRow)">设备日志
            </el-button>
          </div>
          <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="event"></el-tab-pane>
              <el-tab-pane label="设备能力" name="ability"></el-tab-pane>
            </el-tabs>

            <!-- 设备基本信息 -->
            <div v-if="activeTab === 'basic'">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span class="section-title">设备状态基本信息</span>
                </div>
                <div>
                  <p><span class="bold">设备名称：</span>{{ curRow.deviceName }}</p>
                  <p><span class="bold">设备代码：</span>{{ curRow.deviceCode }}</p>
                  <p><span class="bold">子系统：</span>{{ curRow.subsystemName }}</p>
                  <p><span class="bold">设备类型：</span>{{ curRow.deviceCategoryName }}</p>
                  <p><span class="bold">归属设施：</span>{{ curRow.refFacsName }}</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">
                <div slot="header" class="clearfix">
                  <span class="section-title">设备能力</span>
                </div>
                <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="abilityKey"></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-edit" @click="handleAbilityEdit(scope.row)">
                        执行
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
            <el-dialog title="设备能力执行" :visible.sync="abilityDialogVisible" width="60%" append-to-body>
              <el-form ref="abilityForm" :model="abilityForm" label-width="120px">
                <el-form-item label="能力名称">
                  <el-input v-model="abilityForm.abilityName" placeholder="请输入能力名称" disabled></el-input>
                </el-form-item>
                <el-form-item label="能力键">
                  <el-input v-model="abilityForm.abilityKey" placeholder="请输入能力键" disabled></el-input>
                </el-form-item>
                <el-form-item label="能力描述">
                  <el-input type="textarea" v-model="abilityForm.abilityDesc" placeholder="请输入能力描述" disabled
                  ></el-input>
                </el-form-item>
                <el-form-item label="能力参数">
                  <el-input type="textarea" v-model="abilityForm.abilityParam" placeholder="请输入能力参数"></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveAbilityEdit">执行</el-button>
                <el-button @click="cancelAbilityEdit">取消</el-button>
              </div>
            </el-dialog>
            <!-- 设备事件= -->
            <div v-if="activeTab === 'event'">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span class="section-title">设备事件</span>
                </div>
                <el-table :data="eventData" 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="eventKey"></el-table-column>
                  <el-table-column label="事件类型" prop="eventType" :formatter="formatEventType"></el-table-column>
                  <el-table-column label="事件代码" prop="eventCode"></el-table-column>
                  <el-table-column label="外部事件代码" prop="extEventCode"></el-table-column>
                </el-table>
              </el-card>
            </div>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listDevRecursionByArea, getDevice, delDevice, addDevice, updateDevice } from '@/api/device/device'
import { areaTreeSelect,getAreaTreeSelect} from '@/api/basecfg/area'
import { getFacsCategorygetByCode, listAllFacs } from '@/api/basecfg/emsfacs'
import { listSubsystemAll } from '@/api/adapter/subsystem'
import { getModelByCode, listAllModel } from '@/api/basecfg/objModel'
import { getObjAttr } from '@/api/basecfg/objAttribute'
import { addAttrValueBatch } from '@/api/basecfg/objAttributeValue'
import { getDevProcess } from '@/api/commonApi'
import { addComponent, delComponent, getComponent, listByDevice, updateComponent } from '@/api/basecfg/component'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listcallAbility } from '@/api/basecfg/objAbility'
import { getCallLog, getReportLog, listCallLog, listReportLog } from '@/api/basecfg/objLog'

export default {
  name: 'Device',
  components: { Treeselect },
  data() {
    return {
      // 归属区域下拉选项
      areaOptions: [],
      // 归属子区下拉选项
      subAreaOptions: [],
      abilityDialogVisible: false,
      abilityForm: {
        abilityName: '',
        abilityKey: '',
        abilityParam: '',
        abilityDesc: ''
      },
      currentAbilityIndex: -1,
      activeTab: 'basic',
      ComponentRow: [],
      componentForm: {},
      subcategoryCode: '',
      // 属性模板数组
      attrList: [],
      attrValues: [],
      ComponentList: [],
      abilityDevice: [],
      attrValuesMap: {},
      modelList: [],
      showDrawer: false,
      showDevProcessDrawer: false,
      componentOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 能源设备表格数据
      deviceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 区域名称
      areaName: undefined,
      // 区域树选项
      treeAreaOptions: undefined,
      totalAreaOptions: undefined,
      // 设施选项
      facsOptions: undefined,
      // 设备分类
      subCategoryOptions: undefined,
      subsystemOptions: undefined,
      devOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      callDaterangeTime: [],
      logDaterangeTime: [],
      logQueryParams: {
        startTime: '',
        endTime: ''
      },
      callLogQueryParams: {
        abilityKey: '',
        callStatus: '',
        startTime: '',
        endTime: ''
      },
      callStatusOptions: {
        0: '成功',
        1: '进行中',
        2: '失败'
      },
      callLogDetailDialog: false,
      callLogDetailData: {},
      reportDetailDialog: false,
      reportDetailData: {},
      callLog: false,
      reportLog: false,
      callLogData: [],
      reportLogData: [],
      // 查询参数
      queryParams: {
        psCode: null,
        pageNum: 1,
        pageSize: 10,
        deviceCode: null,
        deviceSubCategory: '',
        deviceCategory: 'E',
        locationRef: null,
        locationRefName:null,
        refFacs: null,
        customAttrs: null,
        areaCode: null,
        location: null
      },
      queryComponentParams: {
        pageNum: 1,
        pageSize: 10
      },
      objComTypeMapping: {
        1: '总开',
        2: '照明',
        3: '风机'
      },
      objComTypeOptions: [
        { code: 1, name: '总开' },
        { code: 2, name: '照明' },
        { code: 3, name: '风机' }

      ],
      curRow: {},
      abilityData: [],
      eventData: [],
      BaseData: [],
      ProtocolData: [],
      StateData: [],
      MeasureData: [],
      attrTables: {
        Base: { title: '基础属性', data: [] },
        Protocol: { title: '协议属性', data: [] },
        State: { title: '状态属性', data: [] },
        Measure: { title: '计量属性', data: [] }
      },
      // 表单参数
      form: {
        customAttrs: [],
      },

      // 表单校验
      rules: {
        refFacs: [
          { required: true, message: '归属设施', trigger: 'blur' }
        ],
        refArea: [
          { required: true, message: '安装位置', trigger: 'blur' }
        ],
        deviceCode: [
          { required: true, message: '设备代码不能为空', trigger: 'blur' }
        ],
        deviceName: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ]
      },
      componentRules: {
        deviceCode: [
          { required: true, message: '设备code不能为空', trigger: 'blur' }
        ],
        compoCode: [
          { required: true, message: '部件编码不能为空', trigger: 'blur' }
        ],
        psCode: [
          { required: true, message: '工艺标签代码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 根据名称筛选区域树
    areaName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getAreaTree('0', 2)
    this.getFacsOptions()
    this.getSubsystem()
    this.getSubCategorygetByCode()
    this.getFacsModel()
    this.getAllDevProcess(this.subcategoryCode)
    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)]
    this.loadAreaOptions(); // 加载归属区域数据
  },
  methods: {
    /** 归属设施*/
    handleFacilityChange(selectedFacilityCode) {
      const selectedFacility = this.facsOptions.find(f => f.facsCode === selectedFacilityCode);
      if (selectedFacility) {
        this.form.areaName = selectedFacility.refAreaName;
        this.form.areaCode = selectedFacility.refArea;
        this.loadSubAreaOptions(selectedFacility.refArea);
      }
    },
    /** 归属设施*/
    handleAreaChange(value) {
      this.form.locationRef = null;
      this.loadSubAreaOptions(value);
    },
    /**下拉归属区域*/
    loadAreaOptions() {
      getAreaTreeSelect('0', 1 ).then(response => {
        this.areaOptions = response.data || [];
      });
    },
    /**下拉归属子区*/
    loadSubAreaOptions(rootCode) {
      getAreaTreeSelect(rootCode,  2 ).then(response => {
        this.subAreaOptions = response.data || [];
      });
    },
    getFacsOptions() {
      const getFacsParams = {
        facsCategory: this.queryParams.deviceCategory,
        subCategory: this.queryParams.deviceSubCategory
      }
      listAllFacs(getFacsParams).then(response => {
        this.facsOptions = response.data
      })
    },

    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] || '未知状态'
    },

    /**日志*/
    showCallLog(row) {
      this.curRow = row
      this.getCallLog(row.deviceCode, this.callLogQueryParams.startTime, this.callLogQueryParams.endTime)
      this.callLog = true
    },
    showReportLog(row) {
      this.curRow = row
      // 加载设备日志数据
      this.getReportLog(row.deviceCode, this.logQueryParams.startTime, this.logQueryParams.endTime)
      this.reportLog = true
    },
    /**重置调用日志*/
    resetCallLogQuery() {
      this.callDaterangeTime = []
      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
      }
      listCallLog(query).then(response => {
        this.callLogData = response.rows || []
      })
    },
    /**调用日志详情*/
    handleCallLogDetail(row) {
      getCallLog(row.id).then(response => {
        this.callLogDetailData = response.data || {}
        this.callLogDetailDialog = true
      })
    },

    /**重置设备日志*/
    resetLogQuery() {
      this.logDaterangeTime = []
      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,

      }
      listReportLog(query).then(response => {
        this.reportLogData = response.rows || []
      })
    },

    /**设备日志详情*/
    handleReportLogDetail(row) {
      getReportLog(row.id).then(response => {
        this.reportDetailData = response.data || {}
        this.reportDetailDialog = true

      })
    },

    formatEventType(row, column, cellValue) {
      return cellValue === 1 ? '消息上报' : '异常告警'
    },
    getAttrValueText(attrValue) {
      const valueMap = {
        0: '关闭',
        1: '开启',
        2: '通电'
      }
      return valueMap[attrValue] || attrValue
    },
    /** 查询能源设备列表 */
    getList() {
      this.loading = true
      listDevRecursionByArea(this.queryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /**新增、修改、删除*/
    handleComponentAdd() {
      this.componentReset()
      this.componentOpen = true
      this.title = '添加设备器件属性'
      this.componentForm.deviceCode = this.ComponentRow.deviceCode // 设置默认设备代码
    },
    handleComponentUpdate(row) {
      this.componentReset()
      const id = row.id || this.ids
      getComponent(id).then(response => {
        this.componentForm = response.data
        this.componentOpen = true
        this.title = '修改设备器件属性'
        this.componentForm.deviceCode = this.ComponentRow.deviceCode // 设置默认设备代码
      })
    },
    handleComponentDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除能源对象属性编号为"' + ids + '"的数据项？').then(function() {
        return delComponent(ids)
      }).then(() => {
        this.getComponentList(row.deviceCode)
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    submitComponentForm() {
      this.$refs['componentForm'].validate(valid => {
        if (valid) {
          if (this.componentForm.id != null) {
            updateComponent(this.componentForm).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.componentOpen = false
              this.getComponentList(this.componentForm.deviceCode)
            })
          } else {
            addComponent(this.componentForm).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.componentOpen = false
              this.getComponentList(this.componentForm.deviceCode)
            })
          }
        }
      })
    },
    ComponentCancel() {
      this.componentOpen = false
      this.componentReset()
    },
    /**查询部件列表*/
    getComponentList(deviceCode) {
      listByDevice(deviceCode).then(response => {
        this.ComponentList = response.data
      })
    },
    /** 查询区域树结构 */
    getAreaTree(areaCode, layer) {
      getAreaTreeSelect(areaCode, layer).then(response => {
        this.treeAreaOptions = [{
          id: null,
          label: '全部',
          children: 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()
    },
    /** 执行弹框 */
    handleAbilityEdit(row) {
      // 复制当前行记录的值到弹框表单中
      this.abilityForm = JSON.parse(JSON.stringify(row))
      this.currentAbilityIndex = this.abilityData.indexOf(row)
      this.abilityDialogVisible = true
    },
    /**设备能力-执行按钮*/
    saveAbilityEdit() {
      if (this.currentAbilityIndex !== -1) {
        const updatedAbility = { ...this.abilityForm }
        const abilityParams = {
          objCode: this.curRow.deviceCode,
          objType: 2,
          modeCode: updatedAbility.modelCode,
          abilityKey: updatedAbility.abilityKey,
          abilityParam: updatedAbility.abilityParam
        }
        listcallAbility(abilityParams)
          .then((response) => {
            if (response.code === 200) {
              this.$message.success('保存成功')
              this.abilityData.splice(this.currentAbilityIndex, 1, updatedAbility)
            }
          })
        this.abilityDialogVisible = false
      }
    },
    /** 取消执行按钮 */
    cancelAbilityEdit() {
      this.abilityDialogVisible = false
      this.abilityForm = {
        abilityName: '',
        abilityKey: '',
        abilityParam: '',
        abilityDesc: ''
      }
      this.currentAbilityIndex = -1
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        areaCode:null,
        location:null,
        locationRef:null,
        deviceCode: null,
        deviceName: null,
        deviceType: null,
        deviceStatus: null,
        deviceModel: null,
        refArea: null,
        refFacs: null,
        subsystemCode: null,
        psCode: null,
        createTime: null,
        updateTime: null,
        customAttrs: []
      }
      this.attrList = []
      this.attrValuesMap = {}
      this.resetForm('form')
    },
    componentReset() {
      this.componentForm = {
        id: null,
        deviceCode: this.ComponentRow.deviceCode || '',
        compoCode: null,
        compoTag: null,
        psCode: null,
        extCompoCode: null,
        compoModel: null,
        compoBrand: null,
        compoSpec: null,
        ancestors: null,
        parentCompo: null
      }
      this.resetForm('componentForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.locationRef = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加能源设备'
      this.attrList = []
      this.form.customAttrs = []
      this.attrValuesMap = {}
      // 加载归属子区
      this.loadSubAreaOptions(this.form.areaCode);
    },
    /**设备器件按钮*/
    handleDevProcess(row) {
      this.showDevProcessDrawer = true
      this.ComponentRow = row
      listByDevice(this.ComponentRow.deviceCode).then(response => {
        this.ComponentList = response.data
      })
    },
    shouldShowDevProcessButton(row) {
      const categoryIsW = this.queryParams.deviceCategory === 'W'
      const validPsCodes = ['AA', 'AH', 'AJ', 'AM', 'AP', 'AL', 'APE', 'ALE', 'AF', 'ACC']
      const psCodeIsValid = validPsCodes.includes(row.psCode)
      // 只有当设备分类为输能设备且设备工艺代码有效时，才返回true
      return categoryIsW && psCodeIsValid
    },
    /**设备管理按钮*/
    handleDetail(row) {
      this.showDrawer = true
      this.curRow = row
      console.log("设备详情",this.curRow)
      this.subKey = this.$options.data().subKey
      getModelByCode(this.curRow.deviceModel).then(response => {
        this.eventData = response.data?.eventList || []
        this.abilityData = response.data?.abilityList || []
      })
      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'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data
        // 加载归属子区
        this.loadSubAreaOptions(this.form.areaCode);
        console.log('this.form', this.form)
        this.open = true
        this.title = '修改能源设备'
        this.attrList = []
        this.form.customAttrs = []
        this.attrValuesMap = {}
        this.getObjAttr(2, this.form.deviceCode)
      })
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.attrList) {
        this.attrList = []
      }
      if (!this.form.customAttrs) {
        this.form.customAttrs = []
      }
      let dataToSubmit = []
      this.attrList.forEach(attr => {
        const attrName = attr.attrName
        const attrKey = attr.attrKey
        const attrValue = this.attrValuesMap[attrKey]
        const existingIndex = dataToSubmit.findIndex(item => item.attrKey === attrKey)
        if (existingIndex === -1) {
          dataToSubmit.push({
            modelCode: this.form.deviceModel,
            objCode: this.form.deviceCode,
            objType: 2,
            attrKey: attrKey,
            attrValue: attrValue,
            attrName: attrName
          })
        }
      })

      // 添加自定义属性数据
      this.form.customAttrs.forEach(customAttr => {
        const attrName = customAttr.attrName
        const attrKey = customAttr.attrKey
        const attrValue = customAttr.attrValue
        const existingIndex = dataToSubmit.findIndex(item => item.attrKey === attrKey)
        if (existingIndex === -1) {
          dataToSubmit.push({
            modelCode: '',
            objCode: this.form.deviceCode,
            objType: 2,
            attrKey: attrKey,
            attrValue: attrValue,
            attrName: attrName
          })
        }
      })

      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.showDrawer=false
              this.getList()
              if (this.showDrawer && this.curRow && this.curRow.id === this.form.id) {
                this.handleDetail(this.form)
              }


            })

            if (dataToSubmit.length > 0) {
              addAttrValueBatch(dataToSubmit)
                .then(response => {
                  if (response.code === 200) {
                    this.$message.success('属性添加成功')
                  }
                })
            }
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList() // 刷新设备列表
            })

            if (dataToSubmit.length > 0) {
              addAttrValueBatch(dataToSubmit)
                .then(response => {
                  if (response.code === 200) {
                    this.$message.success('属性添加成功')
                  }
                })
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除能源设备编号为"' + ids + '"的数据项？').then(function() {
        return delDevice(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/basecfg/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },

    getSubCategorygetByCode() {
      getFacsCategorygetByCode(this.queryParams.deviceCategory).then(response => {
        this.subCategoryOptions = response.data.subtypeList || []
      })
    },
    getSubsystem() {
      listSubsystemAll().then(response => {
        this.subsystemOptions = response.data
      })
    },
    getAllDevProcess(subcategoryCode) {
      getDevProcess(subcategoryCode).then(response => {
        this.devOptions = response.data
      })
    },
    deviceCategoryChange() {
      this.queryParams.deviceSubCategory = ''
      if (this.queryParams.deviceCategory === 'E' || this.queryParams.deviceCategory === 'W'
        || this.queryParams.deviceCategory === 'T' || this.queryParams.deviceCategory === 'C') {
        this.getAreaTree('0', 2)
      } else if (this.queryParams.deviceCategory === 'Z') {
        this.getAreaTree('0', 2)
      }
      this.getSubCategorygetByCode()
      this.getFacsOptions()
      this.handleQuery()
    },
    /**自定义属性表格*/
    addCustomAttr() {
      // 添加一个新的自定义属性
      if (!Array.isArray(this.form.customAttrs)) {
        this.form.customAttrs = []
      }
      this.form.customAttrs.push({
        attrKey: '',
        attrName: '',
        attrValue: ''
      })
      // 强制更新视图
      this.$forceUpdate()

    },
    deleteCustomAttr(index) {
      // 删除指定索引的自定义属性
      if (this.form.customAttrs.length > 0) {
        this.form.customAttrs.splice(index, 1)
      }

    },
    /**设备模型*/
    updateAttrValue(attrKey, newValue) {
      this.attrValuesMap[attrKey] = newValue
    },

    getFacsModel() {
      listAllModel(2).then(response => {
        this.modelList = response.data
      })
    },
    handleModelChange(modelCode) {
      if (modelCode) {
        this.getModelByCode(modelCode)
        this.getObjAttr(2, this.form.deviceCode)
      }
    },
    getModelByCode(modelCode) {
      getModelByCode(modelCode).then(response => {
        const filteredAttrList = response.data.attrList.filter(attr => attr.attrType === 0)
        this.attrList = filteredAttrList

      })
    },
    /**  getObjAttr存在问题 */
    getObjAttr(objType, deviceCode) {
      getObjAttr(objType, deviceCode).then(response => {
        // const attrs = response.data.attrs;
        const attrs = response.data.attrs.filter(attr => attr.attrType === 0)
        const attrValues = response.data.attrValues || [] // 确保是一个数组

        // 创建一个映射对象，用于存储 attrKey 与对应的 attrValue
        const attrValuesMap = {}
        // 遍历 attrs 数组
        attrs.forEach(attr => {
          // 查找 attrValues 数组中是否有匹配的 attrKey
          const attrValueObj = attrValues.find(value => value.attrKey === attr.attrKey)
          if (attrValueObj) {
            attrValuesMap[attr.attrKey] = attrValueObj.attrValue
          } else {
            attrValuesMap[attr.attrKey] = ''
          }
        })

        // 更新 attrValuesMap 到组件的数据中
        this.attrValuesMap = attrValuesMap
      })
    }
  }
}
</script>
<style lang="scss" scoped>

.divider {
  border-bottom: 2px solid #ebeef5;
  margin: 10px 0;
}

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

.drawer-content {
  padding: 0 20px;
}


.section-title {
  font-size: 18px;
  font-weight: bold;
}

.attr-list-container {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px 0;
  font-weight: bold;
}

.attr-list-container ul {
  padding: 0;
  list-style: none;
}

.attr-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.attr-input {
  min-width: 100px;
  flex: 1;
}

.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;
}

.detail-dialog .el-dialog {
  width: 80%;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0;
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.button-group {
  display: flex;
  gap: 10px;
}

/* 禁用状态的输入框样式 */
.el-input.is-disabled .el-input__inner,
.el-textarea.is-disabled .el-textarea__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
}
</style>
