<template>
  <el-dialog title="选择人员" :modelValue="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="true"
          :show-index="true"
          :table-height="tableHeight"
          :multiSelect="multiSelect"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #operation="{ 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 #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 setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import CustomTable from '@/components/CustomTable.vue'
import { systemApi } from '@/utils/api'

const props = defineProps({
  multiSelect: {
    type: Boolean,
    default: true,
  },
  dialogVisible: {
    type: Boolean,
    required: true,
  },
  currentSelectedUser: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['update:dialogVisible', 'close', 'confirm'])

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedUsers = ref([])
const currentDepartment = ref('')
const tableHeight = ref(350) // 设置一个合适的高度

// 组织树假数据
const treeData = ref([])

const defaultProps = {
  children: 'children',
  label: 'label',
}

// 表格列定义
const columns = [
  { prop: 'nickName', label: '姓名' },
  { prop: 'dept', label: '部门', type: 'status', callback: (data, row) => data?.deptName },
  { prop: 'roles', label: '角色', type: 'status', callback: (data, row) => data.map(ele => ele.roleName).join(',') },
]


const userData = ref([])

const handleNodeClick = data => {
  currentDepartment.value = data.id
  currentPage.value = 1
  fetchUserList()
}

const handleCurrentChange = val => {
  currentPage.value = val
  fetchUserList()
}

const handleSizeChange = val => {
  pageSize.value = val
  fetchUserList()
}

const handleClose = () => {
  emit('update:dialogVisible', false)
  emit('close')
}

const handleConfirm = () => {
  emit('confirm', selectedUsers.value)
  handleClose()
}
const customTableRef = ref(null)
const isInternalChange = ref(false)

const handleSelectionChange = val => {
  if (isInternalChange.value) return

  if (!props.multiSelect) {
    isInternalChange.value = true
    nextTick(() => {
      if (val.length > 0) {
        const lastSelected = val[val.length - 1]
        selectedUsers.value = [lastSelected]
        customTableRef.value?.clearSelection()
        customTableRef.value?.toggleRowSelection(lastSelected, true)
      } else {
        selectedUsers.value = []
      }
      isInternalChange.value = false
    })
  } else {
    selectedUsers.value = val
  }
}

// 监听 currentSelectedUser 变化
watch(
  () => props.currentSelectedUser,
  newVal => {
    isInternalChange.value = true
    nextTick(() => {
      selectedUsers.value = newVal
      if (customTableRef.value) {
        customTableRef.value.clearSelection()
        newVal.forEach(user => {
          const row = userData.value.find(item => item.userId === user.userId)
          if (row) {
            customTableRef.value.toggleRowSelection(row, true)
          }
        })
      }
      isInternalChange.value = false
    })
  },
  { immediate: true, deep: true },
)

// 在组件挂载时设置初始选中状态
onMounted(() => {
  nextTick(() => {
    if (customTableRef.value && props.currentSelectedUser.length > 0) {
      customTableRef.value.clearSelection()
      props.currentSelectedUser.forEach(user => {
        const row = userData.value.find(item => item.userId === user.userId)
        if (row) {
          customTableRef.value.toggleRowSelection(row, true)
        }
      })
    }
  })
})

const fetchUserList = async () => {
  // 在实际应用中，这里应该调用后端 API
  const response = await systemApi.getUserList({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    deptId: currentDepartment.value,
  })
  userData.value = response.rows
  total.value = response.total
}
const fetchTreeData = async () => {
  const response = await systemApi.getDeptTree()
  treeData.value = response.data
}
// 可以在组件挂载时调用这个方法获取初始数据
onMounted(() => {
  fetchTreeData()
  fetchUserList()
})
</script>

<style 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;
}

: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;
}
</style>
