<template>
  <div class="resource-article">
    <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft">返回</el-button>
    </div>
    <ArticleShowView
      v-if="articleData"
      :as-dialog="false"
      :article-data="articleData"
      :category-list="[]"
    />
    <div v-else class="loading">加载中...</div>
    <ResouceCollect
      :is-collected="isCollected"
      @collect="handleCollect"
      @uncollect="handleUncollect"
    />
    <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 { ArrowLeft } from '@element-plus/icons-vue';

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() {
  try {
    const resourceID = articleData.value?.resourceID;
    if (!resourceID) return;
    
    const res = await resourceApi.incrementCollectCount(resourceID);
    if (res.success) {
      isCollected.value = true;
      ElMessage.success('收藏成功');
    } else {
      ElMessage.error('收藏失败');
    }
  } catch (error) {
    console.error('收藏失败:', error);
    ElMessage.error('收藏失败');
  }
}

function handleUncollect() {
  // TODO: 实现取消收藏API
  isCollected.value = false;
  ElMessage.success('已取消收藏');
}

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>

.page-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;

    .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin: 0;
    }
}
.resource-article {
  flex: 1;
  background: #FFFFFF;
  border-radius: 10px;
  padding: 40px 60px;
}
</style>
