<template>
  <div>
    <a-row :gutter="20">
      <!--部门数据-->
      <a-col :span="6" :xs="24">
        <div class="head-container">
          <a-input
            v-model:value="deptName"
            placeholder="请输入部门名称"
            allow-clear
            size="small"
            style="margin-bottom: 20px"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </div>
        <div class="head-container">
          <a-tree
            :tree-data="deptOptions"
            :replace-fields="{ children: 'children', title: 'label', key: 'id' }"
            :filter-tree-node="filterNode"
            ref="tree"
            default-expand-all
            :selected-keys="selectedKeys"
            @select="handleNodeClick"
          />
        </div>
      </a-col>
      <!--用户数据-->
      <a-col :span="18" :xs="24">
        <a-form
          :model="queryParams"
          layout="inline"
          class="search-form"
          v-show="showSearch"
        >
          <a-form-item label="用户名称" name="userName">
            <a-input
              v-model:value="queryParams.userName"
              placeholder="请输入用户名称"
              allow-clear
              style="width: 150px"
              @press-enter="handleQuery"
            />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleQuery">
                <template #icon><SearchOutlined /></template>
                搜索
              </a-button>
              <a-button @click="resetQuery">
                <template #icon><RedoOutlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
        
        <a-table
          v-if="checkType === 'multiple'"
          ref="dataTable"
          :loading="loading"
          :dataSource="userList"
          :rowKey="record => record.userId"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            type: 'checkbox',
            preserveSelectedRowKeys: true
          }"
          :pagination="false"
        >
          <a-table-column 
            v-for="column in visibleColumns" 
            :key="column.key" 
            :title="column.label" 
            :dataIndex="getDataIndex(column.key)" 
            :ellipsis="true"
            :width="column.key === 4 ? 120 : undefined"
            align="center"
          >
            <template #bodyCell="{ text }">
              <span v-if="text">{{ text }}</span>
            </template>
          </a-table-column>
        </a-table>

        <a-table
          v-if="checkType === 'single'"
          :loading="loading"
          :dataSource="userList"
          :rowKey="record => record.userId"
          :pagination="false"
          @rowClick="handleSingleUserSelect"
        >
          <a-table-column key="selection" width="55" align="center">
            <template #bodyCell="{ record }">
              <a-radio 
                v-model:checked="radioSelected" 
                :value="record.userId"
                @change="() => handleSingleUserSelect(record)"
              ></a-radio>
            </template>
          </a-table-column>
          <a-table-column 
            v-for="column in visibleColumns" 
            :key="column.key" 
            :title="column.label" 
            :dataIndex="getDataIndex(column.key)" 
            :ellipsis="true"
            :width="column.key === 4 ? 120 : undefined"
            align="center"
          >
            <template #bodyCell="{ text }">
              <span v-if="text">{{ text }}</span>
            </template>
          </a-table-column>
        </a-table>

        <div class="pagination-container">
          <a-pagination
            v-show="total > 0"
            v-model:current="queryParams.pageNum"
            v-model:pageSize="queryParams.pageSize"
            :total="total"
            :pageSizeOptions="['5', '10']"
            show-less-items
            show-size-changer
            @change="getList"
            @showSizeChange="getList"
          />
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, computed } from 'vue'
import { SearchOutlined, RedoOutlined } from '@ant-design/icons-vue'
import { listUser, deptTreeSelect } from "@/api/system/user"
import { StrUtil } from '../../common/StrUtil'
import type { TreeProps, TableProps } from 'ant-design-vue'

interface UserItem {
  userId: number
  userName: string
  nickName: string
  dept?: {
    deptName: string
  }
  phonenumber: string
  status?: string
  createTime?: string
}

interface DeptItem {
  id: number
  label: string
  children?: DeptItem[]
}

interface QueryParams {
  pageNum: number
  pageSize: number
  userName?: string
  phonenumber?: string
  status?: string
  deptId?: number
}

interface ColumnItem {
  key: number
  label: string
  visible: boolean
}

interface Props {
  selectValues?: number | string | number[] | string[]
  checkType?: 'single' | 'multiple'
}

const props = withDefaults(defineProps<Props>(), {
  selectValues: null,
  checkType: 'multiple'
})

const emit = defineEmits<{
  (e: 'handleUserSelect', selection: UserItem | UserItem[]): void
}>()

// 响应式数据
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const userList = ref<UserItem[]>([])
const deptOptions = ref<DeptItem[]>([])
const deptName = ref('')
const selectedKeys = ref<number[]>([])
const radioSelected = ref<number | string | null>(null)
const selectedRowKeys = ref<(number | string)[]>([])
const dataTable = ref()
const tree = ref()

// 查询参数
const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  userName: undefined,
  phonenumber: undefined,
  status: undefined,
  deptId: undefined
})

// 列信息
const columns = ref<ColumnItem[]>([
  { 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 },
  { key: 5, label: '状态', visible: false },
  { key: 6, label: '创建时间', visible: false }
])

// 计算可见的列
const visibleColumns = computed(() => {
  return columns.value.filter(col => col.visible)
})

// 获取数据索引
const getDataIndex = (key: number) => {
  const dataIndexMap: { [key: number]: string } = {
    0: 'userId',
    1: 'userName',
    2: 'nickName',
    3: 'dept.deptName',
    4: 'phonenumber'
  }
  return dataIndexMap[key] || ''
}

// 监听部门名称变化
watch(deptName, (val) => {
  if (tree.value) {
    tree.value.filterTreeNodes(val)
  }
})

// 监听selectValues变化
watch(() => props.selectValues, (newVal) => {
  if (StrUtil.isNotBlank(newVal)) {
    if (typeof newVal === 'number' || typeof newVal === 'string') {
      radioSelected.value = newVal
    } else if (Array.isArray(newVal)) {
      selectedRowKeys.value = newVal
    }
  }
}, { immediate: true })

// 监听userList变化（多选模式下的回显）
watch(userList, (newVal) => {
  if (props.checkType === 'multiple' && selectedRowKeys.value.length > 0 && newVal.length > 0) {
    nextTick(() => {
      // Ant Design Table 会自动处理选中状态
    })
  }
})

// 生命周期
onMounted(() => {
  getList()
  getDeptTree()
})

// 筛选节点
const filterNode: TreeProps['filterTreeNode'] = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

// 节点单击事件
const handleNodeClick: TreeProps['onSelect'] = (selectedKeys, { node }) => {
  const data = node as any
  queryParams.deptId = data.key
  handleQuery()
}

// 多选选择变化
const onSelectChange: TableProps['rowSelection']['onChange'] = (selectedKeys) => {
  selectedRowKeys.value = selectedKeys as (number | string)[]
  const selectedRows = userList.value.filter(item => selectedKeys.includes(item.userId))
  emit('handleUserSelect', selectedRows)
}

/** 查询用户列表 */
const getList = async () => {
  try {
    loading.value = true
    const response = await listUser(queryParams)
    userList.value = response.rows
    total.value = response.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 查询部门下拉树结构 */
const getDeptTree = async () => {
  try {
    const response = await deptTreeSelect()
    deptOptions.value = response.data
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

// 单选框选中数据
const handleSingleUserSelect = (record: UserItem) => {
  radioSelected.value = record.userId
  emit('handleUserSelect', record)
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 5,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  })
  selectedKeys.value = []
  handleQuery()
}
</script>

<style scoped>
.head-container {
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 20px;
}

.search-form :deep(.ant-form-item) {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.ant-table-row) {
  cursor: pointer;
}

:deep(.ant-table-row:hover) {
  background-color: #f5f5f5;
}

/* 隐藏radio的label */
:deep(.ant-radio-wrapper) {
  margin-right: 0;
}

:deep(.ant-radio-wrapper .ant-radio + span) {
  display: none;
}

/* 树形组件样式 */
:deep(.ant-tree) {
  background: #fafafa;
  border-radius: 6px;
  padding: 12px;
}

:deep(.ant-tree .ant-tree-node-content-wrapper) {
  padding: 4px 8px;
}

:deep(.ant-tree .ant-tree-node-content-wrapper:hover) {
  background-color: #e6f7ff;
}

:deep(.ant-tree .ant-tree-node-selected) {
  background-color: #bae7ff;
}
</style>