<template>
  <div class="resource-library">
    <!-- 导航和搜索 -->
    <div class="nav-bar">
      <div class="tabs">
        <button
          v-for="tab in tabs"
          :key="tab.value"
          class="tab-btn"
          :class="{ active: activeTab === tab.value }"
          @click="switchTab(tab.value)"
        >
          {{ tab.label }}
        </button>
      </div>
      <div class="search-box">
        <input
          v-model="searchKeyword"
          type="text"
          placeholder="搜索关键词"
          @keyup.enter="handleSearch"
        />
        <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8"/>
          <path d="M21 21l-4.35-4.35"/>
        </svg>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 左侧筛选 -->
      <aside class="filter-panel">
        <div class="sf-section">
          <div class="sf-title-row">
            <span class="sf-title-bar"></span>
            <span class="sf-title-text">科技领域</span>
          </div>
          <div class="sf-options">
            <label
              v-for="field in fields"
              :key="field.value"
              class="sf-label"
            >
              <span
                class="sf-checkbox-icon"
                :class="{ checked: selectedFields.includes(field.value) }"
                @click="toggleField(field.value)"
              >
                <svg v-if="selectedFields.includes(field.value)" width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <rect width="14" height="14" rx="4" fill="#055FC2"/>
                  <path d="M3.5 7L6 9.5L10.5 5" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <span v-else class="sf-checkbox-empty"></span>
              </span>
              <span class="sf-text" @click="toggleField(field.value)">{{ field.label }}</span>
            </label>
          </div>
        </div>
      </aside>

      <!-- 右侧：卡片列表 + 分页 -->
      <div class="right-panel">
        <div class="card-list">
          <div v-if="loading" class="loading-state">
            <div class="loading-spinner"></div>
            <span>加载中...</span>
          </div>
          <template v-else>
            <div
              v-for="item in listData"
              :key="item.id"
              class="resource-card"
            >
              <div class="card-logo">
                <img :src="item.logoUrl || defaultLogo" :alt="item.name" />
              </div>
              <div class="card-name">{{ item.name }}</div>
              <div class="card-location">{{ item.address }}</div>
              <div class="card-majors">{{ item.majors }}</div>
              <div class="card-tags">
                <span
                  v-for="tag in item.tags"
                  :key="tag"
                  class="tag"
                >
                  {{ tag }}
                </span>
              </div>
            </div>
          </template>
        </div>

        <!-- 底部分页 -->
        <div class="pagination-wrapper">
      <div class="total-count">共{{ total }}所{{ currentTabLabel }}</div>
      <div class="pagination">
        <button
          class="page-btn prev"
          :disabled="currentPage === 1"
          @click="goToPage(currentPage - 1)"
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </button>
        <button
          v-for="page in displayedPages"
          :key="page"
          class="page-btn"
          :class="{ active: currentPage === page, ellipsis: page === '...' }"
          :disabled="page === '...'"
          @click="page !== '...' && goToPage(page)"
        >
          {{ page }}
        </button>
        <button
          class="page-btn next"
          :disabled="currentPage === totalPages"
          @click="goToPage(currentPage + 1)"
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 18l6-6-6-6"/>
          </svg>
        </button>
      </div>
    </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { getIndustryKeyList } from '@/api/bill/billHome.js'
import { getSubjectList } from '@/api/characterPage/characterPage.js'

// Props
const props = defineProps<{
  initialTab?: string
}>()

// 默认logo
const defaultLogo = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIj48cmVjdCB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9IiNhMzE4MWIiIHJ4PSI0Ii8+PHBhdGggZmlsbD0iI2ZmZiIgZD0iTTggOGgxNnYxNkg4eiIvPjwvc3ZnPg=='

// 标签配置 - 添加 subjectTypeId
const tabs = ref([
  { label: '大学', value: 'university', subjectTypeId: 1 },
  { label: '实验室', value: 'laboratory', subjectTypeId: 2 },
  { label: '企业', value: 'enterprise', subjectTypeId: 3 }
])

// 生成最近五年的年份列表
const currentYear = new Date().getFullYear()
const yearOptions = ref(
  Array.from({ length: 5 }, (_, i) => {
    const year = currentYear - i
    return { label: String(year), value: String(year) }
  })
)
const selectedYear = ref(String(currentYear))

// 筛选字段（科技领域）- 从接口获取
const fields = ref<{ label: string; value: string }[]>([
  { label: '全部领域', value: 'all' }
])
const fieldsLoading = ref(false)

// 获取科技领域选项
async function fetchFieldOptions() {
  fieldsLoading.value = true
  try {
    const res = await getIndustryKeyList()
    if (res.code === 200 && res.data) {
      const apiFields = res.data.map((item: any) => ({
        label: item.name,
        value: item.id
      }))
      fields.value = [{ label: '全部领域', value: 'all' }, ...apiFields]
    }
  } catch (error) {
    console.error('获取科技领域失败:', error)
  } finally {
    fieldsLoading.value = false
  }
}

// 状态
const activeTab = ref(props.initialTab || 'university')
const searchKeyword = ref('')
const selectedFields = ref<string[]>(['all'])
const loading = ref(false)
const listData = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)

// 计算属性
const currentTabLabel = computed(() => {
  const tab = tabs.value.find(t => t.value === activeTab.value)
  return tab ? tab.label : ''
})

const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const displayedPages = computed(() => {
  const pages: (number | string)[] = []
  const tp = totalPages.value
  const cp = currentPage.value

  if (tp <= 7) {
    for (let i = 1; i <= tp; i++) pages.push(i)
  } else {
    if (cp <= 4) {
      for (let i = 1; i <= 5; i++) pages.push(i)
      pages.push('...')
      pages.push(tp)
    } else if (cp >= tp - 3) {
      pages.push(1)
      pages.push('...')
      for (let i = tp - 4; i <= tp; i++) pages.push(i)
    } else {
      pages.push(1)
      pages.push('...')
      for (let i = cp - 1; i <= cp + 1; i++) pages.push(i)
      pages.push('...')
      pages.push(tp)
    }
  }
  return pages
})

// 方法
function switchTab(tab: string) {
  if (activeTab.value !== tab) {
    activeTab.value = tab
    currentPage.value = 1
    console.log('切换标签:', tab)
    fetchData()
  }
}

function handleSearch() {
  currentPage.value = 1
  console.log('搜索:', searchKeyword.value)
  fetchData()
}

function toggleField(value: string) {
  if (value === 'all') {
    selectedFields.value = ['all']
  } else {
    const idx = selectedFields.value.indexOf(value)
    if (idx > -1) {
      selectedFields.value = selectedFields.value.filter(f => f !== value)
    } else {
      selectedFields.value = selectedFields.value.filter(f => f !== 'all')
      selectedFields.value.push(value)
    }
    if (selectedFields.value.length === 0) {
      selectedFields.value = ['all']
    }
  }
  currentPage.value = 1
  console.log('筛选变化:', selectedFields.value)
  fetchData()
}

function goToPage(page: number | string) {
  if (typeof page === 'number' && page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    console.log('页码变化:', page)
    fetchData()
  }
}

// 模拟API获取数据
async function fetchData() {
  loading.value = true
  try {
    // 获取当前 tab 的 subjectTypeId
    const currentTab = tabs.value.find(t => t.value === activeTab.value)
    const subjectTypeId = currentTab?.subjectTypeId || 1

    // 获取筛选的领域 ID
    const areaIds = selectedFields.value.includes('all') 
      ? '' 
      : selectedFields.value.join(',')

    // 调用真实接口
    const res = await getSubjectList({
      subjectTypeId,
      arealist: areaIds,
      keywords: searchKeyword.value,
      currentPage: currentPage.value - 1, // API 的 currentPage 从 0 开始
      pageSize: pageSize.value
    })

    if (res.code === 200 && res.data) {
      // 映射 API 返回的数据到卡片显示格式
      const mappedData = (res.data.content || []).map((item: any) => ({
        id: item.id,
        name: item.orgName,
        location: item.countryName ? `${item.countryName}·${item.provinceName}` : item.provinceName || '--',
        majors: item.fieldList?.join('、') || '--',
        tags: item.areaList?.map((a: any) => a.areaName) || [],
        logo: defaultLogo
      }))

      listData.value = mappedData
      total.value = res.data.totalElements || 0
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    listData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchFieldOptions()
  fetchData()
})
</script>

<style scoped>
.resource-library {
  width: 1600px;
  margin: 0 auto;
  font-family: 'Source Han Sans CN', 'Microsoft YaHei', sans-serif;
  display: flex;
  flex-direction: column;
  height: 100%;
  box-sizing: border-box;
}

/* 导航和搜索 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-shrink: 0;
  height: 50px;
}

.tabs {
  display: flex;
  align-items: center;
  gap: 16px;
}

.tab-btn {
  height: 42px;
  padding: 4px 24px;
  font-size: 18px;
  font-weight: 400;
  color: rgba(59, 65, 75, 1);
  background: transparent;
  border: none;
  border-radius: 21px;
  cursor: pointer;
  transition: all 0.2s;
  line-height: 24px;
}

.tab-btn:hover {
  color: rgba(5, 95, 194, 1);
}

.tab-btn.active {
  color: #fff;
  background-color: rgba(5, 95, 194, 1);
  font-weight: 700;
}

.search-box {
  position: relative;
  width: 200px;
}

.search-box input {
  width: 100%;
  height: 36px;
  padding: 0 36px 0 12px;
  font-size: 14px;
  color: rgba(59, 65, 75, 1);
  border: 1px solid rgba(230, 231, 232, 1);
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.search-box input:focus {
  border-color: rgba(5, 95, 194, 1);
}

.search-box input::placeholder {
  color: rgba(132, 136, 142, 1);
}

.search-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  color: rgba(132, 136, 142, 1);
  pointer-events: none;
}

/* 内容区域：横向排列筛选面板 + 右侧面板 */
.content {
  display: flex;
  gap: 16px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

/* 筛选面板 */
.filter-panel {
  width: 360px;
  flex-shrink: 0;
  background: #fff;
  border-radius: 10px;
  border: 1px solid rgba(234, 236, 238, 1);
  box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
  box-sizing: border-box;
  padding: 16px 0 24px 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: flex-start;
  overflow: hidden;
  align-self: flex-start;
}

.sf-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-start;
}

.sf-title-row {
  display: flex;
  align-items: center;
  gap: 17px;
  width: 100%;
  box-sizing: border-box;
}

.sf-title-bar {
  display: inline-block;
  width: 8px;
  height: 16px;
  background: rgba(5, 95, 194, 1);
  border-radius: 0 2px 2px 0;
  flex-shrink: 0;
}

.sf-title-text {
  font-size: 16px;
  font-weight: 700;
  font-family: 'Source Han Sans CN', 'Noto Sans SC', sans-serif;
  color: rgba(5, 95, 194, 1);
  letter-spacing: 1px;
  line-height: 24px;
}

.sf-options {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8px 4px;
  align-content: flex-start;
  align-items: flex-start;
  padding: 0 0 0 24px;
  width: 100%;
  box-sizing: border-box;
}

.sf-label {
  width: 160px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  flex-shrink: 0;
}

.sf-checkbox-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  flex-shrink: 0;
  cursor: pointer;
}

.sf-checkbox-empty {
  display: block;
  width: 14px;
  height: 14px;
  border: 1px solid rgba(230, 231, 232, 1);
  border-radius: 4px;
  box-sizing: border-box;
  background: #fff;
}

.sf-text {
  font-size: 16px;
  font-weight: 400;
  font-family: 'Source Han Sans CN', 'Noto Sans SC', sans-serif;
  color: rgba(95, 101, 108, 1);
  line-height: 24px;
  cursor: pointer;
  white-space: nowrap;
}

.sf-label:hover .sf-text {
  color: rgba(59, 65, 75, 1);
}

/* 右侧面板：卡片 + 分页，独立 flex column */
.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

/* 卡片列表 - 调整 height 控制高度 */
.card-list {
  height: 700px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-content: flex-start;
  overflow-y: auto;
  flex-shrink: 0;
  padding: 0 16px;
}

.resource-card {
  width: calc((100% - 32px) / 3);
  padding: 12px 14px;
  background-color: #fff;
  border: 1px solid rgba(230, 231, 232, 1);
  border-radius: 10px;
  box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
  display: flex;
  flex-direction: column;
  gap: 6px;
  transition: box-shadow 0.2s;
}

.resource-card:hover {
  box-shadow: 0px 0px 30px 0px rgba(25, 69, 130, 0.15);
}

.card-logo {
  width: 32px;
  height: 32px;
}

.card-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.card-name {
  font-size: 18px;
  font-weight: 700;
  color: rgba(59, 65, 75, 1);
  line-height: 24px;
}

.card-location {
  font-size: 14px;
  color: rgba(95, 101, 108, 1);
  line-height: 22px;
}

.card-majors {
  font-size: 14px;
  color: rgba(95, 101, 108, 1);
  line-height: 22px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 1px 8px;
  font-size: 14px;
  color: rgba(19, 168, 168, 1);
  background-color: rgba(230, 255, 251, 1);
  border: 1px solid rgba(135, 232, 222, 1);
  border-radius: 4px;
  line-height: 20px;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0 0 0;
  flex-shrink: 0;
  border-top: 1px solid rgba(234, 236, 238, 1);
}

.total-count {
  font-size: 14px;
  color: rgba(95, 101, 108, 1);
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  min-width: 32px;
  height: 32px;
  padding: 0 8px;
  font-size: 14px;
  color: rgba(59, 65, 75, 1);
  background-color: #fff;
  border: 1px solid rgba(230, 231, 232, 1);
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.page-btn:hover:not(:disabled):not(.active):not(.ellipsis) {
  border-color: rgba(5, 95, 194, 1);
  color: rgba(5, 95, 194, 1);
}

.page-btn.active {
  background-color: rgba(5, 95, 194, 1);
  border-color: rgba(5, 95, 194, 1);
  color: #fff;
}

.page-btn.ellipsis {
  border: none;
  background: transparent;
  cursor: default;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn.prev svg,
.page-btn.next svg {
  width: 16px;
  height: 16px;
}

/* 加载状态 */
.loading-state {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: rgba(132, 136, 142, 1);
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(230, 231, 232, 1);
  border-top-color: rgba(5, 95, 194, 1);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
