<template>
  <div class="app-container">
    <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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['topology:topology:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Menu"
            @click="toggleExpandAll"
        >{{ isExpandAll ? '折叠' : '展开' }}</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['topology:topology:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['topology:topology:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['topology:topology:export']"
        >导出
        </el-button>
      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        ref="tableRef"
        v-loading="loading"
        :data="topologyList"
        @selection-change="handleSelectionChange"
        row-key="itemId"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="项目id" align="center" prop="itemId" />
            <el-table-column label="父项目id" align="center" prop="parentId" />
            <el-table-column label="祖级列表" align="center" prop="ancestors" />-->
      <el-table-column label="项目名称" align="center" prop="itemName"/>
      <el-table-column label="显示顺序" align="center" prop="orderNum"/>
      <el-table-column label="部门状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" prop="itemType">
        <template #default="scope">
          <dict-tag :options="root_node_type" :value="scope.row.itemType"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="设备ids" align="center" prop="deviceId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['topology:topology:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                     v-hasPermi="['topology:topology:add']">新增
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['topology:topology:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />-->

    <!-- 添加或修改项目拓扑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="topologyRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="上级项目" prop="parentId">
          <el-tree-select
              v-model="form.parentId"
              :data="itemTopologyOptions"
              :props="{
                  label: 'itemName',
                  children: 'children',
                  value: 'itemId'
              }"
              :disabled="form.parentId === form.itemName"
              filterable
              check-strictly
              style="width: 100%"
          >
            <template #default="{ node, data }">
              <span>{{ data.itemName }}</span>
            </template>
          </el-tree-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序"/>
        </el-form-item>
        <el-form-item label="部门状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择部门状态">
            <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="删除标志" prop="delFlag">
                  <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
                </el-form-item>-->
        <el-form-item label="项目类型" prop="itemType">
          <el-select
              v-model="form.itemType"
              placeholder="请选择项目类型"
              filterable
              clearable
          >
            <el-option
                v-for="dict in root_node_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联设备" prop="deviceId">
          <el-tree-select
              v-model="form.deviceId"
              :data="deviceOptions"
              :props="{
                  label: 'deviceName',
                  children: 'children',
                  value: 'id'
              }"
              multiple
              filterable
              check-strictly
              placeholder="请选择设备"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </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 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: 10000,
    itemName: null,
    status: null,
    itemType: null,
    deviceId: null
  },
  rules: {}
});

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

/** 查询项目拓扑列表 */
function getList() {
  loading.value = true;
  listTopology(queryParams.value).then(response => {
    topologyList.value = proxy.handleTree(response.rows, "itemId", "parentId", "children");
    total.value = response.total;
    loading.value = false;
  });
}

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>
