<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="tree-container">
          <el-table
              ref="tableRef"
              v-loading="loading"
              :data="topologyList"
              @current-change="handleCurrentChange"
              row-key="itemId"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              :default-expand-all="true"
              :indent="24"
              class="custom-table"
              :show-header="false"
              :highlight-current-row="true"
              :border="false"
          >
            <el-table-column align="left" prop="itemName">
              <template #default="{ row }">
                <i
                    v-if="row.children && row.children.length > 0"
                    :class="row.expanded ? 'el-icon-folder-opened' : 'el-icon-folder'"
                    style="margin-right: 5px"
                ></i>
                <i v-else class="el-icon-document" style="margin-right: 5px"></i>
                {{ row.itemName }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="18">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="项目名称" prop="itemName">
            <el-input
                v-model="queryParams.itemName"
                placeholder="请输入项目名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="部门状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择部门状态" clearable style="width: 240px">
              <el-option
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目类型" prop="itemType">
            <el-select v-model="queryParams.itemType" placeholder="请选择项目类型" clearable style="width: 240px">
              <el-option
                  v-for="dict in root_node_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" stripe border :data="deviceOptions" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <!--      <el-table-column label="设备ID" align="center" prop="id" />-->
          <el-table-column label="设备编码" align="center" prop="deviceCode" width="90"/>
          <el-table-column label="设备名称" align="center" prop="deviceName" width="120"/>
          <el-table-column label="设备类型" align="center" prop="deviceType" />
          <el-table-column label="子系统类型" align="center" prop="subsystemType" width="120"/>
          <el-table-column label="所属空间ID" align="center" prop="spaceId" width="100"/>
          <el-table-column label="所属空间名称" align="center" prop="spaceName" width="110"/>
          <el-table-column label="品牌" align="center" prop="brand" />
          <el-table-column label="型号" align="center" prop="model" width="90"/>
          <el-table-column label="序列号" align="center" prop="serialNumber" width="120"/>
          <el-table-column label="生产日期" align="center" prop="manufactureDate" width="110" sortable
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="安装日期" align="center" prop="installDate" width="110">
            <template #default="scope">
              <span>{{ parseTime(scope.row.installDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="保修期(月)" align="center" prop="warrantyPeriod" width="90"/>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="sys_drivce_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="是否在线" align="center" prop="isOnline">
            <template #default="scope">
              <dict-tag :options="sys_yes_no_tf" :value="scope.row.isOnline"/>
            </template>
          </el-table-column>
          <el-table-column label="设备描述" align="center" prop="description" width="140"/>
          <el-table-column label="操作" min-width="140" fixed="right" width="200px" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['driver:basic:detail']">详情</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['driver:basic:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['driver:basic:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getListBasic"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Topology">
import {listTopology, getTopology, delTopology, addTopology, updateTopology} from "@/api/device/topology";
import {listBasic} from "@/api/device/basic";

const {proxy} = getCurrentInstance();
const {root_node_type, sys_normal_disable} = proxy.useDict('root_node_type', 'sys_normal_disable');

const deviceList = ref([]);
const topologyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 新增响应式引用
const itemTopologyOptions = ref([]);
const deviceOptions = ref([]);
const isExpandAll = ref(false);
const tableRef = ref();


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemName: null,
    status: null,
    itemType: null,
    deviceId: null
  },
  rules: {}
});

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

/** 查询项目拓扑列表 */
function getList() {
  loading.value = true;
  listTopology({pageNum: 1,pageSize: 10000,}).then(response => {
    topologyList.value = proxy.handleTree(response.rows, "itemId", "parentId", "children");
    //total.value = response.total;
    loading.value = false;
    topologyList.value = injectDeviceNodes(topologyList.value);
  });
}
// 选中数据后的查询
const handleCurrentChange = (currentRow) => {
  if (currentRow && currentRow.itemId) {
    console.log('当前选中行:', currentRow);

    // 调用(接口)查询方法
    listBasic(queryParams.value).then(response => {
      deviceOptions.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
};

function injectDeviceNodes(treeData) {
  return treeData.map(node => {
    const newNode = {...node};

    // 递归处理子节点
    if (newNode.children && newNode.children.length > 0) {
      newNode.children = injectDeviceNodes(newNode.children);
    }

    // 处理当前节点的 deviceId
    if (newNode.deviceId && typeof newNode.deviceId === "string") {
      const deviceIds = newNode.deviceId.split(",").filter(Boolean);
      const deviceChildren = deviceIds.map(id => ({
        itemId: `${newNode.itemId}-${id}`,
        itemName: `设备: ${id}`,
        level: (newNode.level || 0) + 1,
        isDevice: true
      }));

      // 合并原有子节点和设备子节点
      newNode.children = (newNode.children || []).concat(deviceChildren);
    }

    return newNode;
  });
}


function toggleExpandAll() {
  isExpandAll.value = !isExpandAll.value;

  const toggleChildren = (items) => {
    items.forEach(item => {
      tableRef.value.toggleRowExpansion(item, isExpandAll.value);
      if (item.children && item.children.length > 0) {
        toggleChildren(item.children);
      }
    });
  };

  toggleChildren(topologyList.value);
}

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

// 表单重置
function reset() {
  form.value = {
    itemId: null,
    parentId: null,
    ancestors: null,
    itemName: null,
    orderNum: null,
    status: null,
    delFlag: null,
    itemType: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deviceId: null
  };
  proxy.resetForm("topologyRef");
}

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

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

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

/** 新增按钮操作 */
function handleAdd(row = null) {
  reset();
  open.value = true;
  title.value = "添加项目拓扑";

  form.value = {
    ...form.value,
    parentId: row ? row.itemId : null,
    status: '0', // 默认部门状态为"正常"
    itemType: row ? row.itemType : null,
    deviceId: null
  };

  // 并行加载拓扑和设备数据
  Promise.all([
    listTopology({pageNum: 1, pageSize: 10000}),
    listBasic({pageNum: 1, pageSize: 10000})
  ]).then(([topologyRes, deviceRes]) => {
    itemTopologyOptions.value = proxy.handleTree(topologyRes.rows, "itemId");
    deviceOptions.value = deviceRes.rows.map(item => ({
      id: item.id,
      deviceName: `${item.deviceCode} - ${item.deviceName}`
    }));
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _itemId = row.itemId;

  getTopology(_itemId).then(response => {
    // 处理关联设备数据
    const deviceIds = response.data.deviceId ? response.data.deviceId.split(',').map(id => String(id)) : [];

    // 处理上级项目数据
    //const parentId = response.data.parentId === "0" ? response.data.itemName : response.data.parentId;
    form.value = {
      ...response.data,
      parentId: response.data.parentId === "0" ? response.data.itemName : response.data.parentId,
      deviceId: deviceIds
    };

    Promise.all([
      listTopology({pageNum: 1, pageSize: 10000}),
      listBasic({pageNum: 1, pageSize: 10000})
    ]).then(([topologyRes, deviceRes]) => {
      itemTopologyOptions.value = proxy.handleTree(topologyRes.rows, "itemId");
      deviceOptions.value = deviceRes.rows.map(item => ({
        id: String(item.id),  // 确保ID转为字符串
        deviceName: `${item.deviceCode} - ${item.deviceName}`
      }));
    });

    open.value = true;
    title.value = "修改项目拓扑";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["topologyRef"].validate(valid => {
    if (valid) {
      if (Array.isArray(form.value.deviceId)) {
        form.value.deviceId = form.value.deviceId.join(',');
      }
      if (form.value.itemId != null) {
        updateTopology(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTopology(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _itemIds = row.itemId || ids.value;
  proxy.$modal.confirm('是否确认删除项目拓扑编号为"' + _itemIds + '"的数据项？').then(function () {
    return delTopology(_itemIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

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

function getListBasic() {
  listBasic(queryParams.value).then(response => {
    deviceOptions.value = response.rows;
  });
}

getList();
//getListBasic();
</script>
<style scoped>
/* 左侧树形表格高亮样式 */
:deep(.custom-table .el-table__body tr.current-row > td) {
  background-color: #a6b9dd !important; /* 可以替换为您想要的颜色 */
  border-radius: 12px !important;  /* 添加圆角效果 */
  margin: 8px 0 !important;      /* 添加间距使圆角更明显 */
}

/* 如果需要同时修改文字颜色 */
:deep(.custom-table .el-table__body tr.current-row > td .cell) {
  color: #fff !important;
}

/* 树形表格样式 */
.custom-table {
  background: transparent !important;
}
.custom-table :deep(.el-table__row) {
  background: transparent !important;
}
.custom-table :deep(.el-table__cell) {
  padding: 6px 0 !important;  /* 减小上下内边距 */
  border: none !important;
}
.custom-table :deep(.el-table__cell .cell) {
  line-height: 13px !important;
  height: 13px !important;
}
.custom-table :deep(.el-table__inner-wrapper::before) {
  display: none;
}
.tree-container {
  height: 990px; /* 可根据需要调整高度 */
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>
