<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-select
        v-model="searchParams.isCurrent"
        placeholder="请选择是否是本期奖品"
        clearable
        class="w-200px! mr-12px"
      >
        <el-option label="是" :value="1" />
        <el-option label="否" :value="0" />
      </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="handleLotteryConfig">
        <el-icon class="mr-2"><IEpSetting /></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="isCurrent" label="本期奖品">
            <template #default="{ row }">
              {{ row.isCurrent ? '是' : '否' }}
            </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">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)" :disabled="!!row.isCurrent"
                >编辑</el-button
              >
              <el-button type="danger" link @click="handleDelete(row)" :disabled="!!row.isCurrent"
                >删除</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="30vh"
      :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="isCurrent">
          <el-switch
            v-model="form.isCurrent"
            :active-value="1"
            :inactive-value="0"
            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>

    <LotteryConfig ref="lotteryConfigRef" />
  </div>
</template>

<script setup lang="tsx">
import { usePageSearch, useResetData } from '@/hooks'
import { getLotteryPrizeList, addOrUpdateLotteryPrize, deleteLotteryPrize } from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'
import type { BackendAuctionListItemDto, BackendAddOrUpdateLotteryPrizeDto } from '@/api/backend'
import UploadFile from '@/components/common/UploadFile/index.vue'
import dayjs from 'dayjs'
import LotteryConfig from './components/lotteryConfigDialog.vue'
import { push } from 'notivue'
import { useMessageBox } from '@/hooks'

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

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => (form.value.id ? '编辑' : '新增'))
const formRef = ref<FormInstance>()

// 表单数据
const [form, resetForm] = useResetData<BackendAddOrUpdateLotteryPrizeDto>({
  id: undefined,
  imageUrl: '',
  name: '',
  isCurrent: 0,
})

// 表单验证规则
const formRules: FormRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  isCurrent: [{ required: true, message: '请选择是否展示在前台', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
}

const submitLoading = ref(false)

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

// 编辑
const handleEdit = (row: BackendAddOrUpdateLotteryPrizeDto) => {
  resetForm()
  form.value = {
    ...row,
  }
  dialogVisible.value = true
}

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

  try {
    await deleteLotteryPrize([row.id])
    refresh()
    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()

    if (form.value.id) {
      await addOrUpdateLotteryPrize(form.value)
    } else {
      await addOrUpdateLotteryPrize(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 lotteryConfigRef = ref<InstanceType<typeof LotteryConfig>>()
const handleLotteryConfig = () => {
  lotteryConfigRef.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;

  .search-select {
    width: 200px;
  }
}

// 表格区域
.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;

  .color-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .color-block {
      width: 100%;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #e5e7eb;
      flex: 1;
    }

    .color-text {
      color: #fff;
      font-size: 14px;
      font-weight: 500;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    }
  }
}

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

// 对话框内的颜色显示
.color-value {
  margin-left: 12px;
  color: #606266;
  font-family: monospace;
}

.btn-icon {
  margin-right: 4px;
}
</style>
