<script setup lang="ts">
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "prosonDepartment"
});
import { ref, reactive, watch, nextTick, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import prosonEditDrawer from "./components/prosonEditDrawer.vue";
import newDepartment from "./components/newDepartment.vue";
import addPerson from "./components/addPerson.vue";
import personDetailsDrawer from "./components/personDetailsDrawer.vue";
import changeRole from "./components/changeRole.vue";
import { postListTree, postDelDept } from "@/api/department";
import { postOrganizationUserPage, getDeleteUserApi } from "@/api/userSetting";
import UserPageTable from "@/components/UserPageTable/index.vue";
import { Plus } from "@element-plus/icons-vue";

// 添加部门
const newDepartmentRef = ref(null);
const newDepartmentShow = ref(false);
// 编辑部门
const prosonEditDrawerRef = ref(null);
const prosonEditDrawerShow = ref(false);
// 添加人员
const addPersonDrawerRef = ref(null);
const addPersonDrawerShow = ref(false);
// 人员详情
const personDetailsDrawerRef = ref(null);
const personDetailsDrawerShow = ref(false);
// 配置角色
const changeRoleRef = ref(null);
const changeRoleShow = ref(false);
// 用户搜索
const realName = ref("");
const treeRef = ref();
// table表格
const UserTable = ref();
const dataTree = ref([]);
const deptList = ref({});
const defaultProps = {
  children: "childrenRes",
  label: "deptName"
};
// 添加部门弹窗
const addDepartment = () => {
  newDepartmentRef.value.open();
};
// 添加子部门
const adddeptChild = node => {
  newDepartmentRef.value.open(node);
};
// 查询部门树
const postListTreeApi = async () => {
  const { code, data } = await postListTree();
  if (code == 200) {
    console.log(data);
    if (data && data.length) {
      data[0].id = 1;
    }
    dataTree.value = data;
    console.log("dataTree", dataTree.value);
    let dataId = { data: "" };
    dataId.data = dataTree.value[0];
    nextTick(() => {
      handleNodeClick(dataId);
    });
  }
};
onMounted(() => {
  postListTreeApi();
  setTimeout(() => {
    nextTick(() => {
      selectedNodeId.value = dataTree.value[0].id;
    });
  }, 500);
});
// 删除人员
const deletePerson = row => {
  console.log(row);
  ElMessageBox.confirm("删除后不可恢复，确定要删除吗？", "确认删除该人员吗？", {
    type: "warning"
  })
    .then(() => {
      getDeleteUserApi(row.userCode, () =>
        UserTable.value.handleCurrentChange(1)
      );
    })
    .catch(() => {
      // catch error
    });
};
// 编辑部门弹窗
const editDepartment = node => {
  prosonEditDrawerRef.value.open(node);
};
// 删除部门
const postDelDeptApi = async data => {
  const { code } = await postDelDept(data);
  if (code == 200) {
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    postListTreeApi();
  }
};
const deleteDepartment = node => {
  console.log("删除部门", node);
  ElMessageBox.confirm(
    "请先移除部门内的所有人员再进行删除部门操作",
    "确认删除该部门吗？",
    {
      type: "warning"
    }
  )
    .then(() => {
      postDelDeptApi(node.data);
    })
    .catch(() => {
      // catch error
    });
};
// 添加人员弹窗
const AddPerson = () => {
  // postOrganizationUserPageApi

  addPersonDrawerRef.value.open(
    deptList.value,
    UserTable.value.postOrganizationUserPageApi
  );
};
// 编辑
const personDetails = row => {
  personDetailsDrawerRef.value.open(
    row,
    UserTable.value.postOrganizationUserPageApi
  );
  // console.log(row);
};
const ChangeRole = row => {
  changeRoleRef.value.open(row, "用户");
};
// 部门配置角色
const editRoles = row => {
  changeRoleRef.value.open(row);
};
// 人员表格
const tableData = reactive({
  list: [],
  params: {
    pageNumber: 1,
    pageSize: 10,
    organizationCode: "",
    organizationType: "dept"
  }
});
const selectedNodeId = ref();
const handleNodeClick = data => {
  selectedNodeId.value = data.id;
  // nextTick(() => {
  //   const nodeElement = treeRef.value.$el.querySelector(`[data-node-key="${data.id}"]`);
  //   if (nodeElement) {
  //     nodeElement.classList.add('custom-node-class'); // 在此修改类名
  //   }
  // });
  Object.assign(deptList.value, data.data);
  UserTable.value.handleNodeClick(data.data, "dept");
  // tableData.params.organizationCode = data.deptCode;
  // postOrganizationUserPageApi();
};
const postOrganizationUserPageApi = async () => {
  const { code, data } = await postOrganizationUserPage(tableData.params);
  if (code == 200) {
    console.log(data);
    tableData.list = data.records;
    // tableData.value = res.records;
    // total.value = res.total;
  }
};
const handleSizeChange = val => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = val => {
  console.log(`current page: ${val}`);
};
const filterNode = (value: string, data: any) => {
  if (!value) return true; // 如果没有过滤关键词，显示所有节点
  return data.deptName && data.deptName.includes(value); // 使用 deptName 进行匹配
};
watch(realName, val => {
  treeRef.value!.filter(val);
});
// function handleDropdownClick(node) {
//   // 您的逻辑
//   console.log(1111,node)
// }
</script>

<template>
  <div class="flex w-full h-full">
    <!-- 编辑部门 -->
    <prosonEditDrawer
      ref="prosonEditDrawerRef"
      v-model="prosonEditDrawerShow"
      @handleClick="postListTreeApi"
    />
    <!-- 添加部门 -->
    <newDepartment
      ref="newDepartmentRef"
      v-model="newDepartmentShow"
      @handleClick="postListTreeApi"
    />
    <!-- 添加人员 -->
    <addPerson ref="addPersonDrawerRef" v-model="addPersonDrawerShow" />
    <!-- 人员详情 -->
    <personDetailsDrawer
      ref="personDetailsDrawerRef"
      v-model="personDetailsDrawerShow"
    />
    <!-- 配置角色 -->
    <changeRole ref="changeRoleRef" v-model="changeRoleShow" />
    <!-- 主体内容  @node-click="handleNodeClick" -->
    <div class="box-left">
      <el-input
        v-model="realName"
        placeholder="搜索"
        class="mb-2"
        clearable
        :prefix-icon="Search"
      />
      <el-tree
        ref="treeRef"
        class="m-2 mr-8 infinite-list"
        style="max-width: 600px; max-height: 500px; overflow-y: auto"
        :data="dataTree"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        highlight-current
        :filter-node-method="filterNode"
      >
        <template #default="{ node }">
          <div
            class="flex-1 flex justify-between items-center"
            :class="{ 'custom-node-class': selectedNodeId === node.id }"
          >
            <div class="w-[120px] ellipsis" @click="handleNodeClick(node)">
              {{ node.label }}
            </div>
            <el-dropdown trigger="click">
              <span>
                <el-icon>
                  <Operation />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu class="setting">
                  <Auth :value="['编辑部门']">
                    <el-dropdown-item @click="editDepartment(node)">
                      编辑部门
                    </el-dropdown-item>
                  </Auth>
                  <Auth :value="['添加子部门']">
                    <el-dropdown-item @click="adddeptChild(node)">
                      添加子部门
                    </el-dropdown-item>
                  </Auth>
                  <Auth :value="['配置角色']">
                    <el-dropdown-item @click="editRoles(node)">
                      配置角色
                    </el-dropdown-item>
                  </Auth>
                  <Auth :value="['删除']">
                    <el-dropdown-item @click="deleteDepartment(node)">
                      <el-link type="danger">删除</el-link>
                    </el-dropdown-item>
                  </Auth>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-tree>
      <Auth :value="['新建部门']">
        <el-button
          class="w-full mt-4"
          type="primary"
          plain
          :icon="Plus"
          @click="addDepartment"
          >新增部门</el-button
        >
      </Auth>
    </div>
    <div class="box-right">
      <UserPageTable ref="UserTable">
        <template #add-button>
          <Auth :value="['添加成员']">
            <el-button type="primary" @click="AddPerson">新建人员</el-button>
          </Auth>
        </template>
        <template #actions="{ row }">
          <Auth :value="['编辑成员']">
            <el-dropdown trigger="click" class="mr-2">
              <el-icon @click="personDetails(row)">
                <View />
              </el-icon>
            </el-dropdown>
          </Auth>
          <el-dropdown trigger="click">
            <el-icon>
              <Operation />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu class="setting">
                <Auth :value="['删除成员']">
                  <el-dropdown-item>
                    <el-link type="danger" @click="deletePerson(row)"
                      >删除</el-link
                    >
                  </el-dropdown-item>
                </Auth>
                <Auth :value="['配置角色']">
                  <el-dropdown-item @click="ChangeRole(row)">
                    配置角色
                  </el-dropdown-item>
                </Auth>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </UserPageTable>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.box-left {
  width: 25%;
  // border: 1px solid red;
  height: 100%;
  padding: 10px 20px;
  border-right: 1px solid #999;
}

.box-right {
  width: 70%;
  height: 100%;
  padding: 10px 20px;
}

.ellipsis {
  /* 防止文本换行 */
  overflow: hidden;

  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  // border: 1px solid red;
  white-space: nowrap;

  /* 用省略号表示被截断的部分 */
}

// ::v-deep .el-dropdown {
//   line-height: 1;
// }
// ::v-deep .el-tree-node__expand-icon {
//   line-height: 10px;
//   border: 1px solid red;
// }
// ::v-deep(
//     .el-tree--highlight-current
//       .el-tree-node.is-current
//       > .el-tree-node__content
//   ) {
//   color: #0052d9;
//   background-color: #ecf2fe !important;
// }
.custom-node-class {
  color: #0052d9;
  background-color: #ecf2fe !important;
}

/* 隐藏滚动条 */
.infinite-list::-webkit-scrollbar {
  display: none;

  /* 对于 Webkit 浏览器（Chrome, Safari等） */
}
</style>
