<template>
  <a-drawer
    v-model:open="visible"
    title="添加指导老师"
    placement="right"
    width="850px"
    :footer-style="{ textAlign: 'right', padding: '16px 24px' }"
    @close="handleCancel"
  >
    <template #title>
      <div class="drawer-title">
        <span>添加指导老师</span>
      </div>
    </template>

    <!-- 搜索/筛选区域 -->
    <div class="search-section">
      <div class="search-item">
        <span class="search-label">姓名：</span>
        <a-input
          v-model:value="searchParams.nickname"
          placeholder="请输入"
          allow-clear
          style="width: 200px"
          @press-enter="handleSearch"
        >
          <template #suffix>
            <SearchOutlined />
          </template>
        </a-input>
      </div>
      <div class="search-item">
        <span class="search-label">工号：</span>
        <a-input
          v-model:value="searchParams.employeeNo"
          placeholder="请输入"
          allow-clear
          style="width: 200px"
          @press-enter="handleSearch"
        >
          <template #suffix>
            <SearchOutlined />
          </template>
        </a-input>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{
          type: 'checkbox',
          selectedRowKeys: selectedKeys,
          onChange: handleSelectionChange,
          getCheckboxProps: getCheckboxProps,
        }"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            {{ record.user?.nickname || "-" }}
          </template>
          <template v-else-if="column.key === 'username'">
            {{ record.user?.username || "-" }}
          </template>
          <template v-else-if="column.key === 'employeeNo'">
            {{ record.employeeNo || "-" }}
          </template>
          <template v-else-if="column.key === 'department'">
            {{ record.department?.name || "-" }}
          </template>
          <template v-else-if="column.key === 'phone'">
            {{ record.phone || record.user?.phone || "-" }}
          </template>
          <template v-else-if="column.key === 'subject'">
            {{ record.subject || "-" }}
          </template>
        </template>
      </a-table>
    </div>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue"
import { message } from "ant-design-vue"
import { SearchOutlined } from "@ant-design/icons-vue"
import type { TableColumnsType } from "ant-design-vue"
import { teachersApi, type Teacher } from "@/api/teachers"
import { useListRequest } from "@/composables/useListRequest"

interface Props {
  open: boolean
  selectedTeacherUserIds?: number[] // 已选择的教师用户ID列表（用于禁用已选择的）
}

interface Emits {
  (e: "update:open", value: boolean): void
  (e: "confirm", teachers: Teacher[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const submitLoading = ref(false)
const selectedKeys = ref<number[]>([])

// 搜索参数
const searchParams = reactive<{
  nickname?: string
  employeeNo?: string
}>({})

// 列表请求
const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  search,
  fetchList,
} = useListRequest<Teacher, { nickname?: string; employeeNo?: string }>({
  requestFn: async (params) => {
    // 将搜索参数转换为API需要的格式
    const apiParams: any = {
      page: params.page || 1,
      pageSize: params.pageSize || 10,
    }
    
    // 如果传入了nickname，需要通过user的nickname来搜索
    // 由于API可能不支持直接搜索nickname，这里先简单处理
    // 实际使用时可能需要后端支持或前端过滤
    return teachersApi.getList(apiParams)
  },
  defaultSearchParams: {},
  defaultPageSize: 10,
  errorMessage: "获取教师列表失败",
  immediate: false,
})

// 表格列定义
const columns: TableColumnsType = [
  {
    title: "姓名",
    key: "name",
    width: 120,
  },
  {
    title: "账号",
    key: "username",
    width: 120,
  },
  {
    title: "工号",
    key: "employeeNo",
    width: 120,
  },
  {
    title: "部门",
    key: "department",
    width: 150,
  },
  {
    title: "联系电话",
    key: "phone",
    width: 120,
  },
  {
    title: "任教科目",
    key: "subject",
    width: 120,
  },
]

// 监听 open 变化
watch(
  () => props.open,
  (newVal) => {
    visible.value = newVal
    if (newVal) {
      // 打开时重置状态
      selectedKeys.value = []
      searchParams.nickname = ""
      searchParams.employeeNo = ""
      fetchList()
    }
  },
  { immediate: true }
)

// 监听 visible 变化，同步到父组件
watch(visible, (newVal) => {
  emit("update:open", newVal)
})

// 搜索处理
const handleSearch = () => {
  // 由于API可能不支持直接搜索nickname和employeeNo
  // 这里先调用列表，实际过滤可能需要后端支持
  search({
    nickname: searchParams.nickname || undefined,
    employeeNo: searchParams.employeeNo || undefined,
  })
}

// 选择变化处理
const handleSelectionChange = (
  selectedRowKeys: number[],
  selectedRows: Teacher[]
) => {
  selectedKeys.value = selectedRowKeys
}

// 获取复选框属性，禁用已选择的教师
const getCheckboxProps = (record: Teacher) => {
  const isSelected = props.selectedTeacherUserIds?.includes(record.userId) ?? false
  return {
    disabled: isSelected,
  }
}

// 提交
const handleSubmit = () => {
  if (selectedKeys.value.length === 0) {
    message.warning("请至少选择一个指导老师")
    return
  }

  // 获取选中的教师
  const selectedTeachers = dataSource.value.filter((teacher) =>
    selectedKeys.value.includes(teacher.id)
  )

  emit("confirm", selectedTeachers)
  visible.value = false
  selectedKeys.value = []
}

// 取消
const handleCancel = () => {
  visible.value = false
  selectedKeys.value = []
  searchParams.nickname = ""
  searchParams.employeeNo = ""
}
</script>

<style scoped lang="scss">
.drawer-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.ant-drawer-body) {
  padding: 24px;
}

.search-section {
  margin-bottom: 24px;
  display: flex;
  flex-direction: row;
  gap: 16px;
  align-items: center;
  flex-wrap: nowrap;

  .search-item {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;

    .search-label {
      font-size: 14px;
      color: #303133;
      font-weight: 500;
      white-space: nowrap;
      flex-shrink: 0;
    }
  }
}

.table-section {
  margin-bottom: 24px;

  :deep(.ant-table-thead > tr > th) {
    background-color: #f5f7fa;
    font-weight: 500;
    color: #303133;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background-color: #f5f7fa;
  }

  :deep(.ant-table-tbody > tr:nth-child(even) > td) {
    background-color: #fafafa;
  }
}
</style>

