<template>
  <div class="depart-manage" v-loading="loading">
    <div class="manage-left">
      <div class="handle-btn">
        <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      </div>
      <div class="tree-content">
        <el-tree
          :data="treeData"
          node-key="id"
          default-expand-all
          :props="{label: 'name'}"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span class="node-name">{{ node.label }}</span>
              <el-dropdown>
                <span class="el-dropdown-link">
                  <i class="iconfont icon-gengduo"></i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleAddChild(data)"
                      ><i class="iconfont icon-tianjia"></i
                      >添加子部门</el-dropdown-item
                    >
                    <el-dropdown-item @click="handleEdit(data)"
                      ><i class="iconfont icon-bianji"></i
                      >编辑</el-dropdown-item
                    >
                    <el-dropdown-item @click="handleDelete(data)"
                      ><i class="iconfont icon-shanchu"></i
                      >删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="user-content" v-loading="userLoading">
      <div class="search-container">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="关键字查询">
            <el-input v-model="searchForm.name" :style="{width: '220px'}" clearable
              placeholder="请输入用户姓名" @keydown.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <common-table
        :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="cancelDepartForm"
      :close-on-click-modal="false" :close-on-press-escape="false"
    >
      <el-form :model="departFormData" ref="departForm" :rules="departRules" label-width="100">
        <el-form-item label="项目名称" prop="name">
            <el-input v-model="departFormData.name" />
        </el-form-item>
      </el-form>
      <template #footer>
          <div class="dialog-footer">
              <el-button @click="cancelDepartForm">取消</el-button>
              <el-button type="primary" @click="saveDepartForm">保存</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 userLoading = ref(false);
const treeData = ref([]);
const selectedNode = ref(null);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
let departFormData = ref({});
const departForm = ref();
// 表单验证规则
const departRules = {
  name: [
    { required: true, message: "请输入部门名称", trigger: "blur" }
  ]
};
// 新增部门
const handleAdd = () => {
  dialogTitle.value = "新增部门";
  dialogVisible.value = true;
};
// 添加子部门
const handleAddChild = (data) => {
  dialogTitle.value = "新增子部门";
  departFormData.value.parentId = data.id;
  dialogVisible.value = true;
}
const handleEdit = (data) => {
  departFormData.value = {...data};
  dialogTitle.value = "编辑部门";
  dialogVisible.value = true;
}
const handleDelete = (data) => {
  ElMessageBox.confirm(`确定删除${data.name}？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      proxy.$post({
        url: "/api/user/depart/deleteDepart",
        data: { id: data.id },
        callback: (data) => {
          ElMessage.success("删除成功");
          loadTreeData();
        },
        error: (err) => {
          ElMessage.error("删除失败:", err);
        },
      });
    });
}


const saveDepartForm = () => {
  departForm.value.validate(valid => {
    if (valid) {
      let url = departFormData.value.id ? "updateDepart" : "createDepart"
      proxy.$post({
        url: "/api/user/depart/" + url,
        data: departFormData.value,
        callback: (data) => {
          ElMessage.success(dialogTitle.value + "成功");
          cancelDepartForm();
          loadTreeData();
        },
        error: (err) => {
          ElMessage.error("组织添加失败:", err);
        },
      });
    }
  })
};
const cancelDepartForm = () => {
  departForm.value.resetFields();
  departFormData.value = {};
  dialogVisible.value = false;
};





// 处理树节点点击事件
const handleNodeClick = (data, node, element) => {
  selectedNode.value = data;
  handleUserData();
};

// 树形数据
const loadTreeData = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/user/depart/treeDepart",
    data: {
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    callback: (data) => {
      treeData.value = data;
      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: selectedNode.value.id,
      name: searchForm.value.name,
    },
    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("加载数据失败");
    },
  });
};
// 表格数据
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: "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: "enable",
    label: "状态",
    width: 100,
    slot: "enable",
    align: "center",
  },
];
const handleSearch = () => {
  currentPage.value = 1;
  handleUserData();
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  handleUserData();
};

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



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

<style scoped lang="less">
  @import "@/styles/manage.less";
.depart-manage {
  padding: 20px;
  background: rgba(157, 188, 218, 0.1);
  height: 100%;
  display: flex;
  // flex-direction: row;
  // box-sizing: border-box;
  .manage-left {
    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);
    width: 270px;
    display: flex;
    flex-direction: column;
  }
  .handle-btn{
    display: flex;
    justify-content: flex-end;
  }
  .tree-content {
    flex: 1;
    height: 0;
    margin-top: 20px;
  }
  .user-content {
    flex: 1;
    width: 0;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    padding: 20px 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    .search-container{
      padding: 0 20px;
    }
    .common-table{
        flex: 1;
        height: 0;
        display: flex;
        flex-direction: column;
        .table-container{
            flex: 1;
            height: 0;
            display: flex;
            flex-direction: column;
            .el-table{
                flex: 1;
                height: 0;
            }
        }
    }
  }
}
.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: #ecf5ff;
  color: #409eff;
  height: 40px;
  border-radius: 3px;
}
</style>
