<script setup lang="ts">
import type { TaskItem } from '@/api/aiImage/types';
import { Check, CircleCloseFilled, Download, Loading, MagicStick, Picture, Picture as PictureIcon, Share, User, ZoomIn } from '@element-plus/icons-vue';
import { format } from 'date-fns';
import { defineEmits, defineProps } from 'vue';

const props = defineProps<{
  task: TaskItem;
  showPublishStatus?: boolean;
  batchMode?: boolean;
  selected?: boolean;
}>();

const emit = defineEmits(['click', 'use-prompt', 'use-reference', 'publish', 'preview', 'toggle-select']);

function formatTime(time: string) {
  try {
    return format(new Date(time), 'MM-dd HH:mm');
  }
  catch (e) {
    return '';
  }
}

function handlePreview() {
  if (props.task.storeUrl) {
    emit('preview', props.task.storeUrl);
  }
}

async function handleDownload() {
  if (!props.task.storeUrl)
    return;

  try {
    const response = await fetch(props.task.storeUrl);
    const blob = await response.blob();
    const blobUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = `image-${Date.now()}.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(blobUrl);
  }
  catch (e) {
    console.error('Download failed', e);
    window.open(props.task.storeUrl, '_blank');
  }
}
// 下载方案2
/* async function handleDownload() {
  if (!props.task.storeUrl) return;

  // 显示操作选项
  const userChoice = confirm(
      '由于浏览器安全限制，图片需要手动保存。\n\n' +
      '点击"确定"在新窗口打开图片，然后右键选择"另存为..."。\n' +
      '点击"取消"尝试直接下载（可能不成功）。'
  );

  if (userChoice) {
    // 用户选择手动保存
    window.open(props.task.storeUrl, '_blank');
  } else {
    // 尝试自动下载
    try {
      // 创建一个临时表单提交（绕过某些限制）
      const form = document.createElement('form');
      form.method = 'GET';
      form.action = props.task.storeUrl;
      form.target = '_blank';
      document.body.appendChild(form);
      form.submit();
      document.body.removeChild(form);

      // 同时尝试a标签
      const link = document.createElement('a');
      link.href = props.task.storeUrl;
      link.download = `image-${Date.now()}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (e) {
      window.open(props.task.storeUrl, '_blank');
    }
  }
} */
</script>

<template>
  <div
    class="task-card relative flex flex-col bg-white rounded-xl overflow-hidden border border-gray-100 transition-all duration-300 cursor-pointer"
    :class="{
      'ring-2 ring-primary': selected,
      'group hover:shadow-xl hover:-translate-y-1': !batchMode,
      'hover:ring-2 hover:ring-primary/50': batchMode
    }"
    @click="batchMode ? $emit('click') : undefined"
  >
    <!-- Batch Selection Checkbox -->
    <div v-if="batchMode" class="absolute top-2 right-2 z-20 pointer-events-none">
      <el-checkbox :model-value="selected" size="large" class="batch-checkbox" />
    </div>

    <!-- Image Area -->
    <div class="aspect-square w-full relative bg-gray-100 overflow-hidden">
      <!-- Blurred Background -->
      <div
        v-if="task.taskStatus === 'Success' && task.storeUrl"
        class="absolute inset-0 bg-cover bg-center blur-xl opacity-60 scale-125"
        :style="{ backgroundImage: `url(${task.storeUrl})` }"
      />

      <el-image
        v-if="task.taskStatus === 'Success' && task.storeUrl"
        :src="task.storeUrl"
        fit="contain"
        loading="lazy"
        class="w-full h-full relative z-10 transition-transform duration-500 group-hover:scale-105"
      >
        <template #error>
          <div class="flex flex-col justify-center items-center w-full h-full text-gray-400 bg-gray-50">
            <el-icon class="text-3xl mb-2">
              <Picture />
            </el-icon>
            <span class="text-xs">加载失败</span>
          </div>
        </template>
        <template #placeholder>
          <div class="flex justify-center items-center w-full h-full bg-gray-50">
            <el-icon class="is-loading text-gray-400">
              <Loading />
            </el-icon>
          </div>
        </template>
      </el-image>

      <!-- Non-Success States -->
      <div v-else class="w-full h-full flex flex-col justify-center items-center p-4 text-center relative z-10 bg-gray-50">
        <div v-if="task.taskStatus === 'Processing'" class="flex flex-col items-center text-blue-500">
          <el-icon class="is-loading text-2xl mb-2">
            <Loading />
          </el-icon>
          <span class="text-xs font-medium">生成中...</span>
        </div>
        <div v-else-if="task.taskStatus === 'Fail'" class="flex flex-col items-center text-red-500">
          <el-icon class="text-2xl mb-2">
            <CircleCloseFilled />
          </el-icon>
          <span class="text-xs font-medium">生成失败</span>
        </div>
        <div v-else class="text-gray-400">
          <span class="text-xs">等待中</span>
        </div>
      </div>

      <!-- Overlay (Hover) - Desktop -->
      <div v-if="!batchMode" class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-300 hidden md:flex flex-col items-center justify-center gap-3 z-20 backdrop-blur-[2px]">
        <el-button type="primary" round size="small" class="transform scale-90 group-hover:scale-100 transition-transform shadow-lg" @click="$emit('click')">
          查看详情
        </el-button>
        <div v-if="task.taskStatus === 'Success'" class="flex gap-2">
          <el-tooltip content="放大查看" placement="top" :show-after="500">
            <el-button circle size="small" :icon="ZoomIn" @click.stop="handlePreview" />
          </el-tooltip>
          <el-tooltip content="下载图片" placement="top" :show-after="500">
            <el-button circle size="small" :icon="Download" @click.stop="handleDownload" />
          </el-tooltip>
          <el-tooltip content="使用提示词" placement="top" :show-after="500">
            <el-button circle size="small" :icon="MagicStick" @click.stop="$emit('use-prompt', task.prompt)" />
          </el-tooltip>

          <el-tooltip v-if="false" content="做参考图" placement="top" :show-after="500">
            <el-button circle size="small" :icon="PictureIcon" @click.stop="$emit('use-reference', task.storeUrl)" />
          </el-tooltip>
          <el-tooltip v-if="task.publishStatus === 'Unpublished'" content="发布到广场" placement="top" :show-after="500">
            <el-button circle size="small" type="success" :icon="Share" @click.stop="$emit('publish', task)" />
          </el-tooltip>
        </div>
      </div>

      <!-- Mobile Actions Bar -->
      <div v-if="!batchMode" class="absolute bottom-0 left-0 right-0 md:hidden bg-gradient-to-t from-black/70 to-transparent p-2 z-20">
        <div class="flex items-center justify-between gap-2">
          <el-button
            type="primary"
            size="small"
            round
            class="flex-1"
            @click="$emit('click')"
          >
            查看详情
          </el-button>
          <template v-if="task.taskStatus === 'Success'">
            <el-button circle size="small" :icon="ZoomIn" @click.stop="handlePreview" />
            <el-button circle size="small" :icon="Download" @click.stop="handleDownload" />
            <el-button
              v-if="showPublishStatus && task.publishStatus === 'Unpublished'"
              circle
              size="small"
              type="success"
              :icon="Share"
              @click.stop="$emit('publish', task)"
            />
          </template>
        </div>
      </div>

      <!-- Status Tag -->
      <div v-if="showPublishStatus && task.publishStatus === 'Published'" class="absolute top-2 right-2 z-20">
        <el-tag type="success" effect="dark" size="small" round>
          已发布
        </el-tag>
      </div>
    </div>

    <!-- Content Area -->
    <div class="p-3 flex-1 flex flex-col">
      <p class="text-sm text-gray-700 line-clamp-2 mb-2 h-10 leading-5" :title="task.prompt">
        {{ task.prompt }}
      </p>

      <!-- Tags -->
      <div v-if="task.categories && task.categories.length > 0" class="flex flex-wrap gap-1 mb-2">
        <el-tag
          v-for="tag in task.categories.slice(0, 3)"
          :key="tag"
          size="small"
          type="info"
          effect="plain"
        >
          {{ tag }}
        </el-tag>
        <el-tag v-if="task.categories.length > 3" size="small" type="info" effect="plain">
          +{{ task.categories.length - 3 }}
        </el-tag>
      </div>

      <div class="mt-auto flex justify-between items-center text-xs text-gray-400">
        <div class="flex flex-col gap-1">
          <span>{{ formatTime(task.creationTime) }}</span>
          <span v-if="!task.isAnonymous && task.userName" class="text-blue-500 flex items-center gap-1">
            <el-icon><User /></el-icon> {{ task.userName }}
          </span>
          <span v-else-if="task.isAnonymous" class="text-gray-400 flex items-center gap-1">
            <el-icon><User /></el-icon> 匿名用户
          </span>
        </div>
        <span v-if="task.taskStatus === 'Success'" class="text-green-500 flex items-center gap-1">
          <el-icon><Check /></el-icon> 完成
        </span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.task-card {
  backface-visibility: hidden;
}

.batch-checkbox :deep(.el-checkbox__inner) {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.batch-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
}
</style>
