<template>
  <div class="expert-select-wrap">
    <!-- 已选标签行 -->
    <div v-if="selectedExperts.length > 0" class="selected-row">
      <span class="selected-label">已选 {{ selectedExperts.length }} 人：</span>
      <el-tag
        v-for="expert in selectedExperts"
        :key="expert.id"
        closable
        :disable-transitions="false"
        class="expert-tag"
        @close="removeExpert(expert.id)"
      >
        {{ expert.nickname }}
      </el-tag>
    </div>

    <!-- 搜索框 -->
    <el-input
      v-if="!disabled"
      v-model="searchKeyword"
      placeholder="搜索姓名、单位、职称"
      clearable
      class="search-input"
    >
      <template #prefix>
        <el-icon><Search /></el-icon>
      </template>
    </el-input>

    <!-- 专家表格 -->
    <el-table
      v-if="!disabled"
      ref="tableRef"
      :data="filteredExperts"
      border
      size="small"
      max-height="300"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="姓名" prop="nickname" width="100" />
      <el-table-column label="单位" prop="deptName" show-overflow-tooltip />
      <el-table-column label="职称" prop="title" width="120" show-overflow-tooltip />
    </el-table>

    <!-- 查看模式：仅展示已选专家列表 -->
    <el-table v-if="disabled && selectedExperts.length > 0" :data="selectedExperts" border size="small">
      <el-table-column label="姓名" prop="nickname" width="100" />
      <el-table-column label="单位" prop="deptName" show-overflow-tooltip />
      <el-table-column label="职称" prop="title" width="120" show-overflow-tooltip />
    </el-table>
    <el-empty v-if="disabled && selectedExperts.length === 0" description="暂无参会专家" :image-size="60" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { Search } from '@element-plus/icons-vue'

interface Expert {
  id: number
  nickname: string
  deptName?: string
  title?: string
}

const props = defineProps<{
  modelValue: number[]
  experts: Expert[]
  disabled?: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: number[]): void
}>()

const tableRef = ref()
const searchKeyword = ref('')
const isUpdating = ref(false)

const filteredExperts = computed(() => {
  const kw = searchKeyword.value.trim().toLowerCase()
  if (!kw) return props.experts
  return props.experts.filter(
    (e) =>
      e.nickname?.toLowerCase().includes(kw) ||
      e.deptName?.toLowerCase().includes(kw) ||
      e.title?.toLowerCase().includes(kw)
  )
})

const selectedExperts = computed(() =>
  props.experts.filter((e) => props.modelValue.includes(e.id))
)

// 同步表格选中状态
watch(
  () => props.modelValue,
  async () => {
    await nextTick()
    if (!tableRef.value) return
    isUpdating.value = true
    tableRef.value.clearSelection()
    filteredExperts.value.forEach((row) => {
      if (props.modelValue.includes(row.id)) {
        tableRef.value.toggleRowSelection(row, true)
      }
    })
    isUpdating.value = false
  },
  { immediate: true }
)

const handleSelectionChange = (selected: Expert[]) => {
  if (isUpdating.value) return
  const selectedIds = selected.map((e) => e.id)
  // 合并：保留不在当前过滤列表中的已选项
  const filteredIds = filteredExperts.value.map((e) => e.id)
  const keptIds = props.modelValue.filter((id) => !filteredIds.includes(id))
  emit('update:modelValue', [...new Set([...keptIds, ...selectedIds])])
}

const removeExpert = (id: number) => {
  emit('update:modelValue', props.modelValue.filter((v) => v !== id))
}
</script>

<style scoped>
.expert-select-wrap {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 已选标签行 */
.selected-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 12px;
  background-color: rgba(41, 90, 188, 0.04);
  border: 1px solid rgba(41, 90, 188, 0.12);
  border-radius: 6px;
}
.selected-label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}
.expert-tag {
  margin: 0;
  background-color: rgba(41, 90, 188, 0.1);
  border-color: rgba(41, 90, 188, 0.2);
  color: #295abc;
}

/* 搜索框 */
.search-input {
  max-width: 320px;
}
:deep(.search-input .el-input__wrapper) {
  height: 38px;
  border-radius: 6px;
  border-color: #dcdedf;
}
:deep(.search-input .el-input__inner) {
  font-size: 14px;
}

/* 专家表格 */
:deep(.el-table .el-table__header-wrapper th) {
  background-color: #eef2fb;
  color: #333;
  font-weight: 600;
  font-size: 14px;
  border-color: #e1e7f0;
}
:deep(.el-table .el-table__body td) {
  font-size: 14px;
  color: #333;
  border-color: #e1e7f0;
}
:deep(.el-table .el-table__body tr.active > td) {
  background-color: rgba(41, 90, 188, 0.06);
}
:deep(.el-table .el-table__body .el-checkbox__inner) {
  border-color: #295abc;
}
:deep(.el-table .el-table__body .el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #295abc;
  border-color: #295abc;
}
</style>
