<template>
  <el-dialog title="人员选择"
    v-model="showFlag"
    :modal= false
    width="80%"
    center
  >
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="treeRef"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="工号" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入工号"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div style="min-height: 30px;line-height: 30px;">
          <span>已选人员：</span>
          <el-tag v-for="user in allSelectedUsers" :key="user.userId" closable @close="removeSelected(user)">{{ user.userName }} ({{ user.nickName }})</el-tag>
        </div>
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" ref="tableRef">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="工号" align="center" key="userName" prop="userName" v-if="columns[0].visible" :show-overflow-tooltip="true" />
          <el-table-column label="姓名" align="center" key="nickName" prop="nickName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <template #footer>
        <div class="dialog-footer">
            <el-button type="primary" @click="confirmSelect">确 定</el-button>
            <el-button @click="handleCancel">取 消</el-button>
        </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, watch, onMounted } from 'vue'
import { listUserData } from "@/api/system/user";
import { treeselectNoDataScope } from "@/api/system/dept";

// 定义v-model
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  preSelectedUsers: {
    type: Array,
    default: () => []
  },
  sortDeptId: {
    type: [String, Number],
    default: undefined
  }
})

const emit = defineEmits(['update:modelValue', 'onSelected'])

// 获取组件实例
const { proxy } = getCurrentInstance()

// 定义字典
const {
  sys_normal_disable,
  sys_user_sex
} = proxy.useDict("sys_normal_disable", "sys_user_sex" )

// 定义变量
const showFlag = ref(false)
const loading = ref(true)
const ids = ref([])
const selectedRows = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const userList = ref([])
const title = ref("")
const deptOptions = ref(undefined)
const open = ref(false)
const deptName = ref(undefined)
const dateRange = ref([])
const postOptions = ref([])
const roleOptions = ref([])
const treeRef = ref(null)
const queryRef = ref(null)
const tableRef = ref(null)
const allSelectedUsers = ref([])
const isUpdatingData = ref(false)
const isRestoringSelection = ref(false)

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  showFlag.value = newVal
  // 当对话框打开时，清除之前的选择，并设置预选中
  if (newVal && tableRef.value) {
    tableRef.value.clearSelection()
    ids.value = []
    selectedRows.value = []
    allSelectedUsers.value = JSON.parse(JSON.stringify(props.preSelectedUsers || []))
    // 手动回显选中
    nextTick(() => {
      setTimeout(() => {
        isRestoringSelection.value = true;
        userList.value.forEach(row => {
          if (allSelectedUsers.value.some(sel => sel.userId === row.userId)) {
            tableRef.value.toggleRowSelection(row, true);
          }
        });
        isRestoringSelection.value = false;
      }, 0);
    });
  }
})

// 监听showFlag变化
watch(showFlag, (newVal) => {
  emit('update:modelValue', newVal)
  // 只有当对话框关闭时，才重置选择
  if (!newVal && tableRef.value) {
    tableRef.value.clearSelection()
    ids.value = []
    selectedRows.value = []
    allSelectedUsers.value = []
  }
})

// 默认属性
const defaultProps = {
  children: "children",
  label: "label"
}

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  nickName: undefined,
  status: undefined,
  deptId: undefined,
  sortDeptId: props.sortDeptId,
})

// 列信息
const columns = ref([
  { key: 0, label: `工号`, visible: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `部门`, visible: true },
  { key: 3, label: `状态`, visible: true },
  { key: 4, label: `创建时间`, visible: true }
])

// 监听部门名称变化
watch(deptName, (val) => {
  treeRef.value.filter(val);
})

// 监听sortDeptId变化
watch(() => props.sortDeptId, (newVal) => {
  queryParams.sortDeptId = newVal;
  getList();
})

// 监听userList变化，回显选中
watch(userList, () => {
  nextTick(() => {
    setTimeout(() => {
      isRestoringSelection.value = true;
      userList.value.forEach(row => {
        if (allSelectedUsers.value.some(sel => sel.userId === row.userId)) {
          tableRef.value.toggleRowSelection(row, true);
        }
      });
      isRestoringSelection.value = false;
    }, 0);
  });
}, { immediate: true })

// 组件挂载时查询数据
onMounted(() => {
  getList();
  getTreeselect();
})

/** 查询用户列表 */
function getList() {
  loading.value = true;
  const cleanParams = { ...queryParams };
  // 处理头尾空格，只忽略完全空的输入
  if (cleanParams.userName) {
    cleanParams.userName = cleanParams.userName.trim();
    if (cleanParams.userName === '') delete cleanParams.userName;
  }
  if (cleanParams.nickName) {
    cleanParams.nickName = cleanParams.nickName.trim();
    if (cleanParams.nickName === '') delete cleanParams.nickName;
  }
  if (!cleanParams.deptId) delete cleanParams.deptId;
  listUserData(proxy.addDateRange(cleanParams, dateRange.value)).then(response => {
      isUpdatingData.value = true;
      userList.value = response.rows;
      total.value = response.total;
      loading.value = false;
      nextTick(() => {
        isUpdatingData.value = false;
      });
    }
  );
}

/** 查询部门下拉树结构 */
function getTreeselect() {
  let data = {levelNoEqual:'4'};
  treeselectNoDataScope(data).then(response => {
    deptOptions.value = response.data;
  });
}

// 筛选节点
function filterNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

// 节点单击事件
function handleNodeClick(data) {
  queryParams.deptId = data.id;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  if (isUpdatingData.value || isRestoringSelection.value) return;
  ids.value = selection.map(item => item.userId);
  selectedRows.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // 更新allSelectedUsers
  // 只移除当前页中未选中的，其他页的保留
  allSelectedUsers.value = allSelectedUsers.value.filter(user => {
    if (userList.value.some(u => u.userId === user.userId)) {
      // 当前页的用户，只有在 selection 中才保留
      return selection.some(sel => sel.userId === user.userId);
    } else {
      // 其他页的用户，保留
      return true;
    }
  });
  // 添加新选中的
  selection.forEach(sel => {
    if (!allSelectedUsers.value.some(u => u.userId === sel.userId)) {
      allSelectedUsers.value.push(sel);
    }
  });
}

//确定选中
function confirmSelect(){
    if(allSelectedUsers.value == null || allSelectedUsers.value.length == 0){
        proxy.$notify({
            title:'提示',
            type:'warning',
            message: '请至少选择一条数据!'
        });
        return;
    }
    emit('onSelected', allSelectedUsers.value);
    allSelectedUsers.value = [];
    showFlag.value = false;
}

// 取消按钮
function handleCancel() {
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  ids.value = []
  selectedRows.value = []
  allSelectedUsers.value = []
  showFlag.value = false
}

// 移除选中人员
function removeSelected(user) {
  allSelectedUsers.value = allSelectedUsers.value.filter(u => u.userId !== user.userId);
  // 取消表格中的选中，如果在当前页
  if (tableRef.value) {
    const row = userList.value.find(u => u.userId === user.userId);
    if (row) {
      tableRef.value.toggleRowSelection(row, false);
    }
  }
}
</script>
