<script setup>
import { computed, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { clearScreenshots, deleteScreenshot, fetchScreenshots } from '../api/screenshots'

const loading = ref(false)
const screenshots = ref([])
const currentPage = ref(1)
const total = ref(0)
const pageSize = 24
const totalPages = computed(() => Math.max(1, Math.ceil((total.value || 0) / pageSize)))

const previewOpen = ref(false)
const previewUrl = ref('')
const previewTitle = ref('')

function buildUrl(filename) {
  return `/screenshots/${encodeURIComponent(filename)}`
}

function buildThumbUrl(filename) {
  return `/screenshots/thumb/${encodeURIComponent(filename)}`
}

async function load() {
  loading.value = true
  try {
    const params = {
      limit: pageSize,
      offset: (currentPage.value - 1) * pageSize,
    }
    const payload = await fetchScreenshots(params)
    const items = Array.isArray(payload) ? payload : (Array.isArray(payload?.items) ? payload.items : [])
    const payloadTotal = Array.isArray(payload) ? items.length : Number(payload?.total ?? items.length)

    screenshots.value = items
    total.value = Number.isFinite(payloadTotal) ? Math.max(0, payloadTotal) : items.length
  } catch (e) {
    if (e?.response?.status === 401) window.location.href = '/login'
    screenshots.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

async function onPageChange(page) {
  currentPage.value = page
  await load()
}

function openPreview(item) {
  previewTitle.value = item.display_name || item.filename || '截图预览'
  previewUrl.value = buildUrl(item.filename)
  previewOpen.value = true
}

function onThumbError(event, item) {
  const imageEl = event?.target
  if (!imageEl) return
  if (imageEl.dataset.fullLoaded === '1') return

  imageEl.dataset.fullLoaded = '1'
  imageEl.src = buildUrl(item.filename)
}

function canvasToPngBlob(canvas) {
  return new Promise((resolve, reject) => {
    canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('toBlob_failed'))), 'image/png')
  })
}

async function imageElementToPngBlob(imgEl) {
  if (!imgEl) throw new Error('no_image')
  if (!imgEl.complete || imgEl.naturalWidth <= 0) {
    if (typeof imgEl.decode === 'function') await imgEl.decode()
    else {
      await new Promise((resolve, reject) => {
        imgEl.addEventListener('load', resolve, { once: true })
        imgEl.addEventListener('error', reject, { once: true })
      })
    }
  }

  const canvas = document.createElement('canvas')
  canvas.width = imgEl.naturalWidth
  canvas.height = imgEl.naturalHeight
  const ctx = canvas.getContext('2d')
  if (!ctx) throw new Error('no_canvas')
  ctx.drawImage(imgEl, 0, 0)
  return await canvasToPngBlob(canvas)
}

async function blobToPng(blob) {
  if (!blob) throw new Error('no_blob')
  if (blob.type === 'image/png') return blob

  if (typeof createImageBitmap === 'function') {
    const bitmap = await createImageBitmap(blob)
    const canvas = document.createElement('canvas')
    canvas.width = bitmap.width
    canvas.height = bitmap.height
    const ctx = canvas.getContext('2d')
    if (!ctx) throw new Error('no_canvas')
    ctx.drawImage(bitmap, 0, 0)
    return await canvasToPngBlob(canvas)
  }

  const url = URL.createObjectURL(blob)
  try {
    const img = new Image()
    img.src = url
    if (typeof img.decode === 'function') await img.decode()
    return await imageElementToPngBlob(img)
  } finally {
    URL.revokeObjectURL(url)
  }
}

async function screenshotUrlToPngBlob(url) {
  // 复制时始终拉取原图，避免复制到缩略图
  const resp = await fetch(url, { credentials: 'include', cache: 'no-store' })
  if (!resp.ok) throw new Error('fetch_failed')
  const blob = await resp.blob()
  const mime = resp.headers.get('Content-Type') || blob.type || ''
  if (!mime.startsWith('image/')) throw new Error('not_image')
  return await blobToPng(blob)
}

async function onClearAll() {
  try {
    await ElMessageBox.confirm('确定要清空全部截图吗？', '清空截图', {
      confirmButtonText: '清空',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    const res = await clearScreenshots()
    if (res?.success) {
      ElMessage.success(`已清空（删除 ${res?.deleted || 0} 张）`)
      screenshots.value = []
      total.value = 0
      currentPage.value = 1
      previewOpen.value = false
      return
    }
    ElMessage.error(res?.error || '操作失败')
  } catch (e) {
    const data = e?.response?.data
    ElMessage.error(data?.error || '操作失败')
  }
}

async function onDelete(item) {
  try {
    await ElMessageBox.confirm(`确定要删除截图「${item.display_name || item.filename}」吗？`, '删除截图', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    const res = await deleteScreenshot(item.filename)
    if (res?.success) {
      if (previewUrl.value.includes(encodeURIComponent(item.filename))) previewOpen.value = false
      if (currentPage.value > 1 && screenshots.value.length <= 1) currentPage.value -= 1
      await load()
      ElMessage.success('已删除')
      return
    }
    ElMessage.error(res?.error || '删除失败')
  } catch (e) {
    const data = e?.response?.data
    ElMessage.error(data?.error || '删除失败')
  }
}

async function copyImage(item) {
  const url = buildUrl(item.filename)
  if (
    !navigator.clipboard ||
    typeof navigator.clipboard.write !== 'function' ||
    typeof window.ClipboardItem === 'undefined'
  ) {
    ElMessage.warning('当前环境不支持复制图片（建议使用 Chrome/Edge 并通过 HTTPS 访问）；可用“下载”。')
    return
  }

  try {
    // 关键点：用 Promise 形式的数据源，让 clipboard.write 在用户手势内立即发生（更稳）
    try {
      await navigator.clipboard.write([
        new ClipboardItem({
          'image/png': screenshotUrlToPngBlob(url),
        }),
      ])
    } catch {
      const pngBlob = await screenshotUrlToPngBlob(url)
      await navigator.clipboard.write([new ClipboardItem({ 'image/png': pngBlob })])
    }
    ElMessage.success('图片已复制到剪贴板')
  } catch {
    try {
      if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
        await navigator.clipboard.writeText(`${window.location.origin}${url}`)
        ElMessage.warning('复制图片失败，已复制图片链接（可直接粘贴到浏览器打开）')
        return
      }
    } catch {
      // ignore
    }
    ElMessage.warning('复制图片失败：请确认允许剪贴板权限；可用“下载”。')
  }
}

function download(item) {
  const link = document.createElement('a')
  link.href = buildUrl(item.filename)
  link.download = item.display_name || item.filename
  document.body.appendChild(link)
  link.click()
  link.remove()
}

onMounted(load)
</script>

<template>
  <el-card shadow="never" class="panel" :body-style="{ padding: '14px' }">
    <div class="panel-head">
      <div class="panel-title">截图管理</div>
      <div class="panel-actions">
        <el-button :loading="loading" @click="load">刷新</el-button>
        <el-button type="danger" plain :disabled="total === 0" @click="onClearAll">清空全部</el-button>
      </div>
    </div>

    <el-skeleton v-if="loading" :rows="6" animated />
    <template v-else>
      <el-empty v-if="total === 0" description="暂无截图" />

      <div v-else class="grid">
        <el-card v-for="item in screenshots" :key="item.filename" shadow="never" class="shot-card" :body-style="{ padding: '0' }">
          <img
            class="shot-img"
            :src="buildThumbUrl(item.filename)"
            :alt="item.display_name || item.filename"
            loading="lazy"
            @error="onThumbError($event, item)"
            @click="openPreview(item)"
          />
          <div class="shot-body">
            <div class="shot-name" :title="item.display_name || item.filename">{{ item.display_name || item.filename }}</div>
            <div class="shot-meta app-muted">{{ item.created || '' }}</div>
            <div class="shot-actions">
              <el-button size="small" text type="primary" @click="copyImage(item)">复制图片</el-button>
              <el-button size="small" text @click="download(item)">下载</el-button>
              <el-button size="small" text type="danger" @click="onDelete(item)">删除</el-button>
            </div>
          </div>
        </el-card>
      </div>

      <div v-if="total > pageSize" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next, jumper, ->, total"
          @current-change="onPageChange"
        />
        <div class="page-hint app-muted">第 {{ currentPage }} / {{ totalPages }} 页</div>
      </div>
    </template>

    <el-dialog v-model="previewOpen" :title="previewTitle" width="min(920px, 94vw)">
      <div class="preview">
        <img :src="previewUrl" :alt="previewTitle" class="preview-img" />
      </div>
      <template #footer>
        <el-button @click="previewOpen = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.panel {
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
}

.panel-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.panel-title {
  font-size: 16px;
  font-weight: 900;
}

.panel-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 12px;
  align-items: start;
}

.pagination {
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  flex-wrap: wrap;
}

.page-hint {
  font-size: 12px;
}

.shot-card {
  border-radius: 14px;
  border: 1px solid var(--app-border);
  overflow: hidden;
}

.shot-img {
  width: 100%;
  aspect-ratio: 16/9;
  object-fit: cover;
  cursor: pointer;
  display: block;
}

.shot-body {
  padding: 12px;
}

.shot-name {
  font-size: 13px;
  font-weight: 800;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.shot-meta {
  margin-top: 4px;
  font-size: 12px;
}

.shot-actions {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.preview {
  display: flex;
  justify-content: center;
}

.preview-img {
  max-width: 100%;
  max-height: 78vh;
  object-fit: contain;
  border-radius: 10px;
  border: 1px solid var(--app-border);
  background: #fff;
}

@media (max-width: 480px) {
  .grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .panel-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
