<template>
  <div class="container">
    <a-card class="general-card" title="收藏管理">
      <!-- 数据表格 -->
      <a-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @page-change="handlePageChange"
      >
        <!-- 序号 -->
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>

        <!-- 资源类型 -->
        <template #resource_type="{ record }">
          <a-tag :color="record.resource_type === 'document' ? 'blue' : 'green'">
            {{ record.resource_type === 'document' ? '文档' : 'FAQ' }}
          </a-tag>
        </template>

        <!-- 收藏时间 -->
        <template #created_at="{ record }">
          {{ formatDateTime(record.created_at) }}
        </template>

        <!-- 操作 -->
        <template #actions="{ record }">
          <a-space>
            <a-button
              type="text"
              size="small"
              :disabled="record.is_deleted"
              @click="handleView(record)"
            >
              查看
            </a-button>
            <a-button
              type="text"
              size="small"
              :disabled="record.is_deleted"
              @click="handleDownload(record)"
            >
              下载
            </a-button>
            <a-button
              type="text"
              size="small"
              status="danger"
              @click="handleUncollect(record)"
            >
              取消收藏
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 文档详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="文档详情"
      :width="800"
      :footer="false"
      unmount-on-close
    >
      <div v-if="currentResource" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="资源名称">
            {{ currentResource.title || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="资源类型">
            <a-tag color="blue">文档</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="作者">
            {{ currentResource.author_name || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getDocStatusColor(currentResource.status)">
              {{ getDocStatusText(currentResource.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="发布时间">
            {{ formatDateTime(currentResource.published_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="浏览次数">
            {{ currentResource.view_count || 0 }}
          </a-descriptions-item>
          <a-descriptions-item label="描述" :span="2">
            {{ currentResource.description || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="内容" :span="2">
            <div class="content-preview" v-html="currentResource.content || '-'"></div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- FAQ详情对话框 -->
    <a-modal
      v-model:visible="faqDetailVisible"
      title="FAQ详情"
      :width="800"
      :footer="false"
      unmount-on-close
    >
      <div v-if="currentFaq" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="资源名称">
            {{ currentFaq.question || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="资源类型">
            <a-tag color="green">FAQ</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag color="green">{{ currentFaq.status || '已发布' }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="浏览次数">
            {{ currentFaq.view_count || 0 }}
          </a-descriptions-item>
          <a-descriptions-item label="答案" :span="2">
            <div class="content-preview" v-html="currentFaq.answer || '-'"></div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import {
  fetchFavoriteList,
  uncollectResource,
  type Favorite,
  type ResourceType,
} from '@/api/kb/favorite';
import { request } from '@/api/request';

// 状态管理
const loading = ref(false);
const tableData = ref<Favorite[]>([]);

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});

// 表格列配置
const columns = computed<TableColumnData[]>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 70,
    align: 'center',
  },
  {
    title: '资源名称',
    dataIndex: 'resource_name',
    ellipsis: true,
    tooltip: true,
    width: 250,
  },
  {
    title: '资源类型',
    dataIndex: 'resource_type',
    slotName: 'resource_type',
    width: 100,
    align: 'center',
  },
  {
    title: '收藏时间',
    dataIndex: 'created_at',
    slotName: 'created_at',
    width: 180,
    align: 'center',
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 200,
    fixed: 'right',
  },
]);

// 当前选中的资源
const currentResource = ref<any>(null);
const currentFaq = ref<any>(null);

// 对话框可见性
const detailVisible = ref(false);
const faqDetailVisible = ref(false);

// 获取收藏列表
const fetchFavorites = async () => {
  loading.value = true;

  try {
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
    };

    const res: any = await fetchFavoriteList(params);

    if (res.code === 0) {
      tableData.value = res.details?.data || [];
      pagination.total = res.details?.total || 0;
    } else {
      Message.error(res.message || '获取收藏列表失败');
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error);
    Message.error('获取收藏列表失败');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current;
  fetchFavorites();
};

// 查看详情
const handleView = async (record: Favorite) => {
  if (record.is_deleted) {
    Message.warning('该资源已被删除，无法查看');
    return;
  }

  try {
    if (record.resource_type === 'document') {
      // 如果有resource_data直接使用，否则请求详情
      if (record.resource_data) {
        currentResource.value = record.resource_data;
        detailVisible.value = true;
      } else {
        const res = await request.get<any>(`/Kb/v1/document/${record.resource_id}`);
        if (res.code === 0) {
          currentResource.value = res.details;
          detailVisible.value = true;
        } else {
          Message.error(res.message || '获取文档详情失败');
        }
      }
    } else if (record.resource_type === 'faq') {
      // FAQ详情
      if (record.resource_data) {
        currentFaq.value = record.resource_data;
        faqDetailVisible.value = true;
      } else {
        const res = await request.get<any>(`/Kb/v1/faq/${record.resource_id}`);
        if (res.code === 0) {
          currentFaq.value = res.details;
          faqDetailVisible.value = true;
        } else {
          Message.error(res.message || '获取FAQ详情失败');
        }
      }
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    Message.error('获取详情失败');
  }
};

// 下载文档
const handleDownload = async (record: Favorite) => {
  if (record.is_deleted) {
    Message.warning('该资源已被删除，无法下载');
    return;
  }

  try {
    if (record.resource_type === 'document') {
      // 调用文档下载接口
      const res: any = await request.get<any>(`/Kb/v1/document/${record.resource_id}`);
      if (res.code === 0) {
        const doc = res.details;
        // 创建下载内容
        const content = `# ${doc.title || '无标题'}\n\n## 描述\n${doc.description || '无描述'}\n\n## 内容\n${doc.content || '无内容'}`;
        const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${doc.title || 'document'}.md`;
        link.click();
        URL.revokeObjectURL(url);
        Message.success('下载成功');
      } else {
        Message.error(res.message || '获取文档失败');
      }
    } else if (record.resource_type === 'faq') {
      // FAQ下载
      const res = await request.get<any>(`/Kb/v1/faq/${record.resource_id}`);
      if (res.code === 0) {
        const faq = res.details;
        const content = `# ${faq.question || 'FAQ'}\n\n## 答案\n${faq.answer || '无答案'}`;
        const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `FAQ-${faq.faq_no || 'unknown'}.md`;
        link.click();
        URL.revokeObjectURL(url);
        Message.success('下载成功');
      } else {
        Message.error(res.message || '获取FAQ失败');
      }
    }
  } catch (error) {
    console.error('下载失败:', error);
    Message.error('下载失败');
  }
};

// 取消收藏
const handleUncollect = (record: Favorite) => {
  Modal.confirm({
    title: '确认取消收藏',
    content: `确认取消收藏「${record.resource_name}」吗？`,
    onOk: async () => {
      try {
        const res = await uncollectResource({
          resource_type: record.resource_type,
          resource_id: record.resource_id,
        });

        if (res.code === 0) {
          Message.success('取消收藏成功');
          fetchFavorites();
        } else {
          Message.error(res.message || '取消收藏失败');
        }
      } catch (error) {
        console.error('取消收藏失败:', error);
        Message.error('取消收藏失败');
      }
    },
  });
};

// 格式化日期时间
const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return '-';
  // 处理多种日期格式
  let date: Date;
  if (dateStr.includes('T')) {
    date = new Date(dateStr);
  } else {
    // 格式: YYYY-MM-DD HH:mm:ss
    date = new Date(dateStr.replace(' ', 'T'));
  }

  if (isNaN(date.getTime())) return dateStr;

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取文档状态颜色
const getDocStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    draft: 'gray',
    published: 'green',
    reviewed: 'blue',
    rejected: 'red',
  };
  return colorMap[status || ''] || 'gray';
};

// 获取文档状态文本
const getDocStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    reviewed: '已审核',
    rejected: '已拒绝',
  };
  return textMap[status || ''] || '未知';
};

// 初始化加载数据
onMounted(() => {
  fetchFavorites();
});
</script>

<script lang="ts">
export default {
  name: 'FavoriteManage',
};
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.content-preview {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
  background-color: var(--color-fill-1);
  border-radius: 4px;
}
</style>