<template>
  <section class="space-y-6">
    <header class="space-y-2">
      <h1 class="mos-title text-2xl font-semibold">活动配置向导</h1>
      <p class="mos-muted text-sm">分步完成活动配置与发布设置。</p>
    </header>

    <div class="mos-card p-5 space-y-6">
      <div class="flex items-center gap-2 text-xs text-mosquito-ink/70">
        <span v-for="(step, index) in steps" :key="step" class="mos-pill" :class="{ 'opacity-40': index !== currentStep }">
          {{ index + 1 }}. {{ step }}
        </span>
      </div>

      <div v-if="currentStep === 0" class="space-y-4">
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">活动名称</label>
          <input class="mos-input mt-2 w-full" v-model="form.name" />
        </div>
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">描述</label>
          <textarea class="mos-input mt-2 w-full" rows="3" v-model="form.description"></textarea>
        </div>
      </div>

      <div v-if="currentStep === 1" class="space-y-4">
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">目标人群</label>
          <input class="mos-input mt-2 w-full" v-model="form.audience" />
        </div>
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">转化条件</label>
          <input class="mos-input mt-2 w-full" v-model="form.conversion" />
        </div>
      </div>

      <div v-if="currentStep === 2" class="space-y-4">
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">奖励规则</label>
          <input class="mos-input mt-2 w-full" v-model="form.reward" />
        </div>
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">预算/限额</label>
          <input class="mos-input mt-2 w-full" v-model="form.budget" />
        </div>
        <!-- 富文本内容配置 -->
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">活动详情（富文本）</label>
          <div class="mt-2 border border-gray-300 rounded-md overflow-hidden">
            <!-- 简单工具栏 -->
            <div class="flex gap-1 p-2 bg-gray-50 border-b border-gray-300">
              <button type="button" class="px-2 py-1 text-xs bg-white border rounded hover:bg-gray-100" @click="formatText('bold')" title="粗体">B</button>
              <button type="button" class="px-2 py-1 text-xs bg-white border rounded hover:bg-gray-100 italic" @click="formatText('italic')" title="斜体">I</button>
              <button type="button" class="px-2 py-1 text-xs bg-white border rounded hover:bg-gray-100 underline" @click="formatText('underline')" title="下划线">U</button>
              <span class="border-r mx-1"></span>
              <label class="px-2 py-1 text-xs bg-white border rounded hover:bg-gray-100 cursor-pointer">
                <span>📷 上传图片</span>
                <input type="file" accept="image/png,image/jpeg,image/gif" class="hidden" @change="handleImageUpload" />
              </label>
            </div>
            <!-- 富文本编辑区 -->
            <div
              ref="editorRef"
              class="min-h-[120px] p-3 bg-white outline-none"
              contenteditable="true"
              @input="handleEditorInput"
              v-html="form.richContent"
            ></div>
          </div>
          <p class="text-xs text-gray-500 mt-1">支持富文本编辑，可上传PNG/JPG/GIF图片（最大10MB）</p>
        </div>
        <!-- 已上传图片预览 -->
        <div v-if="uploadedImages.length > 0" class="space-y-2">
          <label class="text-xs font-semibold text-mosquito-ink/70">已上传图片</label>
          <div class="flex flex-wrap gap-2">
            <div v-for="(img, idx) in uploadedImages" :key="idx" class="relative group">
              <img :src="img.url" class="w-20 h-20 object-cover border rounded" />
              <button type="button" class="absolute -top-2 -right-2 w-5 h-5 bg-red-500 text-white rounded-full text-xs opacity-0 group-hover:opacity-100" @click="removeImage(idx)">×</button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="currentStep === 3" class="space-y-4">
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">开始时间</label>
          <input class="mos-input mt-2 w-full" type="date" v-model="form.startDate" />
        </div>
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">结束时间</label>
          <input class="mos-input mt-2 w-full" type="date" v-model="form.endDate" />
        </div>
        <button class="mos-btn mos-btn-accent w-full" @click="saveConfig" :disabled="saving">
          {{ saving ? '保存中...' : '保存配置' }}
        </button>
      </div>

      <div class="flex items-center justify-between">
        <button class="mos-btn mos-btn-secondary" :disabled="currentStep === 0" @click="prevStep">上一步</button>
        <button class="mos-btn mos-btn-accent" :disabled="currentStep === steps.length - 1" @click="nextStep">下一步</button>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { activityService } from '../services/activity'
import type { ActivityStatus } from '../types/activity'

const router = useRouter()
const route = useRoute()
const steps = ['基础信息', '受众与转化', '奖励与预算', '发布设置']
const currentStep = ref(0)
const saving = ref(false)
const uploading = ref(false)
const loading = ref(false)
const editorRef = ref<HTMLElement | null>(null)
const uploadedImages = ref<{ url: string; filename: string }[]>([])

// 从路由参数获取活动 ID
const activityId = ref<number | null>(null)

const form = ref({
  name: '裂变增长计划',
  description: '邀请好友注册，获取双倍奖励。',
  audience: '新注册用户与邀请达人',
  conversion: '完成注册并绑定手机号',
  reward: '每邀请 1 人奖励 20 积分',
  budget: '总预算 50,000 积分',
  richContent: '<p>活动详情描述...</p>',
  startDate: '',
  endDate: ''
})

// 组件挂载时加载活动数据（如果有 ID 参数）
onMounted(async () => {
  const id = route.params.id
  if (id) {
    activityId.value = Number(id)
    await loadActivity(activityId.value)
  }
})

// 加载活动数据
const loadActivity = async (id: number) => {
  loading.value = true
  try {
    const activity = await activityService.getActivityById(id)
    if (activity) {
      // 填充表单数据
      form.value.name = activity.name || ''
      form.value.description = activity.description || ''

      // 解析 JSON 配置字段
      if (activity.targetUsersConfig) {
        try {
          const targetConfig = typeof activity.targetUsersConfig === 'string'
            ? JSON.parse(activity.targetUsersConfig)
            : activity.targetUsersConfig
          form.value.audience = targetConfig.audience || ''
          form.value.conversion = targetConfig.conversion || ''
        } catch (e) {
          console.warn('解析 targetUsersConfig 失败:', e)
        }
      }

      if (activity.pageContentConfig) {
        try {
          const pageConfig = typeof activity.pageContentConfig === 'string'
            ? JSON.parse(activity.pageContentConfig)
            : activity.pageContentConfig
          form.value.reward = pageConfig.rewardDesc || ''
          form.value.budget = pageConfig.budget || ''
          form.value.richContent = pageConfig.richContent || '<p>活动详情...</p>'
          if (pageConfig.images) {
            uploadedImages.value = pageConfig.images
          }
        } catch (e) {
          console.warn('解析 pageContentConfig 失败:', e)
        }
      }

      if (activity.rewardTiersConfig) {
        try {
          const rewardConfig = typeof activity.rewardTiersConfig === 'string'
            ? JSON.parse(activity.rewardTiersConfig)
            : activity.rewardTiersConfig
          form.value.reward = rewardConfig.reward || form.value.reward
          form.value.budget = rewardConfig.budget || form.value.budget
        } catch (e) {
          console.warn('解析 rewardTiersConfig 失败:', e)
        }
      }

      // 解析时间
      if (activity.startTime) {
        form.value.startDate = activity.startTime.split('T')[0]
      }
      if (activity.endTime) {
        form.value.endDate = activity.endTime.split('T')[0]
      }
    }
  } catch (error) {
    console.error('加载活动数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 富文本格式化
const formatText = (command: string) => {
  document.execCommand(command, false)
  editorRef.value?.focus()
}

// 处理编辑器输入
const handleEditorInput = () => {
  if (editorRef.value) {
    form.value.richContent = editorRef.value.innerHTML
  }
}

// 处理图片上传
const handleImageUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 验证文件大小（最大10MB，与后端保持一致）
  if (file.size > 10 * 1024 * 1024) {
    alert('图片大小不能超过10MB')
    return
  }

  // 验证文件类型
  const allowedTypes = ['image/png', 'image/jpeg', 'image/gif']
  if (!allowedTypes.includes(file.type)) {
    alert('仅支持PNG、JPG、GIF格式')
    return
  }

  uploading.value = true
  try {
    let currentActivityId = activityId.value

    // 如果是新活动（没有活动ID），需要先创建活动
    if (!currentActivityId) {
      // 先保存基础信息创建活动
      const activityData = {
        name: form.value.name || '未命名活动',
        description: form.value.description,
        startTime: form.value.startDate ? new Date(form.value.startDate).toISOString() : undefined,
        endTime: form.value.endDate ? new Date(form.value.endDate).toISOString() : undefined,
        status: 'DRAFT' as ActivityStatus,
        targetUsersConfig: JSON.stringify({
          audience: form.value.audience,
          conversion: form.value.conversion
        }),
        pageContentConfig: JSON.stringify({
          description: form.value.description,
          rewardDesc: form.value.reward,
          budget: form.value.budget
        }),
        rewardTiersConfig: JSON.stringify({
          reward: form.value.reward,
          budget: form.value.budget
        }),
        multiLevelRewardConfig: JSON.stringify({})
      }

      const created = await activityService.createActivity(activityData)
      if (created && created.id) {
        currentActivityId = created.id
        activityId.value = currentActivityId
        // 更新路由（可选，让用户可以刷新页面）
        router.replace(`/activity-config/edit/${currentActivityId}`)
      } else {
        alert('请先保存活动基本信息后再上传图片')
        return
      }
    }

    // 调用后端上传接口
    const uploadResult = await activityService.uploadActivityImage(currentActivityId, file)
    // 使用后端返回的URL（这才是真实可访问的路径）
    uploadedImages.value.push({ url: uploadResult.url, filename: uploadResult.filename })

    // 在光标位置插入图片（使用后端URL）
    if (editorRef.value) {
      const img = document.createElement('img')
      img.src = uploadResult.url
      img.className = 'max-w-full h-auto'
      editorRef.value.appendChild(img)
      form.value.richContent = editorRef.value.innerHTML
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    alert('图片上传失败，请重试')
  } finally {
    uploading.value = false
    target.value = '' // 清除文件选择
  }
}

// 移除已上传图片
const removeImage = (index: number) => {
  uploadedImages.value.splice(index, 1)
}

const prevStep = () => {
  if (currentStep.value > 0) currentStep.value--
}

const nextStep = () => {
  if (currentStep.value < steps.length - 1) currentStep.value++
}

const saveConfig = async () => {
  if (!form.value.name || !form.value.startDate || !form.value.endDate) {
    alert('请填写必填字段')
    return
  }

  saving.value = true
  try {
    // 统一前后端契约：四大配置字段
    const activityData = {
      name: form.value.name,
      description: form.value.description,
      startTime: form.value.startDate ? new Date(form.value.startDate).toISOString() : undefined,
      endTime: form.value.endDate ? new Date(form.value.endDate).toISOString() : undefined,
      status: 'DRAFT' as ActivityStatus,
      // 目标用户配置 JSON
      targetUsersConfig: JSON.stringify({
        audience: form.value.audience,
        conversion: form.value.conversion
      }),
      // 页面内容配置 JSON（包含富文本内容）
      pageContentConfig: JSON.stringify({
        description: form.value.description,
        rewardDesc: form.value.reward,
        budget: form.value.budget,
        richContent: form.value.richContent,
        images: uploadedImages.value
      }),
      // 阶梯奖励配置 JSON
      rewardTiersConfig: JSON.stringify({
        reward: form.value.reward,
        budget: form.value.budget
      }),
      // 多级奖励配置（暂时为空，后续可扩展）
      multiLevelRewardConfig: JSON.stringify({})
    }

    let resultId: number
    if (activityId.value) {
      // 更新已有活动
      await activityService.updateActivity(activityId.value, activityData)
      resultId = activityId.value
      alert('活动更新成功')
    } else {
      // 创建新活动
      const created = await activityService.createActivity(activityData)
      resultId = created.id!
      alert('活动创建成功')
    }
    // 跳转到活动详情页
    router.push(`/activity/${resultId}`)
  } catch (error) {
    console.error('保存配置失败:', error)
    alert('保存失败，请重试')
  } finally {
    saving.value = false
  }
}
</script>
