<template>
  <el-drawer
    :model-value="modelValue"
    direction="btt"
    :with-header="false"
    size="88%"
    class="select-book-drawer"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div class="drawer-inner">
    <!-- ===== 顶部操作栏 ===== -->
    <div class="drawer-header">
      <button
        class="lx-btn lx-btn--sm lx-btn--short lx-btn--default"
        type="button"
        @click="handleCancel"
      >
        取消
      </button>
      <span class="drawer-title">选择教材</span>
      <button
        class="lx-btn lx-btn--sm lx-btn--short lx-btn--primary"
        type="button"
        @click="handleConfirm"
      >
        确认
      </button>
    </div>

    <!-- ===== 筛选区域 ===== -->
    <div class="filter-section">
      <!-- 出版社行 -->
      <div class="filter-row">
        <div class="filter-scroll">
          <span
            v-for="p in publishers"
            :key="p"
            class="filter-chip"
            :class="{ active: activePublisher === p }"
            @click="activePublisher = p"
          >{{ p }}</span>
        </div>
        <button v-if="!expanded" class="toggle-btn" @click="expanded = true">
          展示<span class="chevron">▼</span>
        </button>
      </div>

      <!-- 年级行（展开时） -->
      <div v-if="expanded" class="filter-row">
        <div class="filter-scroll">
          <span
            v-for="g in grades"
            :key="g"
            class="filter-chip"
            :class="{ active: activeGrade === g }"
            @click="activeGrade = g"
          >{{ g }}</span>
        </div>
      </div>

      <!-- 年份行 + 收起按钮（展开时） -->
      <div v-if="expanded" class="filter-row">
        <div class="filter-scroll">
          <span
            v-for="y in years"
            :key="y"
            class="filter-chip"
            :class="{ active: activeYear === y }"
            @click="activeYear = y"
          >{{ y }}</span>
        </div>
        <button class="toggle-btn" @click="expanded = false">
          收起<span class="chevron up">▲</span>
        </button>
      </div>
    </div>

    <!-- ===== 书本网格区域 ===== -->
    <div class="book-grid-area">
      <div class="book-grid">
        <BookCoverCard
          v-for="book in filteredBooks"
          :key="book.id"
          :book="book"
          :selected="selectedIds.has(book.id)"
          @click="toggleSelect"
        />
      </div>
    </div>
    </div><!-- /drawer-inner -->
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import BookCoverCard from './BookCoverCard.vue'

interface BookItem {
  id: number
  year: string | null
  level: string | null
  name: string
  subtitle: string
}

const props = defineProps<{
  modelValue: boolean
  books: BookItem[]
  /** 初始选中的 id 列表（对应已添加的书本） */
  initialSelected?: number[]
}>()

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

/* ---- 筛选数据 ---- */
const grades = ['全部', '一年级', '二年级', '三年级', '四年级', '五年级', '六年级']

const publishers = computed(() => ['全部', ...new Set(props.books.map((b: BookItem) => b.name))])
const years = computed(() => {
  const ys = props.books.filter((b: BookItem) => b.year).map((b: BookItem) => b.year as string)
  return ['全部', ...new Set(ys)]
})

const activePublisher = ref('全部')
const activeGrade = ref('全部')
const activeYear = ref('全部')
const expanded = ref(false)

/* ---- 过滤后的书本列表 ---- */
const filteredBooks = computed(() => {
  return props.books.filter((book: BookItem) => {
    const matchPublisher = activePublisher.value === '全部' || book.name === activePublisher.value
    const matchYear = activeYear.value === '全部' || book.year === activeYear.value
    return matchPublisher && matchYear
  })
})

/* ---- 已选书本 id ---- */
const selectedIds = ref<Set<number>>(new Set())

// 每次打开弹框时，用初始选中值重置
watch(
  () => props.modelValue,
  (open: boolean) => {
    if (open) {
      selectedIds.value = new Set(props.initialSelected ?? [])
      activePublisher.value = '全部'
      activeGrade.value = '全部'
      activeYear.value = '全部'
      expanded.value = false
    }
  }
)

function toggleSelect(book: BookItem) {
  const ids = new Set(selectedIds.value)
  if (ids.has(book.id)) {
    ids.delete(book.id)
  } else {
    ids.add(book.id)
  }
  selectedIds.value = ids
}

function handleConfirm() {
  emit('confirm', [...selectedIds.value])
  emit('update:modelValue', false)
}

function handleCancel() {
  emit('update:modelValue', false)
}
</script>

<style scoped lang="scss">
/* ---- Drawer 面板样式覆盖（teleport 到 body，必须用 :global 脱离 scoped） ---- */
:global(.select-book-drawer) {
  border-radius: 26px 26px 0 0 !important;
  overflow: hidden !important;
}

:global(.select-book-drawer .el-drawer__body) {
  padding: 0;
  height: 100%;
  overflow: hidden !important;
}

/* ---- 内部布局容器（接管高度与滚动） ---- */
.drawer-inner {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

/* ---- 顶部操作栏 ---- */
.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28px 40px 20px;
  flex-shrink: 0;
//   border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.drawer-title {
  font-size: 34px;
//   font-weight: 600;
  color: #111;
}

/* ---- 筛选区域 ---- */
.filter-section {
  flex-shrink: 0;
  padding: 16px 40px 0;
  display: flex;
  flex-direction: column;
  gap: 0;
//   border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-bottom: 16px;
}

.filter-scroll {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 4px;
  overflow-x: auto;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}

.filter-chip {
  flex-shrink: 0;
  font-size: 26px;
  color: #555;
  padding: 8px 20px;
  border-radius: 99px;
  cursor: pointer;
  transition: background 0.15s, color 0.15s;
  white-space: nowrap;

  &.active {
    background: rgba(51, 126, 255, 0.10);
    color: #2d64d8;
  }

  &:not(.active):hover {
    background: rgba(0, 0, 0, 0.05);
  }
}

.toggle-btn {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 24px;
  color: var(--color-text-brand);
  background: transparent;
  border: none;
  cursor: pointer;
  white-space: nowrap;
  padding: 8px 0;
}

.chevron {
  font-size: 20px;
  display: inline-block;
  transition: transform 0.2s;

  &.up {
    transform: rotate(180deg);
  }
}

/* ---- 书本网格区域 ---- */
.book-grid-area {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 28px 40px 32px;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}

.book-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 28px 24px;
}
</style>
