<template>
  <div class="system-manage-container">
    <div class="system-manage-header">
      <div class="header-left">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="关键字查询">
            <el-input
              v-model="searchForm.name"
              clearable
              @keydown.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="数据类型查询">
            <el-select v-model="searchForm.type">
              <el-option label="平级数据" value="1"></el-option>
              <el-option label="树形数据" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="header-right">
        <el-form>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="system-manage-content manage-content">
      <common-table
        :autoHeight="true"
        :data="tableData"
        :columns="tableColumns"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        title=""
        :index="true"
        :border="true"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentPageChange"
      >
        <template #operations="{ row, index }">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleEdit(row, index)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="handleDelete(row, index)"
          >
            删除
          </el-button>
        </template>
      </common-table>
    </div>
    <el-dialog
      class="add-dialog"
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="cancelResourceForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="resourceFormData"
        ref="resourceForm"
        :rules="resourceRules"
        label-width="100"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="resourceFormData.name"
            placeholder="请输入资源库名称"
          />
        </el-form-item>
        <el-form-item label="唯一标识" prop="key">
          <el-input
            v-model="resourceFormData.key"
            placeholder="请输入唯一标识"
            :disabled="!!resourceFormData.id"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="resourceFormData.type"
            placeholder="请选择数据类型"
            :disabled="!!resourceFormData.id"
          >
            <el-option label="平级数据" value="1"></el-option>
            <el-option label="树形数据" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="addNode">添加节点</el-button>
        <el-form-item label="资源库数据">
          <div class="tree-content">
            <el-tree
              ref="treeRef"
              :data="treeData"
              node-key="key"
              :props="{ label: 'name' }"
              render-after-expand
            >
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <span class="node-name">
                    {{ node.label }}
                    <span class="node-key">{{ data.key }}</span>
                  </span>
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      <i class="iconfont icon-gengduo"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          @click="nodeAddChild(data)"
                          v-if="resourceFormData.type == 2"
                        >
                          <i class="iconfont icon-tianjia"></i>
                          添加子节点
                        </el-dropdown-item>
                        <el-dropdown-item @click="nodeEdit(data)">
                          <i class="iconfont icon-bianji"></i>
                          编辑
                        </el-dropdown-item>
                        <el-dropdown-item @click="nodeDelete(data)">
                          <i class="iconfont icon-shanchu"></i>
                          删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelResourceForm">取消</el-button>
          <el-button type="primary" @click="saveResourceForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="listDialogVisible"
      :title="listDialogTitle"
      width="600px"
      @close="cancelListForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="listFormData"
        ref="listForm"
        :rules="listRules"
        label-width="100"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="listFormData.name"
            placeholder="请输入资源库名称"
          />
        </el-form-item>
        <el-form-item label="唯一标识" prop="key">
          <el-input v-model="listFormData.key" placeholder="请输入唯一标识" :disabled="!!resourceFormData.id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelListForm">取消</el-button>
          <el-button type="primary" @click="saveListForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import CommonTable from "@/components/common/commonTable.vue";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchForm = ref({});
// 表格列配置
const tableColumns = [
  {
    prop: "name",
    label: "资源库名称",
    minWidth: 100,
    showOverflowTooltip: true,
  },
  {
    prop: "key",
    label: "唯一标识",
    minWidth: 100,
    showOverflowTooltip: true,
  },
  {
    prop: "operations",
    label: "操作",
    width: 120,
    slot: "operations",
    fixed: "right",
    align: "center",
  },
];
const getResourceData = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/resource/listResource",
    data: {
      ...searchForm.value,
      page: currentPage.value,
      pagesize: pageSize.value,
    },
    callback: (data) => {
      tableData.value = data.rows;
      total.value = data.count;
      loading.value = false;
    },
  });
};
onMounted(() => {
  getResourceData();
});
// 分页
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  getResourceData();
};
const handleCurrentPageChange = (page) => {
  currentPage.value = page;
  getResourceData();
};
const handleSearch = (formData) => {
  currentPage.value = 1;
  getResourceData();
};

const dialogVisible = ref(false);
const dialogTitle = ref("新增资源库");
const resourceForm = ref();
const resourceFormData = ref({});
const resourceRules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  key: [{ required: true, message: "请输入唯一标识", trigger: "blur" }],
};
let treeData = ref([]);
const treeRef = ref();
const handleAdd = () => {
  dialogTitle.value = "新增资源库";
  dialogVisible.value = true;
};

const listDialogVisible = ref(false);
const listDialogTitle = ref("添加节点");
const listForm = ref();
const listFormData = ref({});
const listRules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  key: [{ required: true, message: "请输入唯一标识", trigger: "blur" }],
};
const addNode = () => {
  // 重置编辑状态
  isEditNode.value = false;
  currentEditNode.value = null;
  // 清空表单
  listFormData.value = {};
  listForm.value?.resetFields();

  listDialogVisible.value = true;
  listDialogTitle.value = "添加节点";
};
const nodeData = ref(null);
const cancelListForm = () => {
  nodeData.value = null;
  listFormData.value = {};
  listForm.value.resetFields();
  listDialogVisible.value = false;
};

// 用于判断是添加还是编辑
const isEditNode = ref(false);
const currentEditNode = ref(null);
// 添加子节点
const nodeAddChild = (data) => {
  nodeData.value = data;
  addNode();
};

// 添加节点数据
const saveListForm = () => {
  // 先验证表单

  const formData = {
    name: listFormData.value.name,
    key: listFormData.value.key,
  };

  // 区分编辑和新增逻辑
  if (isEditNode.value && currentEditNode.value) {
    // 编辑节点：更新节点数据
    Object.assign(currentEditNode.value, formData);
    // 刷新树节点显示
    treeRef.value.updateKeyChildren(
      currentEditNode.value.key,
      currentEditNode.value.children || [],
    );
    ElMessage.success("节点编辑成功");
  } else {
    // 新增节点：添加到指定父节点或根节点
    if (nodeData.value) {
      // 添加子节点
      treeRef.value.append(formData, nodeData.value);
    } else {
      // 添加根节点
      treeRef.value.append(formData);
    }
    ElMessage.success("节点添加成功");
  }

  // 关闭弹窗并重置状态
  cancelListForm();
};
const nodeEdit = (data) => {
  isEditNode.value = true;
  currentEditNode.value = data;
  listFormData.value = {
    ...data,
  };

  //   dialogVisible.value = false;
  listDialogVisible.value = true;
  listDialogTitle.value = "编辑节点";
};
// 删除节点
const nodeDelete = (data) => {
  ElMessageBox.confirm(`确定删除节点${data.name}？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    treeRef.value.remove(data);
  });
};
// 添加资源库
const saveResourceForm = () => {
  resourceForm.value.validate((valid) => {
    if (valid) {
      let url = resourceFormData.value.id ? "updateResource" : "createResource";
      proxy.$post({
        url: "/api/resource/" + url,
        data: {
          ...resourceFormData.value,
          type: resourceFormData.value.type || "1",
          resourceInfos: treeData.value,
        },
        callback: (data) => {
          ElMessage.success(dialogTitle.value + "成功");
          cancelResourceForm();
          getResourceData();
        },
        error: (err) => {
          ElMessage.error(dialogTitle.value + "失败:", err);
        },
      });
    }
  });
};
const cancelResourceForm = () => {
  resourceFormData.value = {};
  treeData.value = [];
  resourceForm.value.resetFields();
  dialogVisible.value = false;
};

const handleEdit = (row, index) => {
  proxy.$post({
    url: "/api/resource/getResource",
    data: {
      id: row.id,
    },
    callback: (data) => {
      resourceFormData.value = {
        ...data,
        type: data.type.toString(),
      };
      treeData.value = data.resourceInfos || [];
      dialogTitle.value = "编辑资源库";
      dialogVisible.value = true;
    },
  });
};

// 删除资源库
const handleDelete = async (row, index) => {
  try {
    await ElMessageBox.confirm(`确定要删除"${row.name}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    proxy.$post({
      url: "/api/resource/deleteResource",
      data: { id: row.id },
      callback: (data) => {
        getResourceData();
        ElMessage.success("删除成功");
      },
      error: (err) => {
        ElMessage.error("删除失败:", err);
      },
    });
  } catch {}
};
</script>

<style lang="less">
@import "@/styles/manage.less";
.tree-content {
  width: 100%;
  height: 150px;
}
</style>
