<template>
  <div class="resource-list-view">
    <a-page-header
      title="资源库管理"
      sub-title="管理平台数字资源"
    />

    <!-- 统计卡片 -->
    <a-row :gutter="16" style="margin-bottom: 16px;">
      <a-col :span="6">
        <a-card>
          <a-statistic title="资源库总数" :value="stats.totalLibraries">
            <template #prefix><FolderOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="资源总数" :value="stats.totalItems">
            <template #prefix><FileOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="绘本资源" :value="stats.itemsByLibraryType?.PICTURE_BOOK || 0">
            <template #prefix><BookOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="教学材料" :value="stats.itemsByLibraryType?.MATERIAL || 0">
            <template #prefix><AppstoreOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <a-card :bordered="false">
      <template #extra>
        <a-space>
          <a-button @click="showLibraryModal">
            <template #icon><FolderAddOutlined /></template>
            新建资源库
          </a-button>
          <a-button type="primary" @click="showUploadModal">
            <template #icon><UploadOutlined /></template>
            上传资源
          </a-button>
        </a-space>
      </template>

      <!-- 搜索和筛选 -->
      <div class="filter-bar" style="margin-bottom: 16px;">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-input-search
              v-model:value="filters.keyword"
              placeholder="搜索资源名称"
              allow-clear
              @search="fetchItems"
            >
              <template #prefix><SearchOutlined /></template>
            </a-input-search>
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="filters.libraryId"
              placeholder="选择资源库"
              allow-clear
              style="width: 100%"
              @change="fetchItems"
            >
              <a-select-option v-for="lib in libraries" :key="lib.id" :value="lib.id">
                {{ lib.name }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="filters.fileType"
              placeholder="资源类型"
              allow-clear
              style="width: 100%"
              @change="fetchItems"
            >
              <a-select-option value="IMAGE">图片</a-select-option>
              <a-select-option value="PDF">PDF</a-select-option>
              <a-select-option value="VIDEO">视频</a-select-option>
              <a-select-option value="AUDIO">音频</a-select-option>
              <a-select-option value="PPT">PPT</a-select-option>
              <a-select-option value="OTHER">其他</a-select-option>
            </a-select>
          </a-col>
        </a-row>
      </div>

      <a-table
        :columns="columns"
        :data-source="items"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'resource'">
            <div class="resource-item">
              <div class="resource-icon">
                <FilePdfOutlined v-if="record.fileType === 'PDF'" />
                <VideoCameraOutlined v-else-if="record.fileType === 'VIDEO'" />
                <AudioOutlined v-else-if="record.fileType === 'AUDIO'" />
                <PictureOutlined v-else-if="record.fileType === 'IMAGE'" />
                <FilePptOutlined v-else-if="record.fileType === 'PPT'" />
                <FileOutlined v-else />
              </div>
              <div class="resource-info">
                <div class="resource-name">{{ record.title }}</div>
                <div class="resource-meta">
                  <a-tag size="small">{{ getFileTypeLabel(record.fileType) }}</a-tag>
                  <span style="color: #999; font-size: 12px;">
                    {{ formatFileSize(record.fileSize) }}
                  </span>
                </div>
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'library'">
            <a-tag color="blue">{{ record.library?.name || '-' }}</a-tag>
          </template>

          <template v-else-if="column.key === 'tags'">
            <a-tag v-for="tag in record.tags" :key="tag" size="small">{{ tag }}</a-tag>
            <span v-if="!record.tags?.length">-</span>
          </template>

          <template v-else-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="openEditModal(record as ResourceItem)">
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                :disabled="!canPreview(record as ResourceItem)"
                @click="previewResource(record as ResourceItem)"
              >
                预览
              </a-button>
              <a-button type="link" size="small" @click="downloadResource(record as ResourceItem)">
                下载
              </a-button>
              <a-popconfirm title="确定删除此资源？" @confirm="handleDelete(record.id)">
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>

        <!-- 批量操作栏 -->
        <template #footer>
          <div v-if="selectedRowKeys.length > 0" class="batch-actions">
            <a-space>
              <span>已选择 <strong>{{ selectedRowKeys.length }}</strong> 项</span>
              <a-popconfirm title="确定删除选中的资源？" @confirm="batchDelete">
                <a-button size="small" danger>批量删除</a-button>
              </a-popconfirm>
              <a-button size="small" @click="selectedRowKeys = []">取消选择</a-button>
            </a-space>
          </div>
        </template>
      </a-table>
    </a-card>

    <!-- 新建资源库弹窗 -->
    <a-modal
      v-model:open="libraryModalVisible"
      title="新建资源库"
      @ok="handleCreateLibrary"
      :confirm-loading="submitting"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="资源库名称" required>
          <a-input v-model:value="libraryForm.name" placeholder="请输入资源库名称" />
        </a-form-item>
        <a-form-item label="资源库类型" required>
          <a-select v-model:value="libraryForm.libraryType" placeholder="请选择类型">
            <a-select-option value="PICTURE_BOOK">绘本资源</a-select-option>
            <a-select-option value="MATERIAL">教学材料</a-select-option>
            <a-select-option value="TEMPLATE">教学模板</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="libraryForm.description" placeholder="请输入描述" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 上传资源弹窗 -->
    <a-modal
      v-model:open="uploadModalVisible"
      title="上传资源"
      width="600px"
      @ok="handleUpload"
      :confirm-loading="uploading"
    >
      <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="目标资源库" required>
          <a-select v-model:value="uploadForm.libraryId" placeholder="请选择资源库">
            <a-select-option v-for="lib in libraries" :key="lib.id" :value="lib.id">
              {{ lib.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="资源类型" required>
          <a-select v-model:value="uploadForm.fileType" placeholder="请选择资源类型">
            <a-select-option value="IMAGE">图片 (JPG/PNG)</a-select-option>
            <a-select-option value="PDF">PDF文档</a-select-option>
            <a-select-option value="VIDEO">视频 (MP4)</a-select-option>
            <a-select-option value="AUDIO">音频 (MP3)</a-select-option>
            <a-select-option value="PPT">PPT (PPTX)</a-select-option>
            <a-select-option value="OTHER">其他</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="选择文件" required>
          <a-upload
            v-model:file-list="uploadForm.files"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="{ type: 'resources' }"
            :max-count="10"
            list-type="text"
            @change="handleUploadChange"
          >
            <a-button>
              <UploadOutlined /> 选择文件
            </a-button>
          </a-upload>
          <div style="margin-top: 8px; color: #999; font-size: 12px;">
            支持批量上传，单个文件最大 100MB
          </div>
        </a-form-item>

        <a-form-item label="资源标签">
          <a-select
            v-model:value="uploadForm.tags"
            mode="tags"
            placeholder="输入标签，按回车添加"
            style="width: 100%"
          >
            <a-select-option value="绘本阅读">绘本阅读</a-select-option>
            <a-select-option value="儿歌">儿歌</a-select-option>
            <a-select-option value="游戏">游戏</a-select-option>
            <a-select-option value="手工">手工</a-select-option>
            <a-select-option value="科普">科普</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑资源弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑资源"
      @ok="handleEditConfirm"
      :confirm-loading="submitting"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="资源名称">
          <a-input v-model:value="editForm.title" placeholder="资源名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="editForm.description" placeholder="描述" :rows="3" />
        </a-form-item>
        <a-form-item label="标签">
          <a-select
            v-model:value="editForm.tags"
            mode="tags"
            placeholder="输入标签"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 预览弹窗 -->
    <a-modal
      v-model:open="previewModalVisible"
      :title="currentPreviewResource?.title"
      width="800px"
      :footer="null"
    >
      <div class="preview-container">
        <div v-if="currentPreviewResource?.fileType === 'IMAGE'">
          <img :src="getFileUrl(currentPreviewResource?.filePath)" style="max-width: 100%;" />
        </div>
        <div v-else-if="currentPreviewResource?.fileType === 'VIDEO'">
          <video :src="getFileUrl(currentPreviewResource?.filePath)" controls style="width: 100%; max-height: 500px;"></video>
        </div>
        <div v-else-if="currentPreviewResource?.fileType === 'AUDIO'">
          <audio :src="getFileUrl(currentPreviewResource?.filePath)" controls style="width: 100%;"></audio>
        </div>
        <div v-else class="preview-placeholder">
          <FileTextOutlined style="font-size: 64px; color: #ccc;" />
          <p style="color: #999;">此文件类型不支持在线预览</p>
          <a-button type="primary" @click="downloadResource(currentPreviewResource)">下载文件</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
  UploadOutlined,
  SearchOutlined,
  FileTextOutlined,
  FilePdfOutlined,
  FilePptOutlined,
  VideoCameraOutlined,
  AudioOutlined,
  PictureOutlined,
  FileOutlined,
  BookOutlined,
  FolderOutlined,
  FolderAddOutlined,
  AppstoreOutlined,
} from '@ant-design/icons-vue';
import {
  getLibraries,
  getResourceItems,
  createLibrary,
  createResourceItem,
  updateResourceItem,
  deleteResourceItem,
  batchDeleteResourceItems,
  getResourceStats,
} from '@/api/resource';
import type { ResourceLibrary, ResourceItem, FileType as FileTypeType } from '@/api/resource';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();

const loading = ref(false);
const submitting = ref(false);
const uploading = ref(false);

const libraries = ref<ResourceLibrary[]>([]);
const items = ref<ResourceItem[]>([]);

const stats = ref({
  totalLibraries: 0,
  totalItems: 0,
  itemsByType: {} as Record<string, number>,
  itemsByLibraryType: {} as Record<string, number>,
});

const filters = reactive({
  keyword: '',
  libraryId: undefined as number | undefined,
  fileType: undefined as FileTypeType | undefined,
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
});

const selectedRowKeys = ref<number[]>([]);

const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: (string | number)[]) => {
    selectedRowKeys.value = keys as number[];
  },
}));

const libraryModalVisible = ref(false);
const uploadModalVisible = ref(false);
const previewModalVisible = ref(false);
const editModalVisible = ref(false);
const currentPreviewResource = ref<ResourceItem | null>(null);
const editingResource = ref<ResourceItem | null>(null);

const libraryForm = reactive({
  name: '',
  libraryType: 'PICTURE_BOOK' as const,
  description: '',
});

const uploadForm = reactive({
  libraryId: undefined as number | undefined,
  fileType: 'PDF' as const,
  files: [] as any[],
  tags: [] as string[],
});

const editForm = reactive({
  title: '',
  description: '',
  tags: [] as string[],
});

const uploadUrl = '/api/v1/files/upload';
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${userStore.token}`,
}));

const columns = [
  { title: '资源', key: 'resource', width: 300 },
  { title: '所属资源库', key: 'library', width: 150 },
  { title: '标签', key: 'tags', width: 200 },
  { title: '上传时间', key: 'createdAt', width: 120 },
  { title: '操作', key: 'action', width: 200, fixed: 'right' as const },
];

const getFileTypeLabel = (type: FileTypeType) => {
  const labels: Record<FileTypeType, string> = {
    IMAGE: '图片',
    PDF: 'PDF',
    VIDEO: '视频',
    AUDIO: '音频',
    PPT: 'PPT',
    OTHER: '其他',
  };
  return labels[type] || type;
};

const formatFileSize = (bytes?: number) => {
  if (!bytes) return '-';
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
};

const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN');
};

const getFileUrl = (path?: string) => {
  if (!path) return '';
  if (path.startsWith('http')) return path;
  // 使用代理路径，Vite会将 /uploads 请求转发到后端
  return path;
};

const canPreview = (resource: ResourceItem) => {
  return ['IMAGE', 'VIDEO', 'AUDIO'].includes(resource.fileType);
};

const fetchLibraries = async () => {
  try {
    const result = await getLibraries({ pageSize: 100 });
    libraries.value = result.items;
  } catch (error) {
    console.error('Failed to fetch libraries:', error);
  }
};

const fetchItems = async () => {
  loading.value = true;
  try {
    const result = await getResourceItems({
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    });
    items.value = result.items;
    pagination.total = result.total;
  } catch (error) {
    message.error('获取资源列表失败');
  } finally {
    loading.value = false;
  }
};

const fetchStats = async () => {
  try {
    stats.value = await getResourceStats();
  } catch (error) {
    console.error('Failed to fetch stats:', error);
  }
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchItems();
};

const showLibraryModal = () => {
  libraryForm.name = '';
  libraryForm.libraryType = 'PICTURE_BOOK';
  libraryForm.description = '';
  libraryModalVisible.value = true;
};

const handleCreateLibrary = async () => {
  if (!libraryForm.name) {
    message.error('请输入资源库名称');
    return;
  }
  submitting.value = true;
  try {
    await createLibrary(libraryForm);
    message.success('创建成功');
    libraryModalVisible.value = false;
    fetchLibraries();
    fetchStats();
  } catch (error) {
    message.error('创建失败');
  } finally {
    submitting.value = false;
  }
};

const showUploadModal = () => {
  uploadForm.libraryId = libraries.value[0]?.id;
  uploadForm.fileType = 'PDF';
  uploadForm.files = [];
  uploadForm.tags = [];
  uploadModalVisible.value = true;
};

const handleUploadChange = (info: any) => {
  if (info.file.status === 'done') {
    message.success(`${info.file.name} 上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 上传失败`);
  }
};

const handleUpload = async () => {
  if (!uploadForm.libraryId) {
    message.error('请选择目标资源库');
    return;
  }
  if (!uploadForm.fileType) {
    message.error('请选择资源类型');
    return;
  }

  const uploadedFiles = uploadForm.files.filter((f: any) => f.status === 'done' && f.response?.filePath);
  if (uploadedFiles.length === 0) {
    message.error('请上传文件');
    return;
  }

  uploading.value = true;
  let success = 0;
  let failed = 0;

  for (const file of uploadedFiles) {
    try {
      await createResourceItem({
        libraryId: uploadForm.libraryId!,
        title: file.name.replace(/\.[^/.]+$/, ''),
        fileType: uploadForm.fileType,
        filePath: file.response.filePath,
        fileSize: file.size,
        tags: uploadForm.tags,
      });
      success++;
    } catch (error) {
      failed++;
    }
  }

  uploading.value = false;
  uploadModalVisible.value = false;

  if (success > 0) {
    message.success(`成功上传 ${success} 个资源`);
    fetchItems();
    fetchStats();
  }
  if (failed > 0) {
    message.error(`${failed} 个资源上传失败`);
  }
};

const previewResource = (resource: ResourceItem) => {
  currentPreviewResource.value = resource;
  previewModalVisible.value = true;
};

const downloadResource = (resource: ResourceItem | null) => {
  if (!resource) return;
  const link = document.createElement('a');
  link.href = getFileUrl(resource.filePath);
  link.download = resource.title;
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  message.success(`开始下载: ${resource.title}`);
};

const openEditModal = (record: ResourceItem) => {
  editingResource.value = record;
  editForm.title = record.title;
  editForm.description = record.description || '';
  editForm.tags = record.tags || [];
  editModalVisible.value = true;
};

const handleEditConfirm = async () => {
  if (!editingResource.value) return;
  submitting.value = true;
  try {
    await updateResourceItem(editingResource.value.id, editForm);
    message.success('编辑成功');
    editModalVisible.value = false;
    fetchItems();
  } catch (error) {
    message.error('编辑失败');
  } finally {
    submitting.value = false;
  }
};

const handleDelete = async (id: number) => {
  try {
    await deleteResourceItem(id);
    message.success('删除成功');
    fetchItems();
    fetchStats();
  } catch (error) {
    message.error('删除失败');
  }
};

const batchDelete = async () => {
  try {
    await batchDeleteResourceItems(selectedRowKeys.value);
    message.success('批量删除成功');
    selectedRowKeys.value = [];
    fetchItems();
    fetchStats();
  } catch (error) {
    message.error('批量删除失败');
  }
};

onMounted(() => {
  fetchLibraries();
  fetchItems();
  fetchStats();
});
</script>

<style scoped lang="scss">
.resource-list-view {
  background: #f5f5f5;
  min-height: calc(100vh - 64px);

  :deep(.ant-page-header) {
    background: white;
    padding: 16px 24px;
  }

  .filter-bar {
    background: #fafafa;
    padding: 16px;
    border-radius: 4px;
  }

  .resource-item {
    display: flex;
    align-items: center;
    gap: 12px;

    .resource-icon {
      font-size: 24px;
      color: #1890ff;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      height: 40px;
      background: #f0f0f0;
      border-radius: 4px;
    }

    .resource-info {
      flex: 1;

      .resource-name {
        font-weight: 500;
        margin-bottom: 4px;
      }

      .resource-meta {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
  }

  .batch-actions {
    padding: 12px 16px;
    background: #e6f7ff;
    border: 1px solid #91d5ff;
    border-radius: 4px;
  }

  .preview-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 300px;

    .preview-placeholder {
      text-align: center;
    }
  }
}
</style>
