<template>
  <el-dialog
    title="选择人员"
    :visible="dialogVisible"
    width="50%"
    @close="handleClose"
  >
    <div class="select-user-container">
      <div class="org-tree">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
        />
      </div>
      <div class="user-list">
        <CustomTable
          ref="customTableRef"
          :columns="columns"
          :tableData="userData"
          :total="total"
          :show-selection="showSelection"
          :show-index="true"
          :table-height="tableHeight"
          :multiSelect="multiSelect"
          :selectable="selectable"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @selected="selectRow"
          @selectAll="selectAll"
          rowKey="userId"
          :rowClick="
            (row) => {
              rowClick(row);
            }
          "
          maxHeight="380"
          :highligt="highligt"
        >
          <template slot="operation" slot-scope="{ row }">
            <div class="operation-buttons">
              <el-button text type="primary" @click="handleEdit(row)"
                >编辑</el-button
              >
              <el-button text type="primary" @click="showTimesheet(row)"
                >工作日志</el-button
              >
              <el-button text type="danger" @click="handleDelete(row)"
                >删除</el-button
              >
            </div>
          </template>
        </CustomTable>
      </div>
    </div>
    <template slot="footer">
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import CustomTable from "@/components/CustomTable.vue";
import { systemApi } from "@/utils/api";

export default {
  components: {
    CustomTable,
  },
  props: {
    multiSelect: {
      type: Boolean,
      default: true,
    },
    dialogVisible: {
      type: Boolean,
      default: true,
    },
    currentSelectedUser: {
      type: Array,
      default: () => [],
    },
    currentSelectedUserName: {
      type: Array,
      default: () => [],
    },
    showSelection: {
      type: Boolean,
      default: false,
    },
    highligt: {
      type: Boolean,
      default: true,
    },
    selectable: {
      type: Function,
      default: () => true,
    },
  },
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedUsers: [],
      currentDepartment: "",
      tableHeight: "350", // 设置一个合适的高度
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      columns: [
        { prop: "nickName", label: "姓名" },
        {
          prop: "dept",
          label: "部门",
          type: "status",
          callback: (data) => data?.deptName,
        },
        {
          prop: "roles",
          label: "角色",
          type: "status",
          callback: (data) => data.map((ele) => ele.roleName).join(","),
        },
      ],
      userData: [],
      isInternalChange: false,
      selectAllData: [],
    };
  },
  emits: ["close", "confirm"],
  methods: {
    handleNodeClick(data) {
      this.currentDepartment = data.id;
      this.currentPage = 1;
      this.fetchUserList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchUserList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchUserList();
    },
    handleClose() {
      this.$emit("close");
    },
    handleConfirm() {
      if (!this.showSelection) this.$emit("confirm", this.selectedUsers);
      else
        this.$emit(
          "confirm",
          this.selectedUsers.map((ele, index) => ({
            userId: ele.userId,
            nickName: ele.nickName,
          }))
        );

      this.handleClose();
    },
    handleSelectionChange(val) {
      if (this.isInternalChange) return;
      if (!this.multiSelect) {
        this.isInternalChange = true;
        this.$nextTick(() => {
          if (val.length > 0) {
            const lastSelected = val[val.length - 1];
            this.selectedUsers = [lastSelected];
            this.$refs.customTableRef.clearSelection();
            this.$refs.customTableRef.toggleRowSelection(lastSelected, true);
          } else {
            this.selectedUsers = [];
          }
          this.isInternalChange = false;
        });
      } else {
        // this.selectedUsers = val;
      }
    },
    selectRow({ arr, row }) {
      if (!row) return;
      if (this.selectedUsers.filter((ele) => ele.userId == row.userId).length) {
        this.selectedUsers = this.selectedUsers.filter(
          (ele) => ele.userId != row.userId
        );
      } else {
        this.selectedUsers.push({ userId: row.userId, nickName: row.nickName });
      }
    },
    selectAll(arr) {
      let filterArr = this.selectAllData.filter((ele) =>
        !arr.some((item) => item.userId == ele.userId)
      );
      console.log(filterArr,11);
      
      arr.forEach((ele) => {
        if (
          !this.selectedUsers.filter((item) => item.userId == ele.userId).length
        )
          this.selectRow({ row: ele });
      });
      filterArr.forEach((ele) => {

        this.selectRow({ row: ele});
      });


    },
    fetchUserList: async function () {
      const response = await systemApi.getUserList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        deptId: this.currentDepartment,
      });
      this.userData = response.rows;
      this.total = response.total;
    },
    fetchTreeData: async function () {
      const response = await systemApi.getDeptTree();
      this.treeData = response.data;
    },
    currentRow(val) {
      this.selectedUsers = [val];
    },
    rowClick(row) {
      if (!this.showSelection) {
        if (row.userId == this.selectedUsers[0]?.userId)
          this.$refs.customTableRef.$refs.elTableRef.setCurrentRow();
        else this.selectedUsers = [row];
      }
    },
  },
  watch: {
    currentSelectedUser: {
      handler(newVal) {
        this.$nextTick(() => {
          if (!this.showSelection) {
            let row = this.userData.find(
              (ele) => ele.userId == newVal[0]?.userId
            );
            if (row) {
              this.$refs.customTableRef?.setCurrentRow(row);
              this.selectedUsers = [row];
            } else {
              this.selectedUsers = [];
              this.$refs.customTableRef?.setCurrentRow();
            }
          } else {
            if (!newVal.length) {
              this.selectedUsers = [];
              this.$refs.customTableRef?.clearSelection();
            } else {
              // this.$refs.customTableRef?.clearSelection();
              this.selectedUsers = [];
              newVal.forEach((item, index) => {
                this.selectedUsers.push({
                  userId: item,
                  nickName: this.currentSelectedUserName[index],
                });
                let row = this.userData.find((ele) => ele.userId == item);
                if (row) {
                  this.selectAllData.push(row);
                  this.$refs.customTableRef?.toggleRowSelection(row, true);
                }
              });
            }
          }
        });
      },
      immediate: true,
      deep: true,
    },
    userData: {
      handler(newVal) {
        this.$nextTick(() => {
          if (!this.showSelection) {
            let row = this.userData.find(
              (ele) => ele.userId == this.currentSelectedUser[0]?.userId
            );
            if (row) {
              this.selectedUsers = [row];
              this.$refs.customTableRef?.setCurrentRow(row);
            }
          } else {
            this.selectAllData = [];
            this.currentSelectedUser.forEach((item) => {
              let row = newVal.find((ele) => ele.userId == item);
              if (row) {
                this.selectAllData.push(row);

                this.$refs.customTableRef?.toggleRowSelection(row, true);
              }
            });
          }
        });
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    this.fetchTreeData();
    this.fetchUserList();
  },
};
</script>

<style lang="scss" scoped>
.select-user-container {
  display: flex;
  height: 400px;
}

.org-tree {
  width: 200px;
  border-right: 1px solid #dcdfe6;
  padding-right: 20px;
  overflow-y: auto;
}

.user-list {
  flex: 1;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
}

::v-deep .el-dialog__footer {
  padding: 20px 20px 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  width: 100%;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

.dialog-footer .el-button:first-child {
  margin-left: 0;
}
::v-deep .el-table {
  max-height: 360px !important;
}
::v-deep tr.el-table__row.current-row .el-table__cell {
  background-color: #409eff !important;
  color: #fff;
}
</style>