<template>
  <div>
    <div class="flex items-center justify-between mb-4">
      <h1 class="text-lg font-bold text-gray-800">素材上传（微信）</h1>
    </div>

    <!-- 上传方式切换 -->
    <el-card class="mb-4">
      <div class="flex gap-4 mb-4">
        <el-radio-group v-model="uploadMode">
          <el-radio value="file">选择文件上传</el-radio>
          <el-radio value="url">通过链接上传</el-radio>
        </el-radio-group>
      </div>

      <!-- 文件上传模式 -->
      <template v-if="uploadMode === 'file'">
        <el-upload
          drag
          :auto-upload="false"
          accept="image/*"
          :show-file-list="false"
          @change="handleFileChange"
        >
          <div class="flex flex-col items-center py-4">
            <div class="i-carbon-cloud-upload text-4xl text-gray-400 mb-2" />
            <div class="text-sm text-gray-500">将图片拖到此处，或<em class="text-blue-600">点击选择</em></div>
            <div class="text-xs text-gray-400 mt-1">支持 JPG / PNG / GIF 格式</div>
          </div>
        </el-upload>
        <div v-if="selectedFile" class="mt-3 flex items-center gap-3">
          <span class="text-sm text-gray-600">已选择: {{ selectedFile.name }}</span>
          <el-button type="primary" size="small" :loading="uploading" @click="handleFileUpload">
            开始上传
          </el-button>
        </div>
      </template>

      <!-- 链接上传模式 -->
      <template v-if="uploadMode === 'url'">
        <div class="flex gap-2">
          <el-input
            v-model="imageLink"
            placeholder="请输入图片链接地址，例如 https://example.com/image.jpg"
            clearable
            class="flex-1"
          />
          <el-button type="primary" :loading="uploading" @click="handleUrlUpload">
            上传
          </el-button>
        </div>
      </template>
    </el-card>

    <!-- 上传结果 -->
    <el-card v-if="uploadedUrl" class="mb-4">
      <template #header>
        <span class="text-sm font-medium">上传结果</span>
      </template>
      <div class="flex items-start gap-3">
        <div class="w-24 h-24 shrink-0 rounded-lg overflow-hidden bg-gray-100 border">
          <img :src="uploadedUrl" class="w-full h-full object-cover" @error="onImgError" />
        </div>
        <div class="flex-1 min-w-0">
          <div class="text-xs text-gray-400 mb-1">微信图片 URL：</div>
          <div class="text-sm text-blue-600 break-all mb-2">{{ uploadedUrl }}</div>
          <el-button size="small" type="warning" @click="copyUrl">复制链接</el-button>
        </div>
      </div>
    </el-card>

    <!-- 上传记录 -->
    <el-card>
      <template #header>
        <span class="text-sm font-medium">上传记录</span>
      </template>
      <div v-if="history.length === 0" class="text-center text-gray-400 py-6 text-sm">
        暂无上传记录
      </div>
      <div v-else class="space-y-2">
        <div v-for="(item, index) in history" :key="index"
          class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-50 transition-colors">
          <div class="w-10 h-10 shrink-0 rounded overflow-hidden bg-gray-100 border">
            <img :src="item.url" class="w-full h-full object-cover" @error="onImgError" />
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-xs text-gray-500 truncate">{{ item.url }}</div>
            <div class="text-xs text-gray-400">{{ item.time }}</div>
          </div>
          <el-button size="small" text type="primary" @click="copyText(item.url)">复制</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadImage, uploadImageByURL } from '@/api'

const uploadMode = ref<'file' | 'url'>('file')
const selectedFile = ref<File | null>(null)
const imageLink = ref('')
const uploading = ref(false)
const uploadedUrl = ref('')

interface HistoryItem {
  url: string
  time: string
}
const history = ref<HistoryItem[]>([])

function handleFileChange(uploadFile: any) {
  const file = uploadFile.raw as File
  if (!file) return
  selectedFile.value = file
}

async function handleFileUpload() {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择图片文件')
    return
  }
  uploading.value = true
  uploadedUrl.value = ''
  try {
    const res: any = await uploadImage(selectedFile.value)
    const url = res?.data?.url || res?.url || ''
    if (url) {
      uploadedUrl.value = url
      addHistory(url)
      ElMessage.success('上传成功')
    } else {
      ElMessage.error('上传失败：响应中未找到图片 URL')
    }
  } catch {
    // handled by interceptor
  } finally {
    uploading.value = false
  }
}

async function handleUrlUpload() {
  if (!imageLink.value.trim()) {
    ElMessage.warning('请输入图片链接')
    return
  }
  uploading.value = true
  uploadedUrl.value = ''
  try {
    const res: any = await uploadImageByURL(imageLink.value.trim())
    const url = res?.data?.url || res?.url || ''
    if (url) {
      uploadedUrl.value = url
      addHistory(url)
      ElMessage.success('上传成功')
      imageLink.value = ''
    } else {
      ElMessage.error('上传失败：响应中未找到图片 URL')
    }
  } catch {
    // handled by interceptor
  } finally {
    uploading.value = false
  }
}

function addHistory(url: string) {
  history.value.unshift({
    url,
    time: new Date().toLocaleString(),
  })
}

function copyUrl() {
  copyText(uploadedUrl.value)
}

function copyText(text: string) {
  if (!text) return
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

function onImgError(e: Event) {
  (e.target as HTMLImageElement).src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100"><rect fill="%23f3f4f6" width="200" height="100"/><text x="100" y="55" text-anchor="middle" fill="%239ca3af" font-size="12">加载失败</text></svg>'
}
</script>
