<template>

  <div class="my-favorites">
    <div class="favorites-header">
      <h2>我的收藏</h2>
      <div class="filter-tabs">
        <div class="filter-tab" v-for="filter in filters" :key="String(filter.key)"
          :class="{ active: activeFilter === filter.key }" @click="activeFilter = filter.key">
          {{ filter.label }}
        </div>
      </div>
    </div>

    <div v-loading="loading" class="favorites-grid">
      <div class="favorite-item" v-for="item in filteredFavorites" :key="item.id">
        <div class="item-thumbnail">
          <img v-if="getThumbnail(item)" :src="getThumbnail(item)" :alt="getTitle(item)" />
          <div v-else class="thumbnail-placeholder">
            <el-icon :size="48">
              <Document />
            </el-icon>
          </div>
          <div class="item-type">{{ getTypeName(item) }}</div>
        </div>
        <div class="item-info">
          <h3>{{ getTitle(item) }}</h3>
          <p class="item-summary">{{ getSummary(item) }}</p>
          <div class="item-footer">
            <span class="item-date">收藏于 {{ formatDate(item.collectionTime) }}</span>
            <div class="item-actions">
              <el-button size="small" @click="viewItem(item)">查看</el-button>
              <el-button size="small" type="danger" @click="removeFavorite(item)">取消收藏</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredFavorites.length === 0" class="empty-state">
        <el-icon :size="64" class="empty-icon">
          <Star />
        </el-icon>
        <p>暂无收藏内容</p>
      </div>
    </div>
  </div>


</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElButton, ElMessage, ElMessageBox, ElIcon } from 'element-plus';
import { Document, Star } from '@element-plus/icons-vue';
import { userCollectionApi } from '@/apis/usercenter';
import { FILE_DOWNLOAD_URL } from '@/config';
import type { UserCollectionVO } from '@/types';
import { CollectionType } from '@/types/enums';

defineOptions({
  name: 'MyFavoritesView'
});

const store = useStore();
const router = useRouter();

const activeFilter = ref<'all' | number>('all');
const favorites = ref<UserCollectionVO[]>([]);
const loading = ref(false);

const filters: Array<{ key: 'all' | number; label: string }> = [
  { key: 'all', label: '全部' },
  { key: CollectionType.RESOURCE, label: '资源' },
  { key: CollectionType.COURSE, label: '课程' }
];

const filteredFavorites = computed(() => {
  if (activeFilter.value === 'all') return favorites.value;
  return favorites.value.filter(item => item.collectionType === activeFilter.value);
});

// 获取显示标题
const getTitle = (item: UserCollectionVO): string => {
  if (item.collectionType === CollectionType.RESOURCE) {
    return item.title || '未命名资源';
  } else if (item.collectionType === CollectionType.COURSE) {
    return item.courseName || '未命名课程';
  }
  return '未知类型';
};

// 获取显示简介
const getSummary = (item: UserCollectionVO): string => {
  if (item.collectionType === CollectionType.RESOURCE) {
    return item.summary || '暂无简介';
  } else if (item.collectionType === CollectionType.COURSE) {
    return item.description || '暂无简介';
  }
  return '';
};

// 获取显示缩略图
const getThumbnail = (item: UserCollectionVO): string => {
  if (item.coverImage) {
    return `${FILE_DOWNLOAD_URL}${item.coverImage}`;
  }
  return '';
};

// 获取类型名称
const getTypeName = (item: UserCollectionVO): string => {
  if (item.collectionType === CollectionType.RESOURCE) {
    return '资源';
  } else if (item.collectionType === CollectionType.COURSE) {
    return '课程';
  }
  return '未知';
};

// 获取当前用户ID
const currentUser = computed(() => store.getters['auth/user']);

onMounted(() => {
  loadFavorites();
});

// 加载收藏列表
async function loadFavorites() {
  if (!currentUser.value?.id) {
    ElMessage.warning('请先登录');
    return;
  }

  loading.value = true;
  try {
    const result = await userCollectionApi.getUserCollections(currentUser.value.id);

    if (result.success && result.dataList) {
      // 后端已返回扁平化的VO，包含详情，无需再次查询
      favorites.value = result.dataList;
    } else {
      favorites.value = [];
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error);
    ElMessage.error('加载收藏列表失败');
  } finally {
    loading.value = false;
  }
}

// 查看详情
function viewItem(item: UserCollectionVO) {
  if (item.collectionType === CollectionType.RESOURCE && item.resourceID) {
    router.push(`/article/show?articleId=${item.resourceID}`);
  } else if (item.collectionType === CollectionType.COURSE && item.courseID) {
    // TODO: 跳转到课程详情页
    ElMessage.info('课程详情页开发中');
  }
}

// 取消收藏
async function removeFavorite(item: UserCollectionVO) {
  if (!currentUser.value?.id || !item.collectionType || !item.collectionID) {
    return;
  }

  try {
    await ElMessageBox.confirm(
      '确定要取消收藏吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await userCollectionApi.removeCollection(
      {
        collectionType: item.collectionType,
        collectionID: item.collectionID
      }
    );

    if (result.success) {
      ElMessage.success('已取消收藏');
      // 从列表中移除
      favorites.value = favorites.value.filter(f => f.id !== item.id);
    } else {
      ElMessage.error(result.message || '取消收藏失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error);
      ElMessage.error('取消收藏失败');
    }
  }
}

// 格式化日期
function formatDate(dateStr?: string): string {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}
</script>

<style lang="scss" scoped>
.my-favorites {
  .favorites-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;

    h2 {
      font-size: 24px;
      font-weight: 600;
      color: #141F38;
    }
  }
}

.filter-tabs {
  display: flex;
  gap: 8px;
}

.filter-tab {
  padding: 8px 16px;
  background: #f5f5f5;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #ffe6e6;
    color: #C62828;
  }

  &.active {
    background: #C62828;
    color: white;
  }
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.favorite-item {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;

  &:hover {
    border-color: #C62828;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.item-thumbnail {
  position: relative;
  width: 100%;
  height: 180px;
  background: #f5f5f5;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.item-type {
  position: absolute;
  top: 12px;
  left: 12px;
  padding: 4px 12px;
  background: rgba(198, 40, 40, 0.9);
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.item-info {
  padding: 16px;

  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #141F38;
    margin-bottom: 8px;
  }
}

.item-summary {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.item-date {
  font-size: 12px;
  color: #999;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.thumbnail-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #ccc;
}

.empty-state {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #999;

  .empty-icon {
    margin-bottom: 16px;
    color: #ddd;
  }

  p {
    font-size: 16px;
    margin: 0;
  }
}
</style>
