<template>
  <el-dialog
    title="指派任务"
    :visible.sync="visible"
    width="1200px"
    :close-on-click-modal="false"
    custom-class="assign-task-dialog"
  >
    <el-form ref="assignForm" :model="assignForm" label-width="120px">
      <el-row class="dialog-content">
        <el-col :span="12">
          <div class="tree-title">选择部门</div>
          <div class="tree-container">
            <div class="tree-header">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索部门"
                @input="filterDeptTree"
              />
            </div>
            <div class="tree-wrapper">
              <el-tree
                :data="filteredDeptTree"
                :props="deptTreeProps"
                @node-click="handleDeptNodeClick"
                :expand-on-click-node="false"
                :default-expand-all="true"
                :default-expanded-keys="defaultExpandedKeys"
                :render-content="renderTreeContent"
              />
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="user-title">选择人员</div>
          <div class="user-container">
            <div class="user-header">
              <el-input
                v-model="userSearchKeyword"
                placeholder="搜索人员"
                @input="filterUserList"
              />
            </div>
            <div class="user-wrapper">
              <!-- 移除 el-checkbox-group -->
              <el-table
                ref="userTable"
                :data="filteredUserList"
                style="width: 100%"
                border
                fit
                highlight-current-row
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="名称" prop="userName"></el-table-column>
                <el-table-column label="电话号码" prop="phonenumber"></el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="assignTask">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { listUser } from "@/api/system/user";
import { getAllTree } from "@/api/system/dept";
import { addByUser } from "@/api/task/branch";


export default {
  name: "AssignTaskDialog",
  data() {
    return {
      visible: false,
      assignForm: {
        deptId: "",
        userId: "",
      },
      deptTree: [],
      filteredDeptTree: [],
      deptTreeProps: {
        label: "deptName",
        children: "children",
      },
      defaultExpandedKeys: [],
      selectedDept: null,
      userList: [],
      filteredUserList: [],
      searchKeyword: "",
      userSearchKeyword: "",
      // 存储选中的用户列表
      selectedUsers: [],
      taskIds: [],
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.fetchDeptTree();
      }
    },
    searchKeyword(newVal) {
      this.filterDeptTree();
    },
    userSearchKeyword(newVal) {
      this.filterUserList();
    },
  },
  methods: {
    async fetchDeptTree() {
      try {
        const response = await getAllTree();
        this.deptTree = JSON.parse(JSON.stringify(response));
        this.filteredDeptTree = JSON.parse(JSON.stringify(response));
        this.defaultExpandedKeys = this.getAllDeptIds();
      } catch (error) {
        console.error("获取部门树失败", error);
      }
    },
    async handleDeptNodeClick(node, e) {
      this.selectedDept = node;
      this.assignForm.deptId = node.deptId;
      try {
        const response = await listUser({ deptId: node.deptId });
        this.userList = response.rows;
        this.filteredUserList = JSON.parse(JSON.stringify(this.userList));
        // 清空之前的选择
        this.$refs.userTable && this.$refs.userTable.clearSelection();
        this.selectedUsers = [];
      } catch (error) {
        console.error("获取人员列表失败", error);
      }
    },
    open(taskIds) {
      this.taskIds = taskIds;
      this.visible = true;
      // 清空表格的选中状态
      this.$refs.userTable && this.$refs.userTable.clearSelection();
      // 清空部门搜索输入框内容
      this.searchKeyword = '';
      // 清空人员搜索输入框内容
      this.userSearchKeyword = '';
      // 清空过滤后的部门树和人员列表（可选，根据实际需求）
      this.filteredDeptTree = [];
      this.filteredUserList = [];
    },
    assignTask() {
      const userIds = this.selectedUsers.map(user => user.userId);
      addByUser({ userIds, taskIds: this.taskIds })
        .then(() => {
          // 请求完成后触发 reload-data 事件
          this.$emit('reload-data');
        })
        .catch((error) => {
          console.error('任务指派失败', error);
        })
        .finally(() => {
          this.visible = false;
        });
    },
    getAllDeptIds() {
      const deptIds = [];
      const traverse = (nodes) => {
        nodes.forEach((node) => {
          deptIds.push(node.deptId);
          if (node.children && node.children.length > 0) {
            traverse(node.children);
          }
        });
      };
      traverse(this.deptTree);
      return deptIds;
    },
    renderTreeContent(h, { node, data, store }) {
      return <span>{data.deptName}</span>;
    },
    filterDeptTree() {
      if (!this.searchKeyword) {
        this.filteredDeptTree = JSON.parse(JSON.stringify(this.deptTree));
        return;
      }
      const filterNodes = (nodes) => {
        return nodes.filter((node) => {
          if (node.deptName.includes(this.searchKeyword)) {
            if (node.children) {
              node.children = filterNodes(node.children);
            }
            return true;
          }
          if (node.children) {
            const filteredChildren = filterNodes(node.children);
            if (filteredChildren.length > 0) {
              node.children = filteredChildren;
              return true;
            }
          }
          return false;
        });
      };
      this.filteredDeptTree = filterNodes(JSON.parse(JSON.stringify(this.deptTree)));
    },
    filterUserList() {
      if (!this.userSearchKeyword) {
        this.filteredUserList = JSON.parse(JSON.stringify(this.userList));
      } else {
        this.filteredUserList = this.userList.filter((user) =>
          user.userName.includes(this.userSearchKeyword) ||
          (user.phonenumber && user.phonenumber.includes(this.userSearchKeyword))
        );
      }
      // 清空之前的选择
      this.$refs.userTable && this.$refs.userTable.clearSelection();
      this.selectedUsers = [];
    },
    // 处理表格选择变化事件
    handleSelectionChange(selection) {
      this.selectedUsers = selection;
    }
  },
};
</script>

<style scoped>
.tree-title,
.user-title {
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 16px;
}

.tree-container,
.user-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  width: 100%;
  height: 400px;
  display: flex;
  flex-direction: column;
}

.tree-header,
.user-header {
  margin-bottom: 10px;
}

.tree-header .el-input,
.user-header .el-input {
  width: 100%;
}

.tree-wrapper,
.user-wrapper {
  overflow-y: auto;
  flex: 1;
}

.assign-task-dialog {
  max-width: 1200px !important;
}
</style>
