<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { Plus, Refresh, VideoPlay, Delete, Search, Goods } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  getSeckillPageApi,
  getSeckillDetailApi,
  createSeckillApi,
  endSeckillApi,
  addSeckillProductApi,
  removeSeckillProductApi
} from '@/api/seckill'
import { getProductPageApi, getProductDetailApi } from '@/api/product'
import type { ProductItem, ProductSkuItem } from '@/api/product'
import type { SeckillActivity, SeckillActivityDetail, SeckillProductItem } from '@/api/seckill'
import { useUserStore } from '@/stores/modules/user'
import { SECKILL_STATUS_MAP } from '@/utils/dict'
import { formatDate } from '@/utils/date'
import SearchBar from '@/components/common/SearchBar.vue'

interface PendingSeckillItem {
  product: ProductItem
  skuOptions: ProductSkuItem[]
  skuId?: number
  seckillPrice?: number
  seckillStock?: number
  perLimit: number
  sort: number
}

const userStore = useUserStore()
const isSuperAdmin = computed(() => userStore.role === 'super_admin')

const loading = ref(false)
const list = ref<SeckillActivity[]>([])
const total = ref(0)

const query = reactive({ current: 1, size: 10 })

// ==================== 创建活动 ====================
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  name: '',
  startTime: '',
  endTime: ''
})
const formRules: FormRules = {
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// ==================== 活动商品管理 ====================
const productDialogVisible = ref(false)
const productDialogLoading = ref(false)
const currentActivity = ref<SeckillActivityDetail | null>(null)
const products = ref<SeckillProductItem[]>([])

const allProductsLoading = ref(false)
const allProducts = ref<ProductItem[]>([])
const allProductsTotal = ref(0)
const allProductQuery = reactive({ current: 1, size: 10, keyword: '' })
const selectedProducts = ref<ProductItem[]>([])
const allProductsTableRef = ref<any>()

const pendingVisible = ref(false)
const pendingLoading = ref(false)
const pendingSaving = ref(false)
const pendingItems = ref<PendingSeckillItem[]>([])
const confirmSaving = ref(false)

async function fetchData() {
  loading.value = true
  try {
    const res = await getSeckillPageApi(query)
    list.value = res.records
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function openAdd() {
  Object.assign(form, { name: '', startTime: '', endTime: '' })
  dialogVisible.value = true
  nextTick(() => formRef.value?.clearValidate())
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate()
  submitting.value = true
  try {
    await createSeckillApi(form)
    ElMessage.success('活动创建成功')
    dialogVisible.value = false
    fetchData()
  } finally {
    submitting.value = false
  }
}

async function handleEnd(row: SeckillActivity) {
  try {
    await ElMessageBox.confirm(
      `确定要提前结束活动【${row.name}】吗？结束后商品将恢复原价`,
      '提示',
      { type: 'warning' }
    )
  } catch {
    return
  }
  await endSeckillApi(row.id)
  ElMessage.success('活动已结束')
  fetchData()
}

async function openProductManager(activity: SeckillActivity) {
  productDialogVisible.value = true
  currentActivity.value = { ...activity, products: [] }
  products.value = []
  allProductQuery.current = 1
  allProductQuery.size = 10
  allProductQuery.keyword = ''
  selectedProducts.value = []
  await Promise.all([loadProducts(), loadAllProducts()])
}

async function loadProducts() {
  if (!currentActivity.value) return
  productDialogLoading.value = true
  try {
    const detail = await getSeckillDetailApi(currentActivity.value.id)
    currentActivity.value = detail
    products.value = detail.products ?? []
  } finally {
    productDialogLoading.value = false
  }
}

async function loadAllProducts() {
  allProductsLoading.value = true
  try {
    const res = await getProductPageApi({
      current: allProductQuery.current,
      size: allProductQuery.size,
      keyword: allProductQuery.keyword,
      status: 1
    })
    allProducts.value = res.records
    allProductsTotal.value = res.total
  } finally {
    allProductsLoading.value = false
  }
}

function searchAllProducts() {
  allProductQuery.current = 1
  selectedProducts.value = []
  allProductsTableRef.value?.clearSelection()
  loadAllProducts()
}

function handleAllProductSizeChange(size: number) {
  allProductQuery.size = size
  allProductQuery.current = 1
  selectedProducts.value = []
  allProductsTableRef.value?.clearSelection()
  loadAllProducts()
}

function handleAllProductPageChange() {
  selectedProducts.value = []
  allProductsTableRef.value?.clearSelection()
  loadAllProducts()
}

function handleSelectionChange(rows: ProductItem[]) {
  selectedProducts.value = rows
}

function canSelectProduct(row: ProductItem) {
  return !existingProductIds.value.has(row.id)
}

async function openAddSelected() {
  if (!selectedProducts.value.length) {
    ElMessage.warning('请先勾选要添加的商品')
    return
  }
  pendingVisible.value = true
  pendingLoading.value = true
  pendingItems.value = []
  let skipped = 0
  try {
    for (const product of selectedProducts.value) {
      try {
        const detail = await getProductDetailApi(product.id)
        const skus = (detail.skuList ?? []).filter(
          (s) => (s.stock ?? 0) > 0 && !existingSkuIds.value.has(s.id)
        )
        if (!skus.length) {
          skipped++
          continue
        }
        const first = skus[0]
        pendingItems.value.push({
          product,
          skuOptions: skus,
          skuId: first.id,
          seckillPrice: round2((first.price ?? 0) * 0.8),
          seckillStock: Math.min(first.stock ?? 0, 999),
          perLimit: 1,
          sort: 0
        })
      } catch {
        skipped++
      }
    }
    if (!pendingItems.value.length) {
      pendingVisible.value = false
      ElMessage.warning(skipped ? '选中的商品没有可添加的规格' : '请先勾选要添加的商品')
      return
    }
    if (skipped > 0) {
      ElMessage.warning(`${skipped} 个商品没有可用规格，已跳过`)
    }
  } finally {
    pendingLoading.value = false
  }
}

function handleProductDialogConfirm() {
  if (selectedProducts.value.length) {
    quickAddSelectedProducts()
    return
  }
  productDialogVisible.value = false
}

async function quickAddSelectedProducts() {
  if (!currentActivity.value || !selectedProducts.value.length) return
  confirmSaving.value = true
  const failed: string[] = []
  let added = 0
  try {
    for (const product of selectedProducts.value) {
      try {
        const detail = await getProductDetailApi(product.id)
        const skus = (detail.skuList ?? []).filter(
          (s) => (s.stock ?? 0) > 0 && !existingSkuIds.value.has(s.id)
        )
        if (!skus.length) {
          failed.push(product.name)
          continue
        }
        const sku = skus[0]
        await addSeckillProductApi({
          activityId: currentActivity.value.id,
          productId: product.id,
          skuId: sku.id,
          originPrice: sku.price ?? 0,
          seckillPrice: round2((sku.price ?? 0) * 0.8),
          seckillStock: Math.min(sku.stock ?? 0, 999),
          perLimit: 1,
          sort: 0
        })
        added++
      } catch {
        failed.push(product.name)
      }
    }
    if (added > 0) ElMessage.success(`已添加 ${added} 个商品`)
    if (failed.length) ElMessage.warning(`${failed.length} 个商品添加失败：${failed.join('、')}`)
    selectedProducts.value = []
    allProductsTableRef.value?.clearSelection()
    await Promise.all([loadProducts(), loadAllProducts()])
    if (!failed.length) productDialogVisible.value = false
  } finally {
    confirmSaving.value = false
  }
}

function handlePendingSkuChange(item: PendingSeckillItem) {
  const sku = item.skuOptions.find((s) => s.id === item.skuId)
  if (sku) {
    item.seckillPrice = round2((sku.price ?? 0) * 0.8)
    item.seckillStock = Math.min(sku.stock ?? 0, 999)
  }
}

async function handleConfirmAdd() {
  if (!currentActivity.value || !pendingItems.value.length) return
  const invalid = pendingItems.value.some(
    (item) =>
      !item.skuId ||
      !item.seckillPrice ||
      item.seckillPrice <= 0 ||
      !item.seckillStock ||
      item.seckillStock < 1
  )
  if (invalid) {
    ElMessage.warning('请补全所有商品的抢购价和库存')
    return
  }
  pendingSaving.value = true
  try {
    for (const item of pendingItems.value) {
      const sku = item.skuOptions.find((s) => s.id === item.skuId)
      await addSeckillProductApi({
        activityId: currentActivity.value.id,
        productId: item.product.id,
        skuId: item.skuId!,
        originPrice: sku?.price ?? 0,
        seckillPrice: item.seckillPrice!,
        seckillStock: item.seckillStock!,
        perLimit: item.perLimit,
        sort: item.sort
      })
    }
    ElMessage.success(`已添加 ${pendingItems.value.length} 个商品`)
    pendingVisible.value = false
    selectedProducts.value = []
    allProductsTableRef.value?.clearSelection()
    await Promise.all([loadProducts(), loadAllProducts()])
  } finally {
    pendingSaving.value = false
  }
}

async function handleRemoveProduct(row: SeckillProductItem) {
  try {
    await ElMessageBox.confirm(
      `确定将【${row.productName} · ${row.skuName}】移出该活动吗？`,
      '移除商品',
      { type: 'warning' }
    )
  } catch {
    return
  }
  await removeSeckillProductApi(row.id)
  ElMessage.success('商品已移除')
  await Promise.all([loadProducts(), loadAllProducts()])
}

const canManage = computed(
  () => isSuperAdmin.value && currentActivity.value?.status !== 1
)
const existingProductIds = computed(
  () => new Set(products.value.map((p) => p.productId))
)
const existingSkuIds = computed(
  () => new Set(products.value.map((p) => p.skuId))
)

function round2(value: number) {
  return Number(value.toFixed(2))
}

function money(value?: number | null) {
  return value == null ? '-' : Number(value).toFixed(2)
}

function discountText(value?: number | null) {
  return value == null || value <= 0 ? '-' : `${Number(value).toFixed(1)}折`
}

function statusType(s: number) {
  return s === 0 ? 'info' : s === 1 ? 'success' : 'warning'
}

onMounted(fetchData)
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <div>
        <h2>限时抢购</h2>
        <p class="page-desc">管理限时秒杀活动场次与商品</p>
      </div>
      <el-button v-if="isSuperAdmin" type="primary" :icon="Plus" @click="openAdd">创建活动</el-button>
    </div>

    <!-- 数据概览 -->
    <el-row :gutter="16">
      <el-col :span="6">
        <el-card shadow="never" class="overview-card">
          <div class="ov-label">进行中活动</div>
          <div class="ov-value text-success">2</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="overview-card">
          <div class="ov-label">未开始活动</div>
          <div class="ov-value text-primary">1</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="overview-card">
          <div class="ov-label">总参与人次</div>
          <div class="ov-value">8,562</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="overview-card">
          <div class="ov-label">活动总销售额</div>
          <div class="ov-value text-danger">¥ 156,890</div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="table-card">
      <SearchBar show-divider>
        <el-button :icon="Refresh" @click="fetchData">刷新</el-button>
      </SearchBar>

      <el-table v-loading="loading" :data="list" stripe>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="活动名称" min-width="220" />
        <el-table-column label="开始时间" width="170">
          <template #default="{ row }">{{ formatDate(row.startTime) }}</template>
        </el-table-column>
        <el-table-column label="结束时间" width="170">
          <template #default="{ row }">{{ formatDate(row.endTime) }}</template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status) as any" size="small">
              {{ SECKILL_STATUS_MAP[row.status as keyof typeof SECKILL_STATUS_MAP] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openProductManager(row as SeckillActivity)">查看商品</el-button>
            <el-button link type="primary" size="small">数据统计</el-button>
            <el-button
              v-if="row.status === 1"
              link
              type="warning"
              size="small"
              :icon="VideoPlay"
              @click="handleEnd(row as SeckillActivity)"
            >结束活动</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="query.current"
          v-model:page-size="query.size"
          :total="total"
          layout="total, prev, pager, next"
          background
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" title="创建抢购活动" width="540px">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" size="large">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="如：618 限时秒杀" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确认创建</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="productDialogVisible"
      :title="`商品管理：${currentActivity?.name ?? ''}`"
      width="1080px"
    >
      <div class="dialog-toolbar">
        <div v-if="currentActivity" class="dialog-tip">
          <span>状态：{{ SECKILL_STATUS_MAP[currentActivity.status as keyof typeof SECKILL_STATUS_MAP] }}</span>
          <span>{{ formatDate(currentActivity.startTime) }} ~ {{ formatDate(currentActivity.endTime) }}</span>
        </div>
        <el-button :icon="Refresh" @click="loadProducts">刷新</el-button>
      </div>

      <div class="section-block">
        <div class="section-title">活动已有商品（{{ products.length }}）</div>
        <div v-loading="productDialogLoading" class="products-body">
          <el-table v-if="products.length" :data="products" stripe>
            <el-table-column label="商品" min-width="220">
              <template #default="{ row }">
                <div class="product-cell">
                  <el-image :src="row.productImage" fit="cover" class="product-thumb">
                    <template #error>
                      <div class="thumb-fallback">
                        <el-icon><Goods /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div class="product-meta">
                    <div class="product-name">{{ row.productName }}</div>
                    <div class="product-sku">{{ row.skuName }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" width="140">
              <template #default="{ row }">
                <div class="price-main">¥{{ money(row.seckillPrice) }}</div>
                <div class="price-origin">原价 ¥{{ money(row.originPrice) }} · {{ discountText(row.discount) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="库存" width="160">
              <template #default="{ row }">
                <div class="stock-line">剩余 {{ row.remainStock }} / 总 {{ row.seckillStock }}</div>
                <el-progress :percentage="row.soldPercent || 0" :stroke-width="6" class="stock-progress" />
              </template>
            </el-table-column>
            <el-table-column prop="perLimit" label="限购" width="70" align="center" />
            <el-table-column prop="sales" label="已售" width="70" align="center" />
            <el-table-column prop="sort" label="排序" width="70" align="center" />
            <el-table-column label="操作" width="90" align="center">
              <template #default="{ row }">
                <el-button
                  v-if="canManage"
                  link
                  type="danger"
                  :icon="Delete"
                  @click="handleRemoveProduct(row as SeckillProductItem)"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="该活动还没有抢购商品" :image-size="70" />
        </div>
      </div>

      <div class="section-block section-gap">
        <div class="section-head">
          <div class="section-title">选择商品</div>
          <div class="section-actions">
            <el-input
              v-model="allProductQuery.keyword"
              placeholder="商品名称 / 品牌"
              clearable
              style="width: 240px"
              @keyup.enter="searchAllProducts"
            />
            <el-button :icon="Search" @click="searchAllProducts">搜索</el-button>
            <el-button
              v-if="canManage"
              type="primary"
              :icon="Plus"
              :disabled="!selectedProducts.length"
              @click="openAddSelected"
            >添加选中商品</el-button>
          </div>
        </div>

        <el-table
          ref="allProductsTableRef"
          v-loading="allProductsLoading"
          :data="allProducts"
          stripe
          :selectable="canSelectProduct"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="商品" min-width="240">
            <template #default="{ row }">
              <div class="product-cell">
                <el-image :src="row.mainImage" fit="cover" class="product-thumb">
                  <template #error>
                    <div class="thumb-fallback">
                      <el-icon><Goods /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="product-meta">
                  <div class="product-name">{{ row.name }}</div>
                  <div class="product-sku">{{ row.categoryName || '未分类' }} · {{ row.brand || '无品牌' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="起售价" width="110">
            <template #default="{ row }">¥{{ money(row.minPrice) }}</template>
          </el-table-column>
          <el-table-column prop="totalStock" label="总库存" width="90" align="center" />
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag v-if="existingProductIds.has((row as ProductItem).id)" type="success" size="small">已加入</el-tag>
              <el-tag v-else type="info" size="small">可添加</el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="allProductQuery.current"
            v-model:page-size="allProductQuery.size"
            :total="allProductsTotal"
            layout="total, prev, pager, next, sizes"
            background
            @size-change="handleAllProductSizeChange"
            @current-change="handleAllProductPageChange"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="confirmSaving" @click="handleProductDialogConfirm">
          {{ selectedProducts.length ? '确认添加' : '确认' }}
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="pendingVisible"
      title="配置抢购商品"
      width="960px"
      append-to-body
    >
      <div v-loading="pendingLoading" class="pending-body">
        <el-table v-if="pendingItems.length" :data="pendingItems" stripe>
          <el-table-column label="商品" min-width="180">
            <template #default="{ row }">
              <div class="product-name">{{ row.product.name }}</div>
              <div class="product-sku">{{ row.product.brand || '无品牌' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="规格" width="220">
            <template #default="{ row }">
              <el-select
                v-model="row.skuId"
                style="width: 100%"
                @change="handlePendingSkuChange(row as PendingSeckillItem)"
              >
                <el-option
                  v-for="s in row.skuOptions"
                  :key="s.id"
                  :label="`${s.skuName}（¥${money(s.price)} / 库存 ${s.stock}）`"
                  :value="s.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="抢购价" width="130">
            <template #default="{ row }">
              <el-input-number
                v-model="row.seckillPrice"
                :min="0.01"
                :precision="2"
                :controls="false"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存" width="120">
            <template #default="{ row }">
              <el-input-number
                v-model="row.seckillStock"
                :min="1"
                :precision="0"
                :controls="false"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="限购" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.perLimit"
                :min="1"
                :precision="0"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="排序" width="90">
            <template #default="{ row }">
              <el-input-number
                v-model="row.sort"
                :min="0"
                :precision="0"
                style="width: 100%"
              />
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="没有可添加的商品规格" :image-size="70" />
      </div>
      <template #footer>
        <el-button @click="pendingVisible = false">取消</el-button>
        <el-button type="primary" :loading="pendingSaving" @click="handleConfirmAdd">确认添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.overview-card {
  :deep(.el-card__body) {
    padding: 20px;
  }
  .ov-label {
    font-size: 13px;
    color: $color-text-secondary;
  }
  .ov-value {
    font-size: 24px;
    font-weight: 600;
    margin-top: 8px;
  }
  .text-success { color: $color-success; }
  .text-primary { color: $brand-primary; }
  .text-danger  { color: $color-danger; }
}

.dialog-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 16px;
}

.dialog-tip {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 13px;
  color: $color-text-secondary;
}

.section-block {
  min-width: 0;
}

.section-gap {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid $color-divider;
}

.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: $color-text-primary;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.products-body,
.pending-body {
  min-height: 180px;
}

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

.product-thumb {
  width: 48px;
  height: 48px;
  flex: none;
  border-radius: $radius-sm;
  background: $bg-hover;
}

.thumb-fallback {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: $color-text-placeholder;
}

.product-meta {
  min-width: 0;
}

.product-name {
  font-weight: 600;
  color: $color-text-primary;
}

.product-sku {
  margin-top: 4px;
  font-size: 12px;
  color: $color-text-secondary;
}

.price-main {
  font-weight: 600;
  color: $color-danger;
}

.price-origin {
  margin-top: 2px;
  font-size: 12px;
  color: $color-text-secondary;
}

.stock-line {
  font-size: 13px;
  color: $color-text-regular;
}

.stock-progress {
  width: 110px;
  margin-top: 6px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0 0;
}
</style>
