<template>
  <div class="lotteries-page">
    <div class="page-header">
      <el-button type="primary" @click="openAdd">创建抽奖</el-button>
    </div>
    <div class="table-card">
      <el-table :data="paginatedLotteries">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="cycle" label="周期" width="100">
          <template #default="{ row }">{{ cycleText(row.cycle) }}</template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" width="180">
          <template #default="{ row }">{{ formatTime(row.start_time) }}</template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="180">
          <template #default="{ row }">{{ formatTime(row.end_time) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="addPrize(row.id)">奖品</el-button>
            <el-button link type="success" size="small" @click="draw(row.id)">开奖</el-button>
            <el-button link type="warning" size="small" @click="editLottery(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteLottery(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <el-pagination
          v-model:current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <el-dialog v-model="showAdd" :title="editing ? '编辑抽奖' : '创建抽奖'" width="600px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="抽奖名称" required>
          <el-input v-model="form.name" placeholder="请输入抽奖名称" />
        </el-form-item>
        <el-form-item label="抽奖描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入抽奖描述" />
        </el-form-item>
        <el-form-item label="活动图片">
          <el-upload
            class="lottery-image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            accept="image/*"
          >
            <img v-if="form.image" :src="getImageUrl(form.image)" class="lottery-image" />
            <el-icon v-else class="lottery-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="image-tip">建议尺寸: 400x300px，支持 jpg、png、webp 格式</div>
        </el-form-item>
        <el-form-item label="开始时间" required>
          <el-date-picker
            v-model="form.start_time"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ssZ"
            popper-class="dark-date-picker"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" required>
          <el-date-picker
            v-model="form.end_time"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ssZ"
            popper-class="dark-date-picker"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="抽奖周期">
          <el-select v-model="form.cycle" placeholder="选择周期" popper-class="dark-select-dropdown" style="width: 100%">
            <el-option value="daily" label="每日" />
            <el-option value="weekly" label="每周" />
            <el-option value="monthly" label="每月" />
          </el-select>
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="每日配额">
              <el-input-number v-model="form.daily_quota" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总配额">
              <el-input-number v-model="form.total_quota" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="报名有效期">
          <el-input-number v-model="form.registration_validity" :min="0" style="width: 200px" />
          <span style="margin-left: 8px; color: rgba(255,255,255,0.5)">天</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAdd = false">取消</el-button>
        <el-button type="primary" @click="saveLottery">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showPrize" title="添加奖品" width="500px">
      <el-form :model="prizeForm" label-width="100px">
        <el-form-item label="奖品名称" required>
          <el-input v-model="prizeForm.name" placeholder="请输入奖品名称" />
        </el-form-item>
        <el-form-item label="奖品类型">
          <el-select v-model="prizeForm.type" popper-class="dark-select-dropdown" style="width: 100%">
            <el-option value="physical" label="实物奖品" />
            <el-option value="virtual" label="虚拟奖品" />
            <el-option value="credit" label="购买资格" />
          </el-select>
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="奖品数量">
              <el-input-number v-model="prizeForm.quantity" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中奖权重">
              <el-input-number v-model="prizeForm.weight" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="抽奖模式">
          <el-select v-model="prizeForm.draw_mode" popper-class="dark-select-dropdown" style="width: 100%">
            <el-option value="random" label="随机抽奖" />
            <el-option value="weight" label="权重抽奖" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分奖励" v-if="prizeForm.type === 'credit'">
          <el-input-number v-model="prizeForm.credit_reward" :min="1" style="width: 200px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPrize = false">取消</el-button>
        <el-button type="primary" @click="savePrize">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { adminApi } from '../../api'
import { getImageUrl } from '../../utils/image'

const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/upload'
const uploadHeaders = { Authorization: `Bearer ${localStorage.getItem('token')}` }

const lotteries = ref<any[]>([])
const showAdd = ref(false)
const showPrize = ref(false)
const prizeLotteryId = ref(0)
const editing = ref<any>(null)
const page = ref(1)
const pageSize = 20
const total = computed(() => lotteries.value.length)
const paginatedLotteries = computed(() => {
  const start = (page.value - 1) * pageSize
  return lotteries.value.slice(start, start + pageSize)
})
const form = reactive({
  name: '',
  description: '',
  image: '',
  start_time: '',
  end_time: '',
  cycle: 'daily',
  daily_quota: undefined as number | undefined,
  total_quota: undefined as number | undefined,
  registration_validity: undefined as number | undefined
})
const prizeForm = reactive({
  name: '',
  type: 'physical',
  quantity: 1,
  weight: 1,
  draw_mode: 'random',
  credit_reward: undefined as number | undefined
})

const cycleMap: Record<string, string> = { daily: '每日', weekly: '每周', monthly: '每月' }
function cycleText(s: string) { return cycleMap[s] || s }
function formatTime(t: string) {
  if (!t) return '-'
  return t.replace('T', ' ').replace('Z', '').substring(0, 19)
}

function handlePageChange() {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

function beforeImageUpload(file: File) {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

function handleImageSuccess(response: any) {
  if (response.url) {
    form.image = response.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

async function fetchLotteries() {
  const res: any = await adminApi.getLotteries()
  lotteries.value = res.data || []
}

function openAdd() {
  editing.value = null
  Object.assign(form, { name: '', description: '', image: '', start_time: '', end_time: '', cycle: 'daily', daily_quota: undefined, total_quota: undefined, registration_validity: undefined })
  showAdd.value = true
}

function editLottery(row: any) {
  editing.value = row
  Object.assign(form, {
    name: row.name,
    description: row.description || '',
    image: row.image || '',
    start_time: row.start_time,
    end_time: row.end_time,
    cycle: row.cycle || 'daily',
    daily_quota: row.daily_quota,
    total_quota: row.total_quota,
    registration_validity: row.registration_validity
  })
  showAdd.value = true
}

async function saveLottery() {
  if (!form.name || !form.start_time || !form.end_time) {
    ElMessage.warning('请填写必填项')
    return
  }
  try {
    if (editing.value) {
      await adminApi.updateLottery(editing.value.id, form)
    } else {
      await adminApi.createLottery(form)
    }
    ElMessage.success('保存成功')
    showAdd.value = false
    editing.value = null
    await fetchLotteries()
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

function addPrize(id: number) {
  prizeLotteryId.value = id
  Object.assign(prizeForm, { name: '', type: 'physical', quantity: 1, weight: 1, draw_mode: 'random', credit_reward: undefined })
  showPrize.value = true
}

async function savePrize() {
  if (!prizeForm.name) {
    ElMessage.warning('请输入奖品名称')
    return
  }
  await adminApi.addLotteryPrize(prizeLotteryId.value, prizeForm)
  ElMessage.success('奖品已添加')
  showPrize.value = false
}

async function draw(id: number) {
  await ElMessageBox.confirm('确定执行开奖？此操作不可撤销', '确认开奖')
  await adminApi.drawLottery(id)
  ElMessage.success('开奖完成')
}

async function deleteLottery(id: number) {
  await ElMessageBox.confirm('确定删除此抽奖活动？', '确认删除')
  await adminApi.deleteLottery(id)
  ElMessage.success('删除成功')
  await fetchLotteries()
}

onMounted(fetchLotteries)
</script>

<style scoped lang="scss">
.lotteries-page { padding: 0; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.table-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 20px; }

.lottery-image-uploader {
  :deep(.el-upload) {
    border: 1px dashed rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    width: 200px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #4e6ef2;
    }
  }
}

.lottery-image {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
}

.lottery-uploader-icon {
  font-size: 28px;
  color: rgba(255, 255, 255, 0.4);
}

.image-tip {
  margin-top: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

.pagination-wrap {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pagination-wrap :deep(.el-pagination) {
  --el-pagination-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-text-color: rgba(255, 255, 255, 0.6);
  --el-pagination-button-disabled-bg-color: rgba(255, 255, 255, 0.04);
  --el-pagination-button-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-hover-color: #4e6ef2;
}

.pagination-wrap :deep(.el-pagination .el-pager li) {
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
  margin: 0 4px;
}

.pagination-wrap :deep(.el-pagination .el-pager li:hover),
.pagination-wrap :deep(.el-pagination .el-pager li.is-active) {
  background: #4e6ef2;
  color: #fff;
}

.pagination-wrap :deep(.el-pagination .btn-prev),
.pagination-wrap :deep(.el-pagination .btn-next) {
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
}

.pagination-wrap :deep(.el-pagination .btn-prev:hover),
.pagination-wrap :deep(.el-pagination .btn-next:hover) {
  background: rgba(78, 110, 242, 0.2);
  color: #4e6ef2;
}

.pagination-wrap :deep(.el-pagination__total) {
  color: rgba(255, 255, 255, 0.5);
}
</style>
