<template>
  <div class="container-wrapper">
    <el-form
      ref="ruleFormRef"
      :model="formData"
      label-width="auto"
      style="margin-top: 0.5rem;"
    >
      <ColumnItem title="批量创建机器人回复">
        <!-- 文件上传区域 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上传文件">
              <el-upload
                ref="uploadRef"
                :action="`${getBaseUrl()}/fileUploadAndDownload/upload`"
                :before-upload="checkFile"
                :on-error="uploadError"
                :on-success="uploadSuccess"
                :on-remove="removeFile"
                :file-list="fileList"
                :data="{'classId': 3}"
                :headers="{'x-token': token}"
                :show-file-list="false"
                multiple
                drag
                class="upload-dragger"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持批量上传文件（图片/文档等），单个文件不超过10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 已上传文件列表（自定义美化列表，隐藏el-upload内置列表） -->
        <el-row :gutter="20" v-if="uploadedFiles.length > 0">
          <el-col :span="24">
            <el-form-item label="已上传文件">
              <div class="file-list">
                <div 
                  v-for="(file, index) in uploadedFiles" 
                  :key="index"
                  class="file-item"
                >
                  <el-image
                    v-if="file.isImage"
                    :src="file.url"
                    :preview-src-list="uploadedFiles.filter(f=>f.isImage).map(f => f.url)"
                    fit="cover"
                    class="file-preview"
                  />
                  <div v-else class="file-icon">{{ getExt(file.name) }}</div>
                  <div class="file-info">
                    <div class="file-name">{{ file.name }}</div>
                    <div class="file-url">{{ file.url }}</div>
                  </div>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeUploadedFile(index)"
                    class="remove-btn"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </ColumnItem>
    </el-form>

    <div class="gva-table-box footer-box">
      <el-button @click="$router.back()">返回</el-button>
      <el-button 
        type="primary" 
        @click="submit()"
        :loading="submitLoading"
        :disabled="uploadedFiles.length === 0"
      >
        批量创建 ({{ uploadedFiles.length }} 个文件)
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { bulkCreateBot } from '@/api/bot/bot.js'
import ColumnItem from '@/components/columnItem/ColumnItem.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { getBaseUrl } from '@/utils/format'
import { useUserStore } from "@/pinia"
import logoImg from '@/assets/bot_logo.png'

const router = useRouter()
const userStore = useUserStore()
const token = userStore.token

const ruleFormRef = ref(null)
const uploadRef = ref(null)
const submitLoading = ref(false)
const fileList = ref([])
const uploadedFiles = ref([])

const formData = ref({})

// 文件类型工具
const getExt = (name) => {
  const idx = name.lastIndexOf('.')
  return idx > -1 ? name.slice(idx + 1).toUpperCase() : 'FILE'
}

// 文件上传前处理：校验大小并为图片添加底部水印
const checkFile = async (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('单个文件大小不能超过 10MB!')
    return false
  }
  const isImage = (file.type && file.type.startsWith('image/')) || /\.(png|jpg|jpeg|gif|webp|bmp)$/i.test(file.name)
  if (!isImage) {
    return true
  }
  try {
    const watermarked = await addWatermarkToImage(file)
    return watermarked
  } catch (e) {
    console.error('添加水印失败，使用原图上传:', e)
    return true
  }
}

// 为图片底部追加白底条 + 放大 logo + 文字“好运助手”
async function addWatermarkToImage(rawFile) {
  const imageBitmap = await readImageFromFile(rawFile)
  const originWidth = imageBitmap.width
  const originHeight = imageBitmap.height

  const barHeight = Math.max(80, Math.round(originHeight * 0.16))
  const canvas = document.createElement('canvas')
  canvas.width = originWidth
  canvas.height = originHeight + barHeight
  const ctx = canvas.getContext('2d')

  // 原图
  ctx.drawImage(imageBitmap, 0, 0, originWidth, originHeight)
  // 底部白色背景
  ctx.fillStyle = '#FFFFFF'
  ctx.fillRect(0, originHeight, originWidth, barHeight)

  // 绘制 logo（略大一些）
  const logo = await readImageFromUrl(logoImg)
  const logoTargetHeight = Math.min(barHeight * 0.8, 160)
  const logoScale = logoTargetHeight / logo.height
  const logoTargetWidth = Math.round(logo.width * logoScale)
  const paddingY = originHeight + Math.round((barHeight - logoTargetHeight) / 2)

  // 绘制文字（先计算尺寸以便整体居中）
  const text = '好运助手'
  // 字号根据条高自适应
  const fontSize = Math.min(Math.max(Math.round(barHeight * 0.42), 26), 64)
  ctx.font = `${fontSize}px Microsoft YaHei, PingFang SC, Arial` 
  ctx.fillStyle = '#333333'
  ctx.textBaseline = 'middle'
  const textMetrics = ctx.measureText(text)
  const textWidth = Math.ceil(textMetrics.width)
  const spacing = Math.round(barHeight * 0.2)

  // 计算整体水平居中起点
  const groupWidth = logoTargetWidth + spacing + textWidth
  const startX = Math.max(0, Math.round((originWidth - groupWidth) / 2))

  // 绘制 logo 和文字（水平居中）
  const logoX = startX
  const textX = logoX + logoTargetWidth + spacing
  const textY = originHeight + Math.round(barHeight / 2)

  ctx.drawImage(logo, logoX, paddingY, logoTargetWidth, logoTargetHeight)
  ctx.fillText(text, textX, textY)

  const mime = rawFile.type && rawFile.type.startsWith('image/') ? rawFile.type : 'image/jpeg'
  const blob = await new Promise((resolve) => canvas.toBlob(resolve, mime, 0.92))
  const wmFile = new File([blob], appendSuffixToFilename(rawFile.name, '_wm'), { type: blob.type })
  return wmFile
}

function appendSuffixToFilename(name, suffix) {
  const idx = name.lastIndexOf('.')
  if (idx === -1) return name + suffix
  return name.slice(0, idx) + suffix + name.slice(idx)
}

function readImageFromFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const img = new Image()
      img.onload = () => resolve(img)
      img.onerror = reject
      img.src = reader.result
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

function readImageFromUrl(url) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.onload = () => resolve(img)
    img.onerror = reject
    img.src = url
  })
}

// 文件上传成功
const uploadSuccess = (res, file) => {
  if (res.code === 0 && res.data.file) {
    const url = res.data.file.url
    uploadedFiles.value.push({
      name: file.name,
      url,
      isImage: (file.type && file.type.startsWith('image/')) || /\.(png|jpg|jpeg|gif|webp|bmp|svg)$/i.test(file.name)
    })
    ElMessage.success(`${file.name} 上传成功`)
  } else {
    ElMessage.error('上传失败')
  }
}

// 文件上传失败
const uploadError = () => {
  ElMessage.error('上传失败')
}

// 移除文件（同步两侧列表）
const removeFile = (file) => {
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index > -1) {
    uploadedFiles.value.splice(index, 1)
  }
}

// 移除已上传文件
const removeUploadedFile = (index) => {
  uploadedFiles.value.splice(index, 1)
  if (fileList.value[index]) {
    fileList.value.splice(index, 1)
  }
}

// 提交创建
async function submit() {
  if (uploadedFiles.value.length === 0) {
    ElMessage.warning('请先上传文件')
    return
  }

  submitLoading.value = true
  try {
    const payload = {
      files: uploadedFiles.value.map(f => f.url)
    }
    const res = await bulkCreateBot(payload)
    if (res.code === 0) {
      ElMessage.success('批量创建成功!')
      router.back()
    } else if (res.code === 5) {
      handlePartialFailure(res)
    } else {
      ElMessage.error(res.msg || '批量创建失败')
    }
  } catch (e) {
    console.error('批量创建失败:', e)
    ElMessage.error('批量创建失败')
  } finally {
    submitLoading.value = false
  }
}

// 处理部分失败（与文章批量上传一致协议：data 为失败URL数组字符串）
function handlePartialFailure(res) {
  try {
    const failedUrls = res.data.replace(/[[\]]/g, '').split(' ').filter(url => url.trim())
    if (failedUrls.length === 0) {
      ElMessage.error('解析失败文件列表出错')
      return
    }

    const originalCount = uploadedFiles.value.length
    uploadedFiles.value = uploadedFiles.value.filter(file => failedUrls.includes(file.url))
    fileList.value = fileList.value.filter(file => failedUrls.some(url => file.url === url))

    const successCount = originalCount - failedUrls.length
    const failedCount = failedUrls.length

    ElMessage.warning({
      message: `部分创建失败！成功：${successCount}个，失败：${failedCount}个。请处理失败项后重试。`,
      duration: 5000
    })

    ElMessageBox.alert(
      `失败的文件：\n${failedUrls.join('\n')}`,
      '创建失败详情',
      {
        confirmButtonText: '确定',
        type: 'warning'
      }
    )
  } catch (error) {
    console.error('处理部分失败时出错:', error)
    ElMessage.error('处理结果时出错')
  }
}
</script>

<style lang="scss" scoped>
.container-wrapper {
  padding: 20px;
}

.upload-dragger {
  width: 100%;
}

.file-list {
width: 1920px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 12px;
  margin-top: 10px;
  max-height: 420px;
  overflow: auto;
  padding-right: 6px;
}

.file-item {
  display: flex;
  flex-direction: column;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
  min-width: 0;
  transition: border-color .2s ease, box-shadow .2s ease;
}

.file-item:hover {
  border-color: #dcdfe6;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.file-preview {
  width: 100%;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
}

.file-icon {
  width: 100%;
  height: 120px;
  border-radius: 4px;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #606266;
}

.file-info {
  flex: 1;
  min-width: 0;
  margin-top: 8px;
}

.file-name {
  font-size: 12px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
}

.file-url {
  font-size: 10px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.remove-btn {
  align-self: flex-end;
  margin-top: 8px;
}

.footer-box {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
  position: sticky;
  bottom: 0;
  z-index: 10;
  box-shadow: 0 -4px 10px rgba(0,0,0,0.06);
}

::deep(.el-row) {
  margin-bottom: 20px;
}

::deep(.el-form) {
  flex: 1;
  background: white;
  overflow: hidden;
}

::deep(.el-form-item) {
  margin-bottom: 18px;
}

::deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

::deep(.el-upload-dragger) {
  width: 100%;
  height: 120px;
}
</style>


