<template>
  <div class="resource-article">
    <ArticleShowView
      v-if="articleData"
      :as-dialog="false"
      :article-data="articleData"
      :category-list="[]"
      :show-back-button="true"
      back-button-text="返回列表"
      @back="handleBack"
    />
    <div v-else class="loading">加载中...</div>
    <ResouceCollect
      :is-collected="isCollected"
      @collect="handleCollect"
    />
    <ResouceBottom
      :prev-resource="prevResource"
      :next-resource="nextResource"
      @navigate="handleNavigate"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ArticleShowView } from '@/views/article';
import { ResouceCollect, ResouceBottom } from '@/views/resource-center/components';
import { resourceApi } from '@/apis/resource';
import { ElMessage } from 'element-plus';
import type { Resource } from '@/types/resource';
import { CollectionType, type UserCollection } from '@/types';

interface Props {
  resourceId?: string;
  categoryId?: string;
  resourceList?: Resource[];
}
const props = defineProps<Props>();

const emit = defineEmits<{
  'resource-change': [resourceId: string];
  'back-to-list': [];
  'navigate': [direction: 'prev' | 'next', resourceId: string];
}>();

const articleData = ref<any>(null);
const isCollected = ref(false);
const prevResource = ref<Resource | null>(null);
const nextResource = ref<Resource | null>(null);

watch(() => props.resourceId, (newId) => {
  if (newId) {
    // 进入加载前先置空，避免子组件读取到 null 字段
    articleData.value = null;
    loadArticle(newId);
    updateAdjacentResources(newId);
  }
}, { immediate: true });

watch(() => props.resourceList, () => {
  if (props.resourceId) {
    updateAdjacentResources(props.resourceId);
  }
}, { deep: true });

async function loadArticle(resourceId: string) {
  try {
    const res = await resourceApi.getResourceById(resourceId);
    if (res.success && res.data) {
      const resourceVO = res.data;
      articleData.value = {
        ...resourceVO.resource,
        tags: resourceVO.tags || []
      };
    } else {
      ElMessage.error('加载文章失败');
    }
  } catch (error) {
    console.error('加载文章失败:', error);
    ElMessage.error('加载文章失败');
  }
}

function updateAdjacentResources(currentResourceId: string) {
  if (!props.resourceList || props.resourceList.length === 0) {
    prevResource.value = null;
    nextResource.value = null;
    return;
  }
  
  const currentIndex = props.resourceList.findIndex(r => 
    String(r.resourceID) === String(currentResourceId)
  );
  
  if (currentIndex !== -1) {
    prevResource.value = currentIndex > 0 ? props.resourceList[currentIndex - 1] : null;
    nextResource.value = currentIndex < props.resourceList.length - 1 ? props.resourceList[currentIndex + 1] : null;
  } else {
    prevResource.value = null;
    nextResource.value = null;
  }
}

async function handleCollect(type: number) {
  try {
    const resourceID = articleData.value?.resourceID;
    if (!resourceID) return;
    let collect: UserCollection = {
      collectionType: CollectionType.RESOURCE,
      collectionID: resourceID,
      collectionValue: type
    }
    const res = await resourceApi.resourceCollect(collect);
    if (res.success) {
      if (type === 1) {
        isCollected.value = true;
        ElMessage.success('收藏成功');
      } else if (type === -1) {
        isCollected.value = false;
        ElMessage.success('已取消收藏');
      }
    } else {
      ElMessage.error(type === 1 ? '收藏失败' : '取消收藏失败');
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
}

function handleNavigate(direction: 'prev' | 'next', resource: Resource) {
  const resourceId = resource.resourceID;
  if (resourceId) {
    emit('resource-change', resourceId);
    emit('navigate', direction, resourceId);
  }
}

// 返回列表
function handleBack() {
  emit('back-to-list');
}
</script>

<style lang="scss" scoped>
.resource-article {
  flex: 1;
  background: #FFFFFF;
  border-radius: 10px;
  padding: 40px 60px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}
</style>
