<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';

import { Button, Card, Space, Table, Tag, Select, Tooltip, message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useFinanceStore } from '#/store/finance';

defineOptions({ name: 'FinanceMediaCenter' });

const financeStore = useFinanceStore();

const DEFAULT_LIMIT = 200;

const selectedTypes = ref<string[]>([]);
const isRefreshing = ref(false);

const typeOptions = [
  { label: '图片', value: 'photo' },
  { label: '视频', value: 'video' },
  { label: '音频', value: 'audio' },
  { label: '语音', value: 'voice' },
  { label: '文件', value: 'document' },
  { label: '视频消息', value: 'video_note' },
  { label: '动图', value: 'animation' },
  { label: '贴纸', value: 'sticker' },
];

const columns = [
  { title: '类型', dataIndex: 'fileType', key: 'fileType', width: 120 },
  { title: '说明', dataIndex: 'caption', key: 'caption', ellipsis: true },
  { title: '发送者', dataIndex: 'displayName', key: 'sender', width: 160 },
  { title: '用户名', dataIndex: 'username', key: 'username', width: 160 },
  { title: '时间', dataIndex: 'createdAt', key: 'createdAt', width: 200 },
  { title: '大小', dataIndex: 'fileSize', key: 'fileSize', width: 120 },
  { title: '状态', dataIndex: 'available', key: 'available', width: 120 },
  { title: '操作', key: 'action', width: 160, fixed: 'right' },
];

const pagination = ref({
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showTotal: (total: number) => `共 ${total} 条媒体记录`,
});

const loading = computed(
  () => financeStore.loading.mediaMessages || isRefreshing.value,
);

const mediaMessages = computed(() => {
  const types = selectedTypes.value;
  if (!types || types.length === 0) {
    return financeStore.mediaMessages;
  }
  return financeStore.mediaMessages.filter((item) =>
    types.includes(item.fileType),
  );
});

const typeLabelMap: Record<string, string> = {
  photo: '图片',
  video: '视频',
  audio: '音频',
  voice: '语音',
  document: '文件',
  video_note: '视频消息',
  animation: '动图',
  sticker: '贴纸',
};

function formatFileSize(size?: number) {
  if (!size || size <= 0) {
    return '-';
  }
  if (size < 1024) {
    return `${size} B`;
  }
  if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(1)} KB`;
  }
  if (size < 1024 * 1024 * 1024) {
    return `${(size / 1024 / 1024).toFixed(1)} MB`;
  }
  return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
}

async function fetchMedia() {
  isRefreshing.value = true;
  try {
    await financeStore.fetchMediaMessages({
      limit: DEFAULT_LIMIT,
      fileTypes: selectedTypes.value.length > 0 ? selectedTypes.value : undefined,
    });
  } catch (error) {
    console.error('[finance][media] fetch failed', error);
    message.error('媒体记录加载失败，请稍后重试');
  } finally {
    isRefreshing.value = false;
  }
}

function handleDownload(record: (typeof mediaMessages.value)[number]) {
  if (!record.available || !record.downloadUrl) {
    message.warning('文件不可用或已被移除');
    return;
  }
  const apiBase = (import.meta.env.VITE_GLOB_API_URL ?? '').replace(/\/$/, '');
  const url = record.downloadUrl.startsWith('http')
    ? record.downloadUrl
    : `${apiBase}${record.downloadUrl.startsWith('/') ? '' : '/'}${record.downloadUrl}`;
  window.open(url, '_blank');
}

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

watch(selectedTypes, () => {
  // 每次筛选更新时刷新数据
  fetchMedia();
});
</script>

<template>
  <div class="space-y-4">
    <Card
      :loading="loading"
      title="📂 多媒体中心"
      bordered
    >
      <template #extra>
        <Space :size="12">
          <Select
            v-model:value="selectedTypes"
            mode="multiple"
            :options="typeOptions"
            allow-clear
            placeholder="筛选媒体类型"
            style="min-width: 240px"
            max-tag-count="responsive"
          />
          <Button type="primary" :loading="isRefreshing" @click="fetchMedia">
            手动刷新
          </Button>
        </Space>
      </template>

      <Table
        :columns="columns"
        :data-source="mediaMessages"
        :loading="loading"
        :pagination="pagination"
        :scroll="{ x: 1000 }"
        row-key="id"
        bordered
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'fileType'">
            <Tag color="blue">
              {{ typeLabelMap[record.fileType] ?? record.fileType }}
            </Tag>
          </template>

          <template v-else-if="column.key === 'caption'">
            <Tooltip>
              <template #title>
                <div class="max-w-72 whitespace-pre-wrap">
                  {{ record.caption || '（无备注）' }}
                </div>
              </template>
              <span class="block max-w-56 truncate">
                {{ record.caption || '（无备注）' }}
              </span>
            </Tooltip>
          </template>

          <template v-else-if="column.key === 'sender'">
            {{ record.displayName || `用户 ${record.userId}` }}
          </template>

          <template v-else-if="column.key === 'createdAt'">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>

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

          <template v-else-if="column.key === 'available'">
            <Tag :color="record.available ? 'success' : 'error'">
              {{ record.available ? '可下载' : '已缺失' }}
            </Tag>
          </template>

          <template v-else-if="column.key === 'action'">
            <Space>
              <Button
                type="link"
                size="small"
                :disabled="!record.available"
                @click="handleDownload(record)"
              >
                下载
              </Button>
              <Tooltip title="复制文件路径">
                <Button
                  type="link"
                  size="small"
                  @click="
                    navigator.clipboard
                      .writeText(record.filePath)
                      .then(() => message.success('已复制文件路径'))
                      .catch(() => message.error('复制失败'))
                  "
                >
                  复制路径
                </Button>
              </Tooltip>
            </Space>
          </template>

          <template v-else>
            {{ record[column.dataIndex as keyof typeof record] ?? '-' }}
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.space-y-4 > * + * {
  margin-top: 1rem;
}
</style>
