<template>
  <div class="app-container">
    <el-form size="small" :inline="true" ref="queryForm" :model="queryParams">
      <el-form-item label="项目名称" prop="proName">
        <el-input
          clearable
          placeholder="请输入项目名称"
          v-model="queryParams.proName"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属单位" prop="unit">
        <el-input
          clearable
          placeholder="请输入所属单位"
          v-model="queryParams.unit"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="chargePerson">
        <el-input
          clearable
          placeholder="请输入负责人"
          v-model="queryParams.chargePerson"
          @keyup.enter.native="handleQuery"
        />
      </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"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getModelList"></right-toolbar>
    </el-row>

    <el-table
      border
      row-key="id"
      v-loading="loading"
      :data="modelList"
      :tree-props="{ children: 'nodes' }"
    >
      <el-table-column label="序号" align="center" type="index" />

      <el-table-column label="项目名称">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
          <el-tag style="margin-left: 10px" size="mini" type="primary">节点{{ row.level }}</el-tag>
        </template>
      </el-table-column>

	  <el-table-column label="层级名称">
	    <template slot-scope="{ row }">
	      <!-- 只在项目级(第一级)显示层级名称 -->
	      <span v-if="row.level === 1">{{ row.levelName }}</span>
	    </template>
	  </el-table-column>
      <el-table-column label="操作" align="center" width="340">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddChild(row)"
            v-if="row.level < row.nodeCount"
          >
            新增
          </el-button>

          <el-button
            size="mini"
            type="text"
            :icon="row.modelUrl ? 'el-icon-view' : 'el-icon-upload'"
            @click="row.modelUrl ? handleViewModel(row) : handleUploadModel(row)"
            v-if="row.nodeCount === row.level"
          >
            {{ row.modelUrl ? '查看模型' : '上传模型' }}
          </el-button>

          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(row)"
            v-if="row.level != 1"
          >
            修改
          </el-button> -->

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="color: #f56c6c"
            @click="handleDelete(row)"
            v-if="row.level != 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="proName">
          <el-input v-model="form.proName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="层级配置" prop="level">
          <el-select v-model="form.level" placeholder="请选择层级配置" style="width: 100%">
            <el-option
              :key="item.configId"
              :value="item.configId"
              :label="item.configName"
              v-for="item in levelList"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </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-dialog width="50%" append-to-body :title="useOrReturnFormTitle" :visible.sync="useOrReturnFormVisible">
      <UseOrReturnForm
        ref="useOrReturnFormComponentRef"
        v-if="useOrReturnFormVisible"
        :project-id="currentProjectId"
        @closeUseOrReturnFormDialog="useOrReturnFormVisible = false"
        @refreshParentList="getModelList"
      />
    </el-dialog>
  <!-- 添加或修改岗位对话框 -->
        <el-dialog width="40%" append-to-body :title="addOrEditFormTitle" :visible.sync="addOrEditFormVisible">
            <AddOrEditForm ref="addOrEditComponentRef" @closeAddOrEditFormDialog="closeAddOrEditFormDialog" />
        </el-dialog>
    <el-dialog
      title="模型预览"
      :visible.sync="viewDialogVisible"
      width="60%"
      append-to-body
    >
	  <dxf-viewer :entities="dxfPreviewUrl"></dxf-viewer>
    </el-dialog>
  </div>
</template>

<script>
import AddOrEditForm from './addOrEditForm.vue'
import UseOrReturnForm from './useOrReturnForm.vue'
import UseRecordTable from './useRecordTable.vue'
import DxfViewer from './DxfViewer.vue'

// 引入相关的 API 接口
import { getModelListApi, delModelApi,openView } from '@/api/basic/model'
import { listProject, getProject, delProject, addProject, updateProject } from '@/api/basic/project'
import { getLevelListApi } from '@/api/basic/level-manage.js'


export default {
  name: 'DeviceManage',
  components: {
    AddOrEditForm,
    UseOrReturnForm,
    UseRecordTable,
    DxfViewer
  },

  data() {
    return {
      // 用于新增/修改项目的对话框
      open: false,
      title: '', // 对话框标题
      form: {
        proId: undefined,
        proName: undefined,
        proType: undefined,
        unit: undefined,
        chargePerson: undefined,
        location: undefined,
        remark: undefined,
        level: undefined,
      },
      rules: {
        proName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        level: [{ required: true, message: '请选择层级配置', trigger: 'change' }],
      },
      levelList: [], // 层级配置列表

      viewDialogVisible: false,
      dxfPreviewUrl: [],
      total: 0, // 总条数
      loading: false, // 加载中
      addOrEditFormTitle: '新增', // 新增或编辑对话框标题 (旧的AddOrEditForm组件使用)
      addOrEditFormVisible: false, // 新增或编辑对话框是否显示 (旧的AddOrEditForm组件使用)
      useOrReturnFormTitle: '模型上传', // 领用或归还对话框标题
      useOrReturnFormVisible: false, // 领用或归还对话框是否显示
      useRecordFormVisible: false, // 使用记录对话框是否显示
      // 设备列表
      modelList: [],
      currentProjectId: null,
      showSearch: true, // 控制搜索栏显示隐藏
      // 查询参数
      queryParams: {
        // pageNum: 1, // 如果您的API支持分页，可以保留
        // pageSize: 10, // 如果您的API支持分页，可以保留
        proName: undefined,
        unit: undefined,
        chargePerson: undefined,
      },
    }
  },
  created() {
    this.getModelList()
    this.getLevelList() // 获取层级配置数据
  },
  methods: {
    /** 获取层级配置列表 */
    async getLevelList() {
      try {
        const res = await getLevelListApi({
          pageNum: 1,
          pageSize: 1000,
        })
        this.levelList = res.rows
      } catch (error) {
        console.error("获取层级配置失败:", error)
      }
    },
    // 打开新增项目对话框
    handleAdd() {
      this.reset() // 重置表单
      this.open = true // 显示对话框
      this.title = '新增项目' // 设置对话框标题
    },
    // 查看模型按钮
    handleViewModel(row) {
    /*  const modelUrl = row.modelUrl
      if (!modelUrl || !modelUrl.endsWith('.dxf')) {
        this.$modal.msgWarning('模型地址无效或不是DXF文件')
        return
      } */
/* 新需求 重新做 上面建议不要删除  有需要直接可以查看 */
      openView({ id: row.id }).then(response => {
		this.dxfPreviewUrl = response.data
		this.viewDialogVisible = true
      }).catch(error => {
        console.error("获取项目详情失败:", error);
      });

    },

    // 查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1 // 假设有分页，查询时重置页码
      this.getModelList()
    },

    // 重置按钮
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 新增设备 (如果您的旧组件AddOrEditForm.vue仍然需要，可以保留此方法)
    handleAddDevice() {
      this.addOrEditFormTitle = '新增'
      this.editForm = null
      this.addOrEditFormVisible = true
    },

    // 新增子节点
    handleAddChild(row) {
      const { id, proName, nodeName, level, nodeCount, projectId } = row;
      const name = nodeName || proName; // 如果 nodeName 存在就用它，否则用 proName

      this.addOrEditFormTitle = '新增'
      this.editForm = null
      this.addOrEditFormVisible = true

      const editForm = { deviceName: name, id, level, nodeCount, projectId }
      this.$nextTick(() => {
        this.$refs.addOrEditComponentRef.setFormData(editForm)
      })
    },

    // 获取模型列表
 // 生成 UUID，备用当 nodeId 缺失时
  generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
      const r = Math.random() * 16 | 0
      const v = c === 'x' ? r : (r & 0x3 | 0x8)
      return v.toString(16)
    })
  },

  // 获取模型列表
  // 获取模型列表 - 最终优化版
  // 获取模型列表 - 最终优化版
  getModelList() {
    this.loading = true;
    getModelListApi(this.queryParams).then((response) => {
      const rawList = response.rows || [];

      // 增强型递归处理
      const formatNodes = (nodes, level = 2) => {  // 从第二级开始
        if (!Array.isArray(nodes)) return [];

        return nodes
          .filter(item => item && item.nodeId)  // 过滤无效节点
          .map(item => ({
            ...item,
            id: item.nodeId,
            name: item.nodeName || '未命名节点',
            level: level,  // 添加层级标记
            // 递归处理子节点，层级+1
            nodes: formatNodes(item.nodes || item.children || [], level + 1)
          }));
      };

      // 处理项目层数据
      const formatted = rawList.map(project => {
        const children = project.children || [];

        // 获取层级名称（项目级才需要）
        let levelName = '';
		let nodeCount = '';
        if (this.levelList && this.levelList.length > 0) {
          const levelConfig = this.levelList.find(
            item => item.configId == project.level  // 注意类型匹配
          );
          levelName = levelConfig ? levelConfig.configName : '';
        }

        return {
          ...project,
          id: project.projectId,
          name: project.proName || '未命名项目',
          level: 1,  // 项目级标记为1
          levelName: project.levelName,  // 添加层级名称
          nodes: formatNodes(children),
          rawData: project,
		  nodeCount:project.nodeCount
        };
      });

      this.modelList = formatted;
      this.total = response.total;
      this.loading = false;

    }).catch(error => {
      console.error("获取模型列表失败:", error);
      this.loading = false;
      this.$message.error("模型数据加载失败，请重试");
    });
  },
    // 上传按钮
    handleUploadModel(row) {
      this.$nextTick(() => {
        this.currentProjectId =  row.id || null
        this.useOrReturnFormVisible = true
        // 找到子组件并调用它的 resetForm 方法 (如果存在)
        // 确保 useOrReturnFormComponentRef 存在且 resetForm 是一个函数
        if (this.$refs.useOrReturnFormComponentRef && typeof this.$refs.useOrReturnFormComponentRef.resetForm === 'function') {
            this.$refs.useOrReturnFormComponentRef.resetForm()
        }
      })
    },

    // 查看记录按钮
    handleViewRecord(row) {
      console.log(row)
      this.useRecordFormVisible = true
    },

    // 编辑按钮 (旧的AddOrEditForm组件使用)
    handleEdit(row) {
      const { id, proName, level, nodeCount } = row
      this.addOrEditFormTitle = '编辑'
      this.editForm = null
      this.addOrEditFormVisible = true

      const editForm = { deviceName: proName, id, level, nodeCount }
      this.$nextTick(() => {
        // 确保 addOrEditComponentRef 存在
        if (this.$refs.addOrEditComponentRef) {
          this.$refs.addOrEditComponentRef.setFormData(editForm)
        }
      })
    },

    /** 修改按钮操作 (使用新的弹窗) */
    handleUpdate(row) {
      this.reset();
      const proId = row.id; // 对于模型列表，id 对应 projectId
      getProject(proId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改项目';
        // 注意：这里 form.level 的赋值可能需要根据您的实际数据结构调整
        // 比如，如果 response.data.level 是 configId，则可以直接赋值
        // this.form.level = response.data.level;
      }).catch(error => {
        console.error("获取项目详情失败:", error);
      });
    },

    // 删除按钮
    handleDelete(row) {
      this.$modal.confirm('是否确认删除当前节点数据吗？').then(async () => {
        // 根据 row.level 判断是删除项目还是删除模型节点
        let res;
        if (row.level === 1) { // 假设 level 1 是项目
          res = await delProject(row.id); // 使用 delProject API 删除项目
        } else {
          res = await delModelApi({ id: row.id }); // 使用 delModelApi 删除模型节点
        }

        if (res.code === 200) {
          this.$modal.msgSuccess('删除成功')
          this.getModelList()
        } else {
          this.$modal.msgError(res.msg || '删除失败');
        }
      }).catch(() => {
        // 用户取消删除
      })
    },

    // 关闭新增或编辑对话框 (针对旧的AddOrEditForm组件)
    closeAddOrEditFormDialog(isSuccess) {
      if (this.$refs.addOrEditComponentRef) {
        this.$refs.addOrEditComponentRef.resetForm()
      }
      this.addOrEditFormVisible = false
      if (isSuccess) {
        this.getModelList()
      }
    },

    // 关闭领用或归还对话框 (UseOrReturnForm)
    closeUseOrReturnFormDialog() {
      // 这个方法现在由 @closeUseOrReturnFormDialog="useOrReturnFormVisible = false" 直接处理，
      // 如果还需要 resetForm，可以取消注释下面两行并确保子组件有此方法
      // if (this.$refs.useOrReturnFormComponentRef) {
      //   this.$refs.useOrReturnFormComponentRef.resetForm();
      // }
      this.useOrReturnFormVisible = false
    },

    // 新增/修改项目对话框的取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 新增/修改项目对话框的表单重置
    reset() {
      this.form = {
        proId: undefined,
        proName: undefined,
        proType: undefined,
        unit: undefined,
        chargePerson: undefined,
        location: undefined,
        remark: undefined,
        level: undefined,
      }
      this.resetForm('form') // Element UI 的 resetForm 方法
    },
    /** 提交按钮 (新增/修改项目) */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.proId != undefined) {
            updateProject(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getModelList() // 刷新列表
            }).catch(error => {
              console.error("修改项目失败:", error);
            });
          } else {
            addProject(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getModelList() // 刷新列表
            }).catch(error => {
              console.error("新增项目失败:", error);
            });
          }
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
/* 修改树形表格的展开图标为 +/- */
::v-deep .el-table .el-table__expand-icon {
  transform: rotate(0deg); /* 取消默认的旋转效果 */
}

::v-deep .el-table .el-table__expand-icon .el-icon-arrow-right:before {
  content: '＋'; /* 更大的加号 */
  font-size: 16px; /* 调整大小 */
  font-weight: bold;
  border: 1px solid #409eff;
  color: #409eff;
  background-color: #f0f7ff;
}

::v-deep .el-table .el-table__expand-icon--expanded .el-icon-arrow-right:before {
  content: '－'; /* 更大的减号 */
  font-size: 16px;
  font-weight: bold;
  border: 1px solid #409eff;
  color: #409eff;
  background-color: #f0f7ff;
}
</style>
