<template>
  <div class="app-container">
    <el-row :gutter="5">
      <!--左侧部门数据-->
      <el-col :span="5" :xs="24">
        <div class="left-panel">
          <div class="head-container">
            <el-tree-select
              style="width: 100%"
              clearable
              v-model="selectFrom.deptId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="key"
              placeholder="请选择所属部门"
              check-strictly
              :render-after-expand="false" />
          </div>
          <div class="head-container search-container">
            <el-input
              v-model="selectFrom.selectName"
              placeholder="请输入机房名称、备注模糊查询"
              clearable
              prefix-icon="search"
              class="search-input" />
            <el-button icon="search" @click="handleSearch" class="search-button" />
          </div>
          <div class="head-container">
            <el-tree
              ref="treeRef"
              :key="treeKey"
              style="width: 100%; max-height: calc(100vh - 320px); overflow-y: auto"
              @node-click="handleNodeClick"
              :props="props"
              :load="loadNode"
              :default-expanded-keys="defaultExpandedKeys"
              node-key="id"
              lazy>
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <div class="node-label">
                    <span>{{ node.label }}</span>
                  </div>
                  <div class="tree-node-actions">
                    <el-tooltip v-if="selectedNodeId === data.id" class="box-item" effect="dark" content="已选中">
                      <el-icon class="selected-icon"><Check /></el-icon>
                    </el-tooltip>
                    <el-tooltip v-if="data.level > 0 && data.level < 4" class="box-item" effect="dark" :content="getAddNodeTooltip(node, data)">
                      <el-icon v-if="data.level > 0 && data.level < 4" @click.stop="handleAddNode(node, data)"><CirclePlus /></el-icon>
                    </el-tooltip>
                    <el-tooltip v-if="data.level > 1 && data.level < 5" class="box-item" effect="dark" content="编辑">
                      <el-icon v-if="data.level > 1 && data.level < 5" @click.stop="handleEditNode(node, data)"><EditPen /></el-icon>
                    </el-tooltip>
                    <el-tooltip v-if="data.level > 0 && data.level < 4" class="box-item" effect="dark" content="刷新子节点">
                      <el-icon @click.stop="handleRefreshNode(node, data)"><Refresh /></el-icon>
                    </el-tooltip>
                    <el-tooltip v-if="data.level > 1 && data.level < 5" class="box-item" effect="dark" content="删除">
                      <el-icon><DeleteFilled @click.stop="handleDeleteNode(node, data)" /></el-icon>
                    </el-tooltip>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>
      <!--右侧内容区域-->
      <el-col :span="19" :xs="24">
        <div class="right-content">
          <div style="margin-left: 10px; margin-top: 10px">
            <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
              <el-form-item label="端口" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入端口" />
              </el-form-item>
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="queryParams.remarks" placeholder="请输入备注" />
              </el-form-item>

              <el-form-item label="历史故障记录" prop="historyRemarks">
                <el-input v-model="queryParams.historyRemarks" placeholder="请输入备注" />
              </el-form-item>
              <el-form-item label="光缆段信息" prop="remarks">
                <el-input v-model="queryParams.opticalCableOffRemarks" placeholder="请输入光缆段信息" />
              </el-form-item>
              <el-form-item>
                <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
                <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
              </el-form-item>
            </el-form>
          </div>
          <!-- 工具区域 -->
          <div class="toolbar-container">
            <el-row :gutter="15">
              <el-col :span="1.5">
                <el-dropdown trigger="click" v-hasPermi="['odfports:import']">
                  <el-button type="primary" plain icon="Upload">
                    导入端口数据<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="upload">
                        <importData
                          templateUrl="business/OdfPorts/importTemplate"
                          importUrl="business/OdfPorts/importData"
                          @success="handleFileSuccess"></importData>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['odfports:export']"> 导出端口数据 </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>
          </div>

          <!-- 表格区域 -->
          <div class="table-container">
            <el-table
              :data="dataList"
              v-loading="loading"
              ref="table"
              border
              header-cell-class-name="el-table-header-cell"
              highlight-current-row
              height="100%"
              @sort-change="sortChange"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column prop="id" label="Id" width="50" align="center" v-if="columns.showColumn('id')" />
              <el-table-column
                prop="roomName"
                min-width="110"
                label="机房信息"
                align="center"
                :show-overflow-tooltip="true"
                v-if="columns.showColumn('roomName')">
                <template #default="scope">
                  <div class="room-info">
                    <div class="info-item">部门：{{ scope.row.deptName }}</div>
                    <div class="info-item">机房：{{ scope.row.roomName }}</div>
                    <div class="info-item">机架：{{ scope.row.rackName }}</div>
                    <div class="info-item">机框：{{ scope.row.frameName }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" width="80" label="端口" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('name')" />
              <el-table-column prop="status" width="120" label="连接状态" align="center" v-if="columns.showColumn('status')">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="连接"
                    inactive-text="断开"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    inline-prompt
                    @change="handleStatusChange(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column
                prop="opticalAttenuation"
                width="80"
                label="光衰值（dB）"
                align="center"
                :show-overflow-tooltip="true"
                v-if="columns.showColumn('opticalAttenuation')" />
              <el-table-column
                prop="remarks"
                min-width="150"
                label="备注"
                align="center"
                :show-overflow-tooltip="true"
                v-if="columns.showColumn('remarks')" />
              <el-table-column
                min-width="150"
                prop="historyRemarks"
                label="历史故障记录"
                align="center"
                :show-overflow-tooltip="true"
                v-if="columns.showColumn('historyRemarks')" />
              <el-table-column
                prop="opticalCableOffRemarks"
                width="230"
                label="光缆段信息"
                align="center"
                :show-overflow-tooltip="true"
                v-if="columns.showColumn('opticalCableOffRemarks')" />
              <el-table-column prop="createdAt" label="数据信息" width="180" :show-overflow-tooltip="true" v-if="columns.showColumn('createdAt')">
                <template #default="scope">
                  <div class="time-info">
                    <div class="time-item">创建：{{ scope.row.createdAt }}</div>
                    <div class="time-item">修改：{{ scope.row.updatedAt }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button
                      type="success"
                      size="small"
                      icon="edit"
                      title="编辑"
                      v-hasPermi="['odfports:edit']"
                      @click="handleUpdate(scope.row)"></el-button>
                    <el-button
                      type="danger"
                      size="small"
                      icon="delete"
                      title="清空"
                      v-hasPermi="['odfrooms:delete']"
                      @click="handleDelete(scope.row)"></el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 分页区域 -->
          <div class="pagination-container">
            <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- ODF端口表单组件 -->
    <OdfPortForm v-model:visible="formVisible" :id="currentId" @success="handleFormSuccess" />
    <!-- 机房表单组件 -->
    <OdfRoomForm v-model:visible="roomForm.visible" :id="roomForm.id" :mode="roomForm.mode" @success="roomForm.handleFormSuccess" />

    <!-- ODF机架表单组件 -->
    <OdfRackForm
      v-model:visible="rackForm.visible"
      :id="rackForm.id"
      :roomId="rackForm.roomId"
      :mode="rackForm.mode"
      @success="rackForm.handleFormSuccess" />

    <!-- ODF机框表单组件 -->
    <OdfFrameForm
      v-model:visible="frameForm.visible"
      :id="frameForm.id"
      :rackId="frameForm.rackId"
      :roomId="frameForm.roomId"
      :mode="frameForm.mode"
      @success="frameForm.handleFormSuccess" />
  </div>
</template>

<script setup name="odfIndex">
import { CirclePlus, EditPen, Refresh, DeleteFilled, Check } from '@element-plus/icons-vue'
import { getOdfRoomsTreeList } from '@/api/business/odfindex'
import OdfPortForm from '@/components/business/OdfPortForm.vue'
import OdfRoomForm from '@/components/business/OdfRoomExpertForm.vue'
import OdfRackForm from '@/components/business/OdfRackExpertForm.vue'
import OdfFrameForm from '@/components/business/OdfFrameForm.vue'
const { proxy } = getCurrentInstance()
import { treeselect } from '@/api/system/dept'

// 响应式数据
const selectTreeName = ref('')
const deptOptions = ref([])
const selectedDept = ref(null)
const formVisible = ref(false)
const currentId = ref(null)
const selectedNodeId = ref(null) // 添加选中节点ID跟踪
let selectFrom = ref({
  deptId: '',
  selectName: ''
})
const roomForm = ref({
  visible: false,
  id: null,
  mode: 'edit',
  currentNode: null, // 存储当前编辑的节点
  handleFormSuccess: () => {
    handleSearch()
    // 只刷新当前修改的节点
    refreshCurrentRoomNode()
  }
})

const rackForm = ref({
  visible: false,
  id: null,
  mode: 'edit',
  roomId: null,
  currentNode: null, // 存储当前编辑的节点
  handleFormSuccess: () => {
    // 只刷新当前修改的节点
    refreshCurrentNode()
  }
})
const frameForm = ref({
  visible: false,
  id: null,
  mode: 'edit',
  rackId: null,
  roomId: null,
  currentNode: null, // 存储当前编辑的节点
  handleFormSuccess: () => {
    // 只刷新当前修改的节点
    refreshCurrentFrameNode()
  }
})
const treeRef = ref(null)
const treeKey = ref(0)
const defaultExpandedKeys = ref(['all-rooms'])

const handleSearch = () => {
  // 通过增加 key 值强制重新渲染树组件，触发重新加载
  treeKey.value++
  // 清除选中状态
  selectedNodeId.value = null
}

// 刷新当前机房节点
const refreshCurrentRoomNode = () => {
  if (roomForm.value.currentNode && treeRef.value) {
    const currentNode = roomForm.value.currentNode
    const parentNode = currentNode.parent

    if (parentNode) {
      // 重新加载父节点的数据
      getOdfRoomsTreeList({
        level: parentNode.level,
        roomId: parentNode.data?.roomId,
        racksId: parentNode.data?.racksId,
        framesId: parentNode.data?.framesId,
        name: selectFrom.value.selectName,
        deptId: selectFrom.value.deptId
      }).then((res) => {
        // 清空父节点的子节点
        const children = parentNode.childNodes.slice()
        children.forEach((child) => {
          treeRef.value.remove(child)
        })

        // 添加新的子节点数据
        const dataWithIds = res.data.map((item, index) => ({
          ...item,
          id: item.id || `${parentNode.level}-${index}-${Date.now()}`
        }))

        // 重新添加子节点
        dataWithIds.forEach((item) => {
          treeRef.value.append(item, parentNode)
        })

        // 保持父节点的展开状态
        if (!parentNode.expanded) {
          parentNode.expand()
        }
      })
    }
  }

  // 清空当前节点引用
  roomForm.value.currentNode = null
}

// 刷新当前节点
const refreshCurrentNode = () => {
  if (rackForm.value.currentNode && treeRef.value) {
    const currentNode = rackForm.value.currentNode
    const parentNode = currentNode.parent

    if (parentNode && parentNode.data) {
      // 重新加载父节点的数据
      getOdfRoomsTreeList({
        level: parentNode.level,
        roomId: parentNode.data.roomId,
        racksId: parentNode.data.racksId,
        framesId: parentNode.data.framesId,
        name: selectFrom.value.selectName,
        deptId: selectFrom.value.deptId
      }).then((res) => {
        // 清空父节点的子节点
        const children = parentNode.childNodes.slice()
        children.forEach((child) => {
          treeRef.value.remove(child)
        })

        // 添加新的子节点数据
        const dataWithIds = res.data.map((item, index) => ({
          ...item,
          id: item.id || `${parentNode.level}-${index}-${Date.now()}`
        }))

        // 重新添加子节点
        dataWithIds.forEach((item) => {
          treeRef.value.append(item, parentNode)
        })

        // 保持父节点的展开状态
        if (!parentNode.expanded) {
          parentNode.expand()
        }
      })
    }
  }

  // 清空当前节点引用
  rackForm.value.currentNode = null
}

// 刷新当前机框节点
const refreshCurrentFrameNode = () => {
  if (frameForm.value.currentNode && treeRef.value) {
    const currentNode = frameForm.value.currentNode
    const parentNode = currentNode.parent

    if (parentNode && parentNode.data) {
      // 重新加载父节点的数据
      getOdfRoomsTreeList({
        level: parentNode.level,
        roomId: parentNode.data.roomId,
        racksId: parentNode.data.racksId,
        framesId: parentNode.data.framesId,
        name: selectFrom.value.selectName,
        deptId: selectFrom.value.deptId
      }).then((res) => {
        // 清空父节点的子节点
        const children = parentNode.childNodes.slice()
        children.forEach((child) => {
          treeRef.value.remove(child)
        })

        // 添加新的子节点数据
        const dataWithIds = res.data.map((item, index) => ({
          ...item,
          id: item.id || `${parentNode.level}-${index}-${Date.now()}`
        }))

        // 重新添加子节点
        dataWithIds.forEach((item) => {
          treeRef.value.append(item, parentNode)
        })

        // 保持父节点的展开状态
        if (!parentNode.expanded) {
          parentNode.expand()
        }
      })
    }
  }

  // 清空当前节点引用
  frameForm.value.currentNode = null
}

// 刷新父节点（通用函数）
const refreshParentNode = (node) => {
  if (!node || !treeRef.value) return

  const parentNode = node.parent
  if (!parentNode) {
    // 如果没有父节点，说明是根节点，刷新整个树
    handleSearch()
    return
  }

  // 重新加载父节点的数据
  getOdfRoomsTreeList({
    level: parentNode.level,
    roomId: parentNode.data?.roomId,
    racksId: parentNode.data?.racksId,
    framesId: parentNode.data?.framesId,
    name: selectFrom.value.selectName,
    deptId: selectFrom.value.deptId
  })
    .then((res) => {
      // 清空父节点的子节点
      const children = parentNode.childNodes.slice()
      children.forEach((child) => {
        treeRef.value.remove(child)
      })

      // 添加新的子节点数据
      const dataWithIds = res.data.map((item, index) => ({
        ...item,
        id: item.id || `${parentNode.level}-${index}-${Date.now()}`
      }))

      // 重新添加子节点
      dataWithIds.forEach((item) => {
        treeRef.value.append(item, parentNode)
      })

      // 保持父节点的展开状态
      if (!parentNode.expanded) {
        parentNode.expand()
      }
    })
    .catch((error) => {
      console.error('刷新父节点失败:', error)
      proxy.$message.error('刷新失败，请稍后重试')
    })
}
// 表单成功处理
function handleFormSuccess() {
  handleSearch()
  getList()
}
const getAddNodeTooltip = (node, data) => {
  if (node.level == 1) {
    return '添加机房'
  }
  if (node.level == 2) {
    return '添加机架'
  }
  if (node.level == 3) {
    return '添加机框'
  }
  return ''
}
const handleAddNode = (node, data) => {
  console.log(node, data)
  if (node.level === 1) {
    roomForm.value.id = data.roomId
    roomForm.value.mode = 'add'
    roomForm.value.visible = true
  }
  if (node.level === 2) {
    rackForm.value.id = data.racksId
    rackForm.value.roomId = data.roomId
    rackForm.value.mode = 'add'
    rackForm.value.currentNode = node
    rackForm.value.visible = true
  }
  if (node.level === 3) {
    frameForm.value.id = data.framesId
    frameForm.value.rackId = data.racksId
    frameForm.value.roomId = data.roomId
    frameForm.value.mode = 'add'
    frameForm.value.currentNode = node
    frameForm.value.visible = true
  }
}
const handleEditNode = (node, data) => {
  if (node.level === 2) {
    roomForm.value.id = data.roomId
    roomForm.value.mode = 'edit'
    roomForm.value.currentNode = node // 保存当前编辑的节点引用
    roomForm.value.visible = true
  }
  if (node.level === 3) {
    rackForm.value.id = data.racksId
    rackForm.value.roomId = data.roomId
    rackForm.value.mode = 'edit'
    rackForm.value.currentNode = node // 保存当前编辑的节点引用
    rackForm.value.visible = true
  }
  if (node.level === 4) {
    frameForm.value.id = data.framesId
    frameForm.value.rackId = data.racksId
    frameForm.value.roomId = data.roomId
    frameForm.value.mode = 'edit'
    frameForm.value.currentNode = node // 保存当前编辑的节点引用
    frameForm.value.visible = true
  }
}
const handleDeleteNode = (node, data) => {
  console.log(node, data)

  proxy
    .$confirm(`确认删除"${data.name}"数据吗？删除后数据无法恢复！`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      // 调用删除API
      deleteOdfPortsAll(data)
        .then(() => {
          proxy.$modal.msgSuccess(`删除成功`)

          // 刷新父节点
          refreshParentNode(node)

          // 如果右侧有列表也刷新
          getList()
        })
        .catch(() => {
          proxy.$modal.msgError('删除失败')
        })
    })
    .catch(() => {})
}
// 刷新节点
const handleRefreshNode = (node, data) => {
  if (!treeRef.value) return

  // 如果是叶子节点，无需刷新
  if (data.leaf) {
    proxy.$message.info('该节点无子节点')
    return
  }

  // 显示加载状态
  const loadingMessage = proxy.$message({
    message: '正在刷新子节点...',
    type: 'info',
    duration: 0
  })

  // 清空当前节点的子节点
  const children = node.childNodes.slice()
  children.forEach((child) => {
    treeRef.value.remove(child)
  })

  // 重新加载子节点数据
  getOdfRoomsTreeList({
    level: node.level,
    roomId: data.roomId,
    racksId: data.racksId,
    framesId: data.framesId,
    name: selectFrom.value.selectName,
    deptId: selectFrom.value.deptId
  })
    .then((res) => {
      // 关闭加载消息
      loadingMessage.close()

      // 为每个节点添加唯一id
      const dataWithIds = res.data.map((item, index) => ({
        ...item,
        id: item.id || `${node.level}-${index}-${Date.now()}`
      }))

      if (dataWithIds.length === 0) {
        proxy.$message.info('该节点暂无子节点')
        return
      }

      // 重新添加子节点
      dataWithIds.forEach((item) => {
        treeRef.value.append(item, node)
      })

      // 保持节点的展开状态
      if (!node.expanded) {
        node.expand()
      }

      proxy.$message.success(`刷新成功，共加载 ${dataWithIds.length} 个子节点`)
    })
    .catch((error) => {
      // 关闭加载消息
      loadingMessage.close()
      console.error('刷新失败:', error)
      proxy.$message.error('刷新失败，请稍后重试')
    })
}

const props = {
  label: 'name',
  isLeaf: 'leaf'
}

const loadNode = (node, resolve, reject) => {
  if (node.level === 0) {
    return resolve([
      {
        id: 'all-rooms',
        name: '全部机房',
        level: 1
      }
    ])
  }
  if (node.level >= 1) {
    console.log(node.data)
    getOdfRoomsTreeList({
      level: node.level,
      roomId: node.data.roomId,
      racksId: node.data.racksId,
      framesId: node.data.framesId,
      name: selectFrom.value.selectName,
      deptId: selectFrom.value.deptId
    }).then((res) => {
      console.log(res)
      // 为每个节点添加唯一id（如果API返回的数据没有id的话）
      const dataWithIds = res.data.map((item, index) => ({
        ...item,
        id: item.id || `${node.level}-${index}-${Date.now()}`
      }))
      resolve(dataWithIds)
    })
  }
}
/** 根据名称筛选部门树 */
watch(selectTreeName, (val) => {
  //   proxy.$refs['deptTreeRef'].filter(val)
})

/** 查询部门下拉树结构 */
function getTreeselect() {
  treeselect().then((response) => {
    deptOptions.value = [{ id: 0, label: '未知部门', children: [] }, ...response.data]
  })
}

/** 节点单击事件 */
function handleNodeClick(data) {
  console.log(data)
  // 设置选中的节点ID
  selectedNodeId.value = data.id
  queryParams.roomId = data.roomId
  queryParams.racksId = data.racksId
  queryParams.framesId = data.framesId
  queryParams.deptId = data.deptId
  handleQuery()
  //   selectedDept.value = data
  //   console.log('选中部门：', data.name)
  // 这里可以添加选中部门后的处理逻辑
}

import {
  listOdfPorts,
  addOdfPorts,
  delOdfPorts,
  updateOdfPorts,
  updateOdfPortsStatus,
  getOdfPorts,
  emptyOdfPorts,
  deleteOdfPortsAll
} from '@/api/business/odfports.js'
import importData from '@/components/ImportData'

const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 100,
  sort: 'Id',
  sortType: 'asc',
  roomId: null,
  racksId: null,
  framesId: null,
  deptId: null,
  opticalCableOffRemarks: null
})
const columns = ref([
  { visible: false, align: 'center', type: '', prop: 'id', label: 'Id' },

  { visible: true, align: 'center', type: '', prop: 'roomName', label: '机房信息', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'name', label: '端口名称', showOverflowTooltip: true },
  { visible: true, align: 'center', type: 'dict', prop: 'status', label: '连接状态' },
  { visible: true, align: 'center', type: '', prop: 'remarks', label: '备注', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'opticalAttenuation', label: '光衰值（dB）', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'historyRemarks', label: '历史故障表', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'opticalCableOffRemarks', label: '光缆段信息', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'createdAt', label: '数据信息', showOverflowTooltip: true }
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

var dictParams = []

function getList() {
  loading.value = true
  listOdfPorts(queryParams).then((res) => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  rules: {
    name: [{ required: true, message: '端口名称不能为空', trigger: 'blur' }],
    roomId: [{ required: true, message: '机房ID不能为空', trigger: 'blur', type: 'number' }],
    roomName: [{ required: true, message: '机房名称不能为空', trigger: 'blur' }],
    rackId: [{ required: true, message: '机架ID不能为空', trigger: 'blur', type: 'number' }],
    rackName: [{ required: true, message: '机架名称不能为空', trigger: 'blur' }],
    frameId: [{ required: true, message: '框ID不能为空', trigger: 'blur', type: 'number' }],
    frameName: [{ required: true, message: '框名称不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '部门ID不能为空', trigger: 'blur', type: 'number' }],
    rowNumber: [{ required: true, message: '行号（1-6）不能为空', trigger: 'blur', type: 'number' }],
    portNumber: [{ required: true, message: '端口号（1-12）不能为空', trigger: 'blur', type: 'number' }],

    createdAt: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
    updatedAt: [{ required: true, message: '修改时间不能为空', trigger: 'blur' }]
  },
  options: {
    // 连接状态，0正常，1断开 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    statusOptions: [],
    odf_ports_status: []
  }
})

const { form, rules, options, single, multiple } = toRefs(state)
var dictParams = ['odf_ports_status']

proxy.getDicts(dictParams).then((response) => {
  response.data.forEach((element) => {
    state.options[element.dictType] = element.list
    console.log(state.options[element.dictType])
  })
})
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order
  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

// 缺失的函数定义
function handleAdd() {
  console.log('添加功能')
}

// 修改按钮操作
function handleUpdate(row) {
  console.log(row)

  const id = row?.id
  currentId.value = id
  formVisible.value = true
}

// 处理状态开关变化
function handleStatusChange(row) {
  const statusText = row.status === 1 ? '连接' : '断开'
  // 调用更新API
  updateOdfPortsStatus(row.id, row.status)
    .then(() => {
      proxy.$modal.msgSuccess(`状态已更新为${statusText}`)
      getList() // 刷新列表
    })
    .catch(() => {
      // 更新失败，恢复原状态
      row.status = row.status === 1 ? 0 : 1
      proxy.$modal.msgError('状态更新失败')
    })
  //   proxy
  //     .$confirm(`确认${statusText}端口"${row.name}"吗？`, '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning'
  //     })
  //     .then(() => {
  //       // 调用更新API
  //       updateOdfPortsStatus(row.id, row.status)
  //         .then(() => {
  //           proxy.$modal.msgSuccess(`状态已更新为${statusText}`)
  //           getList() // 刷新列表
  //         })
  //         .catch(() => {
  //           // 更新失败，恢复原状态
  //           row.status = row.status === 1 ? 0 : 1
  //           proxy.$modal.msgError('状态更新失败')
  //         })
  //     })
  //     .catch(() => {
  //       // 用户取消，恢复原状态
  //       row.status = row.status === 1 ? 0 : 1
  //     })
}

function handleDelete(row) {
  const statusText = row.status === 1 ? '连接' : '断开'

  proxy
    .$confirm(`确认清空端口"${row.name}"数据吗？清空不会删除数据，只会将数据重置！`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      // 调用更新API
      emptyOdfPorts(row.id)
        .then(() => {
          proxy.$modal.msgSuccess(`清空成功`)
          getList() // 刷新列表
        })
        .catch(() => {
          proxy.$modal.msgError('清空失败')
        })
    })
    .catch(() => {})
}

function handleFileSuccess(response) {
  proxy.$alert('<p>' + response.data + '</p>', '导入结果', {
    dangerouslyUseHTMLString: true
  })
  handleSearch()
  getList()
}

// 导出按钮操作
function handleExport() {
  proxy
    .$confirm('是否确认导出端口数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      await proxy.downFile('/business/OdfPorts/export', { ...queryParams })
    })
}

// 初始化
getTreeselect()
handleQuery()
</script>

<style scoped>
:deep(.el-switch__core) {
  /* --el-switch-border-color: red; */
  --el-switch-off-color: red;
}
.app-container {
  padding: 0px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 160px);
  border-radius: 8px;
}

.head-container {
  margin-bottom: 0px;
  background: #ffffff;
  padding: 7px;
  border-radius: 8px;
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed; */
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.custom-tree-node:hover {
  background-color: #f0f9ff;
}

.custom-tree-node .node-label {
  width: 75%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
  color: #303133;
}

.content-area {
  height: calc(100vh - 160px);
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.content-body {
  min-height: 400px;
  padding: 20px;
}

.placeholder-content {
  margin-top: 50px;
}

.search-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-input {
  flex: 1;
}
.el-form-item {
  margin-bottom: 5px;
}

.search-button {
  flex-shrink: 0;
  width: 40px;
  height: 32px;
}

.tree-node-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.custom-tree-node:hover .tree-node-actions {
  opacity: 1;
}

/* .tree-node-actions .el-icon {
  cursor: pointer;
  padding: 6px;
  border-radius: 4px;
  transition: all 0.2s ease;
  color: #606266;
  font-size: 14px;
} */

.tree-node-actions .el-icon:hover {
  /* background-color: #409eff; */
  /* color: #ffffff; */
  transform: scale(1.1);
}

/* 选中图标样式 */
.tree-node-actions .selected-icon {
  color: #67c23a !important;
  font-weight: bold;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 刷新图标样式 */
/* .tree-node-actions .el-icon:last-child {
  color: #409eff;
}

.tree-node-actions .el-icon:last-child:hover {
  color: #337ecc;
  animation: rotate 0.5s ease-in-out;
} */

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 左侧面板样式 */
.left-panel {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  height: calc(100vh - 160px);
  overflow: hidden;
}

/* 右侧内容区域样式 */
.right-content {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  height: calc(100vh - 160px);
  display: flex;
  flex-direction: column;
}

/* 工具栏样式 */
.toolbar-container {
  padding: 6px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafbfc;
  border-radius: 8px 8px 0 0;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  /* padding: 0 20px 20px 20px; */
  overflow: auto;
}

/* 分页样式 */
.pagination-container {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: #fafbfc;
  border-radius: 0 0 8px 8px;
}

/* 表格内容样式 */
.room-info {
  text-align: left;
  line-height: 1.4;
}

.info-item {
  font-size: 12px;
  color: #606266;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.info-item:last-child {
  margin-bottom: 0;
}

.time-info {
  text-align: left;
  line-height: 1.4;
}

.time-item {
  font-size: 11px;
  color: #909399;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.time-item:last-child {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 4px;
  justify-content: center;
}

.action-buttons .el-button {
  padding: 5px 8px;
  min-height: auto;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table__header-wrapper) {
  background: #f8f9fa;
}

:deep(.el-table th.el-table__cell) {
  background: #f8f9fa;
  color: #303133;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-table td.el-table__cell) {
  border-bottom: 1px solid #f0f2f5;
}

:deep(.el-table__row:hover > td.el-table__cell) {
  background-color: #f5f7fa;
}

/* Element Plus组件样式优化 */
:deep(.el-tree-node__content) {
  height: 36px;
  border-radius: 4px;
  margin: 2px 0;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f0f9ff;
}

:deep(.el-tree-select .el-select__wrapper) {
  border-radius: 6px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }

  .head-container {
    padding: 8px;
    margin-bottom: 12px;
  }

  .left-panel,
  .right-content {
    height: auto;
    margin-bottom: 16px;
  }

  .search-container {
    flex-direction: column;
    gap: 12px;
  }

  .search-input {
    width: 100%;
  }

  .search-button {
    width: 100%;
    height: 36px;
  }

  .toolbar-container {
    padding: 12px;
  }

  .table-container {
    padding: 0 12px 12px 12px;
  }

  .pagination-container {
    padding: 12px;
  }
}
</style>
