<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchParams.name"
        placeholder="请输入奖品名称"
        clearable
        class="w-200px! mr-12px"
      />
      <el-select
        v-model="searchParams.isEnabled"
        placeholder="是否启用"
        clearable
        class="w-200px! mr-12px"
      >
        <el-option label="是" :value="BooleanFlag.YES" />
        <el-option label="否" :value="BooleanFlag.NO" />
      </el-select>
      <el-button type="primary" @click="refresh">
        <el-icon><IEpSearch /></el-icon>
        搜索
      </el-button>
      <el-button @click="reset">重置</el-button>

      <el-button type="primary" @click="handleAdd">
        <el-icon><IEpPlus /></el-icon>
        新增
      </el-button>

      <el-button type="primary" @click="handleWheelConfig">
        <el-icon class="mr-2"><IEpSetting /></el-icon>
        抽奖配置
      </el-button>
      <el-button class="config-tip-button" @click="configTipVisible = true">
        <el-icon class="mr-2"><IEpInfoFilled /></el-icon>
        配置提示
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <div class="table-wrapper">
        <el-table v-loading="loading" :data="list" height="100%">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="imageUrl" label="图片">
            <template #default="{ row }">
              <el-image
                v-if="row.imageUrl"
                :preview-teleported="true"
                :src="row.imageUrl"
                class="w-20 h-20 object-cover"
                :preview-src-list="[row.imageUrl]"
              />
              <span v-else>暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="奖品数量" />
          <el-table-column prop="probability" label="中奖概率">
            <template #default="{ row }"> {{ row.probability }}% </template>
          </el-table-column>
          <el-table-column prop="isEnabled" label="是否启用">
            <template #default="{ row }">
              {{ row.isEnabled === BooleanFlag.YES ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间">
            <template #default="{ row }">
              {{ dayjs(row.createdAt * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="140">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchParams.current"
          v-model:page-size="searchParams.size"
          :total="total"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="changePageSize"
          @current-change="goToPage"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="510px"
      top="20vh"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称（最多25个字符）" maxlength="25" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <UploadFile v-model="form.imageUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="奖品数量" prop="quantity">
          <el-input-number
            v-model="form.quantity"
            :min="0"
            :max="999999"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="中奖概率" prop="probability">
          <el-input-number
            v-model="form.probability"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.01"
            controls-position="right"
          />
          <span class="ml-2">%</span>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-switch
            v-model="form.isEnabled"
            :active-value="BooleanFlag.YES"
            :inactive-value="BooleanFlag.NO"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          <el-icon class="btn-icon"><IEpUpload /></el-icon>
          保存
        </el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="configTipVisible" width="620px" top="18vh" class="config-tip-dialog">
      <div class="config-tip-panel">
        <div class="config-tip-hero">
          <div class="config-tip-icon">
            <el-icon><IEpInfoFilled /></el-icon>
          </div>
          <div>
            <div class="config-tip-title">转盘配置建议</div>
            <p class="config-tip-subtitle">
              为了保证抽奖逻辑和页面展示效果正常，建议在配置前先确认以下规则。
            </p>
          </div>
        </div>

        <div class="config-tip-list">
          <div class="config-tip-item">
            <div class="config-tip-index">01</div>
            <div class="config-tip-content">
              <div class="config-tip-item-title">中奖概率总和不能超过 100%</div>
              <p>
                所有已启用奖品的中奖概率相加后不得超过 100%。如果总概率小于
                100%，剩余概率将自动落到“祝福语”上，也就是“谢谢参与”。
              </p>
            </div>
          </div>

          <div class="config-tip-item">
            <div class="config-tip-index">02</div>
            <div class="config-tip-content">
              <div class="config-tip-item-title">建议总配置项保持为偶数</div>
              <p>
                “已启用奖品”加上“谢谢参与”后的总数量，建议保持为偶数（如图1）；如果是奇数，转盘分区在页面上的展示会不够协调，视觉效果会受影响（如图2）。
              </p>
              <div class="config-tip-example">
                <el-image
                  v-for="(image, index) in configTipImages"
                  :key="`${image}-${index}`"
                  :src="image"
                  :preview-src-list="configTipImages"
                  :initial-index="index"
                  fit="cover"
                  preview-teleported
                  class="config-tip-example-image"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <WheelConfig ref="wheelConfigRef" />
  </div>
</template>

<script setup lang="tsx">
import { usePageSearch, useResetData } from '@/hooks'
import { getWheelPrizeList, addOrUpdateWheelPrize, deleteWheelPrize } from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'
import type { BackendWheelPrizeListItemDto, BackendAddOrUpdateWheelPrizeDto } from '@/api/backend'
import UploadFile from '@/components/common/UploadFile/index.vue'
import dayjs from 'dayjs'
import WheelConfig from './components/wheelConfigDialog.vue'
import { push } from 'notivue'
import { useMessageBox } from '@/hooks'
import { BooleanFlag } from '@/constants'

const { confirm } = useMessageBox()
const { loading, list, total, reset, goToPage, changePageSize, refresh, searchParams, search } =
  usePageSearch(getWheelPrizeList)

const dialogVisible = ref(false)
const configTipVisible = ref(false)
const configTipImages = [
  'https://soundasia.oss-cn-shenzhen.aliyuncs.com/OA/readName/png/2026/04/03/Common/1775212125999.png',
  'https://soundasia.oss-cn-shenzhen.aliyuncs.com/OA/readName/png/2026/04/03/Common/1775212079319.png',
]
const dialogTitle = computed(() => (form.value.id ? '编辑' : '新增'))
const formRef = ref<FormInstance>()

const [form, resetForm] = useResetData<BackendAddOrUpdateWheelPrizeDto>({
  id: undefined,
  imageUrl: '',
  name: '',
  quantity: 0,
  probability: 0,
  isEnabled: BooleanFlag.YES,
})

const formRules: FormRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入奖品数量', trigger: 'change' }],
  probability: [{ required: true, message: '请输入中奖概率', trigger: 'change' }],
  isEnabled: [{ required: true, message: '请选择是否启用', trigger: 'change' }],
}

const submitLoading = ref(false)

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: BackendWheelPrizeListItemDto) => {
  resetForm()
  form.value = {
    id: row.id,
    name: row.name,
    imageUrl: row.imageUrl,
    quantity: row.quantity,
    probability: row.probability,
    isEnabled: row.isEnabled,
  }
  dialogVisible.value = true
}

const handleDelete = async (row: BackendWheelPrizeListItemDto) => {
  await confirm({
    title: '提示',
    message: `确定要删除奖品"${row.name}"吗?`,
    type: 'danger',
  })

  try {
    await deleteWheelPrize([row.id])
    push.success('删除成功')
    refresh()
  } catch (error) {
    if (error !== 'cancel') {
      push.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    submitLoading.value = true
    await formRef.value.validate()
    await addOrUpdateWheelPrize(form.value)
    push.success(form.value.id ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    if (form.value.id) {
      search()
    } else {
      refresh()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const wheelConfigRef = ref<InstanceType<typeof WheelConfig>>()
const handleWheelConfig = () => {
  wheelConfigRef.value?.open()
}
</script>

<style scoped lang="scss">
.official-tag-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px 0;
  flex-shrink: 0;
}

.table-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  min-height: 0;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  flex-shrink: 0;
}

.btn-icon {
  margin-right: 4px;
}

.config-tip-button {
  border-color: #c9d7ff;
  color: #3b6ff5;
  background: linear-gradient(135deg, #f7faff 0%, #eef4ff 100%);
}

.config-tip-button:hover {
  border-color: #9db7ff;
  color: #2f5de0;
  background: linear-gradient(135deg, #eef4ff 0%, #e4edff 100%);
}

.config-tip-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.config-tip-hero {
  display: flex;
  gap: 16px;
  padding: 18px 20px;
  border-radius: 16px;
  background: linear-gradient(135deg, #f5f8ff 0%, #eef3ff 100%);
  border: 1px solid #dbe6ff;
}

.config-tip-icon {
  width: 44px;
  height: 44px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 14px;
  font-size: 22px;
  color: #3b6ff5;
  background: #fff;
  box-shadow: 0 10px 24px rgba(59, 111, 245, 0.12);
}

.config-tip-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2a44;
  line-height: 1.4;
}

.config-tip-subtitle {
  margin: 6px 0 0;
  font-size: 13px;
  line-height: 1.7;
  color: #5b6475;
}

.config-tip-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.config-tip-item {
  display: flex;
  gap: 14px;
  padding: 18px 20px;
  border-radius: 16px;
  background: #fff;
  border: 1px solid #ebeef5;
  box-shadow: 0 8px 24px rgba(31, 42, 68, 0.05);
}

.config-tip-index {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  border-radius: 12px;
  background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: 0.5px;
}

.config-tip-content {
  flex: 1;
}

.config-tip-item-title {
  margin-bottom: 6px;
  font-size: 15px;
  font-weight: 600;
  color: #1f2a44;
}

.config-tip-content p {
  margin: 0;
  font-size: 13px;
  line-height: 1.8;
  color: #5b6475;
}

.config-tip-example {
  margin-top: 14px;
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.config-tip-example-image {
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e5eaf3;
  box-shadow: 0 8px 20px rgba(31, 42, 68, 0.08);
  cursor: zoom-in;
}

:deep(.config-tip-dialog .el-dialog) {
  border-radius: 20px;
  overflow: hidden;
}

:deep(.config-tip-dialog .el-dialog__header) {
  margin-right: 0;
  padding: 22px 24px 0;
}

:deep(.config-tip-dialog .el-dialog__body) {
  padding: 18px 24px 8px;
}

:deep(.config-tip-dialog .el-dialog__footer) {
  padding: 0 24px 24px;
}
</style>
