<template>
  <div class="depart-manage" v-loading="loading">
    <div class="search-origin">
      <div class="origin-title">
        <h3>部门管理</h3>
        <!-- <span @click="handleAdd('parent')">+&nbsp; 新增组织</span> -->
      </div>
      <el-input placeholder="请输入部门名称" clearable>
        <template #prefix>
          <el-icon><search /></el-icon>
        </template>
      </el-input>
      <div class="tree-content">
        <span class="filterRow">
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="iconfont icon-gengduo"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleAdd"
                  ><i class="iconfont icon-tianjia"></i
                  >添加组织</el-dropdown-item
                >
                <el-dropdown-item @click="handleOriginEdit"
                  ><i class="iconfont icon-bianji"></i
                  >编辑组织</el-dropdown-item
                >
                <el-dropdown-item @click="handleDeleteOrigin"
                  ><i class="iconfont icon-shanchu"></i
                  >删除组织</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </span>
        <el-tree
          :data="treeData"
          node-key="id"
          default-expand-all
          draggable
          @node-click="handleNodeClick"
        >
        </el-tree>
      </div>
    </div>
    <div class="table-container" v-loading="userLoading">
      <div class="search-contain">
        <div>
          人员信息：
          <el-input placeholder="请输入人员信息" v-model="userName" />
        </div>
        <div>
          <el-button type="" @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleUserData">查询</el-button>
        </div>
      </div>
      <common-table
        :autoHeight="true"
        :maxRows="10"
        :data="tableData"
        :columns="tableColumns"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        title=""
        :border="true"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentPageChange"
      >
        <template #enable="{ row }">
          <el-tag :type="row.enable === 0 ? 'success' : 'danger'">
            {{ row.enable === 0 ? "启用" : "停用" }}
          </el-tag>
        </template>
      </common-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="400px"
      @close="handleDialogClose"
    >
      <commonForm
        v-model="originForm"
        :config="formConfig"
        :items="formItems"
        :rules="formRules"
        @submit="handleFormSubmit"
        @reset="handleFormReset"
      />
    </el-dialog>
  </div>
</template>

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

const { proxy } = getCurrentInstance();
const loading = ref(false);
const userLoading = ref(false);
const treeData = ref([]);
const originTreeData = ref([]);
const selectedNode = ref(null);
const userName = ref("");

// 数据转换函数
const convertToTreeData = (apiData, type) => {
  if (type === "id") {
    return apiData.map((item) => ({
      id: item.id,
      label: item.name,
      parentId: item.parentId,
      children: item.children ? convertToTreeData(item.children, "id") : [],
    }));
  } else {
    return apiData.map((item) => ({
      parentId: item.parentId,
      value: item.id,
      label: item.name,
      children: item.children ? convertToTreeData(item.children, "value") : [],
    }));
  }
};

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 表格列配置
const tableColumns = [
  {
    prop: "name",
    label: "用户姓名",
    minWidth: 100,
    showOverflowTooltip: true,
  },
  {
    prop: "departs",
    label: "所属部门",
    minWidth: 80,
    showOverflowTooltip: true,
  },
  {
    prop: "positions",
    label: "岗位",
    minWidth: 100,
    showOverflowTooltip: true,
  },
  {
    prop: "roles",
    label: "角色",
    minWidth: 100,
    showOverflowTooltip: true,
  },
  {
    prop: "mobile",
    label: "手机号码",
    minWidth: 100,
  },
  {
    prop: "createdAt",
    label: "创建时间",
    minWidth: 160,
  },
  {
    prop: "enable",
    label: "状态",
    width: 100,
    slot: "enable",
    align: "center",
  },
];

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增用户");
const isEdit = ref(false);

// 用户表单数据
const originForm = ref({
  name: "",
  parentId: "",
});

// 用户表单配置
const formConfig = {
  labelWidth: "100px",
  showButtons: true,
  submitText: "保存",
  resetText: "取消",
};

// 用户表单项配置
const formItems = computed(() => [
  {
    type: "tree",
    prop: "parentId",
    label: "上级组织",
    placeholder: "请选择上级组织",
    data: originTreeData.value,
    clearable: true,
    filterable: true,
    checkStrictly: true,
    renderAfterExpand: false,
    showCheckbox: false,
    multiple: false,
    span: 24,
    // required: true,
    // rules: [{ required: true, message: "请选择上级组织", trigger: "blur" }],
  },
  {
    type: "input",
    prop: "name",
    label: "组织名称:",
    placeholder: "请输入组织名称",
    required: true,
    rules: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
    span: 24,
  },
]);

// 表单验证规则
const formRules = {};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadTableData();
};

const handleCurrentPageChange = (page) => {
  currentPage.value = page;
  loadTableData();
};

// 新增用户
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "新增组织";
  dialogVisible.value = true;
  console.log(selectedNode.value);
  originForm.value = {
    parentId: "",
    name: "",
  };
};
let currentID = ref("");
// 处理树节点点击事件
const handleNodeClick = (data, node, element) => {
  selectedNode.value = data;
  currentID.value = selectedNode.value.id;
  handleUserData();
};
// 组织详情
const handleOriginEdit = () => {
  if (selectedNode.value === null) {
    ElMessage.warning("请选择要编辑的数据");
  } else {
    isEdit.value = true;
    dialogVisible.value = true;
    dialogTitle.value = "编辑组织";
    const selectID = {
      id: selectedNode.value.id,
    };
    proxy.$post({
      url: "/api/user/depart/getDepart",
      data: selectID,
      callback: (data) => {
        originForm.value = { ...data };
        currentID.value = data.id;
      },
      error: (err) => {
        ElMessage.error("编辑失败:", err);
      },
    });
  }
};
// 组织删除
const handleDeleteOrigin = () => {
  console.log(selectedNode.value);
  if (selectedNode.value === null) {
    ElMessage.warning("请选择要删除的组织");
  } else {
    const deleteItem = {
      id: selectedNode.value.id,
      name: selectedNode.value.label,
      parentId: selectedNode.value.parentId
        ? selectedNode.value.parentId
        : null,
    };
    proxy.$post({
      url: "/api/user/depart/deleteDepart",
      data: deleteItem,
      callback: (data) => {
        handleTreeData();
        ElMessage.success("删除成功");
      },
      error: (err) => {
        ElMessage.error("删除失败", err);
      },
    });
  }
};

const handleFormSubmit = (formData) => {
  if (isEdit.value) {
    // 编辑组织
    const updateOriForm = {
      ...formData,
      parentId: formData.parentId ? formData.parentId : null,
      id: currentID.value,
    };
    proxy.$post({
      url: "/api/user/depart/updateDepart",
      data: updateOriForm,
      callback: (data) => {
        dialogVisible.value = false;
        handleTreeData();
        ElMessage.success("组织更新成功");
      },
      error: (err) => {
        ElMessage.error("组织更新失败", err);
      },
    });
  } else {
    // 新增组织
    const addOroginForm = {
      ...formData,
      parentId: formData.parentId ? formData.parentId : null,
    };
    proxy.$post({
      url: "/api/user/depart/createDepart",
      data: addOroginForm,
      callback: (data) => {
        dialogVisible.value = false;
        handleTreeData();
        ElMessage.success("组织添加成功");
      },
      error: (err) => {
        ElMessage.error("组织添加失败:", err);
      },
    });
  }
};

const handleFormReset = () => {
  dialogVisible.value = false;
  selectedNode.value = "";
};

const handleDialogClose = () => {
  dialogVisible.value = false;
  selectedNode.value = null;
};
const handleReset = () => {
  userName.value = "";
  currentPage.value = 1;
  handleUserData();
};

// 树形数据
const handleTreeData = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/user/depart/treeDepart",
    data: {
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    callback: (data) => {
      treeData.value = convertToTreeData(data, "id");
      originTreeData.value = convertToTreeData(data, "value");
      selectedNode.value = data[0].id;
      loading.value = false;
    },
    error: (err) => {
      loading.value = false;
      ElMessage.error("加载数据失败");
    },
  });
};
// 人员信息
const handleUserData = () => {
  userLoading.value = true;
  proxy.$post({
    url: "/api/user/depart/getDepartUsers",
    data: {
      page: currentPage.value,
      pageSize: pageSize.value,
      departId: currentID.value,
      name: userName.value,
    },
    callback: (data) => {
      tableData.value = data.rows.map((item) => {
        item.departs = item.departs.map((item) => item.name).join(",");
        item.positions = item.positions.map((item) => item.name).join(",");
        item.roles = item.roles.map((item) => item.name).join(",");
        return item;
      });
      total.value = data.count;
      userLoading.value = false;
    },
    error: (err) => {
      userLoading.value = false;
      ElMessage.error("加载数据失败");
    },
  });
};

onMounted(() => {
  handleTreeData();
});
</script>

<style scoped lang="less">
.depart-manage {
  padding: 20px;
  background: rgba(157, 188, 218, 0.1);
  height: 100%;
  display: flex;
  // flex-direction: row;
  // box-sizing: border-box;
  .search-origin {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    padding: 20px;
    margin-right: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  .origin-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    span {
      color: #2561ef;
      cursor: pointer;
    }
  }
  .search-contain {
    display: flex;
    justify-content: space-between;
    .el-input {
      width: 255px;
    }
  }
  .filterRow {
    display: inline-block;
    cursor: pointer;
    display: flex;
    justify-content: end;
    .icon-gedian {
      color: rgba(37, 97, 239, 1);
      font-size: 20px;
    }
  }
  .tree-content {
    margin-top: 20px;
    position: relative;
    .el-tree {
      max-height: 700px;
      overflow-y: auto;
      // 只有当内容超过700px时才显示滚动条
      &:not(:hover) {
        scrollbar-width: none;
        -ms-overflow-style: none;
        &::-webkit-scrollbar {
          display: none;
        }
      }
      &:hover {
        scrollbar-width: thin;
        &::-webkit-scrollbar {
          display: block;
          width: 6px;
        }
        &::-webkit-scrollbar-thumb {
          background-color: rgba(144, 147, 153, 0.3);
          border-radius: 3px;
        }
        &::-webkit-scrollbar-track {
          background-color: transparent;
        }
      }
    }
  }

  .table-container {
    flex: 1;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}
.el-input__wrapper {
  height: 35px;
}

// 树节点选中样式
:deep(.el-tree-node__content) {
  &:hover {
    background-color: #f5f7fa;
  }
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(37, 97, 239, 1);
  color: #fff;
  height: 40px;
  border-radius: 3px;

  .el-tree-node__label {
    color: white !important;
  }

  .el-icon {
    color: white !important;
  }
}
</style>
