<template>
  <div class="page-container">
    <h1>{{ pageTitle }}</h1>
    <div class="table-header">
      <el-input v-model="searchQuery" placeholder="搜索标题..." @keyup.enter="fetchData(1)" style="width: 300px;"></el-input>
      <el-button type="primary" :icon="'Refresh'" @click="fetchData(1)" :loading="loading">刷新</el-button>
    </div>
    <el-table :data="tableData" v-loading="loading" border>
      <el-table-column label="封面" width="120">
        <template #default="{ row }">
          <el-image style="width: 80px; height: 120px" :src="row.poster" fit="cover" lazy>
             <template #error><div class="image-slot">无封面</div></template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="300"></el-table-column>
      <el-table-column prop="year" label="年份" width="120"></el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px; justify-content: flex-end;"
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import * as api from '../api';

const route = useRoute();
const loading = ref(false);
const searchQuery = ref('');
const tableData = ref([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 根据路由元信息动态设置页面标题和服务器类型
const pageTitle = computed(() => route.meta.title);
const serverType = computed(() => route.meta.serverType);

const fetchData = async (page = pagination.currentPage) => {
  loading.value = true;
  pagination.currentPage = page;
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      query: searchQuery.value
    };
    const res = await api.getMediaServerLibrary(serverType.value, params);
    tableData.value = res.list;
    pagination.total = res.total;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchData(1);
};

const handleCurrentChange = (page) => {
  fetchData(page);
};

// 监听路由变化，当从Emby切换到Plex时重新加载数据
watch(serverType, () => {
    searchQuery.value = '';
    fetchData(1);
});

onMounted(() => fetchData());
</script>

<style scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
</style>
