<template>
  <AdminLayout :currentPage="currentPage">
    <view class="marketing-groupbuy-list">
      <!-- 1. 过滤搜索栏 -->
      <view class="filter-card border-shadow">
        <view class="filter-row">
          <view class="filter-item">
            <text class="label">活动搜索：</text>
            <input class="input-mock" placeholder="请输入活动名称" v-model="searchQuery" @confirm="handleSearch" />
          </view>
          <view class="filter-btns">
            <button class="btn-query" @click="handleSearch">查询</button>
          </view>
        </view>
      </view>

      <!-- 2. 操作栏 -->
      <view class="action-bar">
        <button class="btn-add" @click="handleAdd">添加团购活动</button>
      </view>

      <!-- 3. 数据表格 -->
      <view class="table-card border-shadow">
        <view class="table-container">
          <!-- Loading 遮罩 -->
          <view v-if="isLoading" class="loading-mask">
            <text class="loading-text">数据加载中...</text>
          </view>
          
          <view class="table-head">
            <view class="th cell-id">ID</view>
            <view class="th cell-product">关联商品</view>
            <view class="th cell-title">活动标题</view>
            <view class="th cell-price">团购价</view>
            <view class="th cell-people">成团人数</view>
            <view class="th cell-stock">库存</view>
            <view class="th cell-time">有效期</view>
            <view class="th cell-status">状态</view>
            <view class="th cell-op">操作</view>
          </view>

          <view class="table-body">
            <view v-if="dataList.length === 0 && !isLoading" class="empty-row">
              <text>暂无团购活动记录</text>
            </view>
            <view v-for="item in dataList" :key="item.id" class="table-row">
              <view class="td cell-id">
                <text class="td-txt-small">{{ item.id }}</text>
              </view>
              <view class="td cell-product">
                <view class="p-info">
                  <image class="p-img" :src="item.product_image || '/static/logo.png'" mode="aspectFill" />
                  <text class="p-name line-clamp-1">{{ item.product_name || '未知商品' }}</text>
                </view>
              </view>
              <view class="td cell-title">
                <text class="td-txt">{{ item.title }}</text>
              </view>
              <view class="td cell-price">
                <text class="td-txt danger">￥{{ item.price }}</text>
              </view>
              <view class="td cell-people">
                <text class="td-txt">{{ item.people }}人</text>
              </view>
              <view class="td cell-stock">
                <text class="td-txt">{{ item.stock }}</text>
              </view>
              <view class="td cell-time">
                <text class="td-txt-small">始: {{ formatTime(item.start_time) }}</text>
                <text class="td-txt-small">终: {{ formatTime(item.stop_time) }}</text>
              </view>
              <view class="td cell-status">
                <view class="switch-mock" :class="{ active: item.status }" @click="toggleStatus(item)">
                  <view class="switch-dot"></view>
                  <text class="switch-txt">{{ item.status ? '开启' : '关闭' }}</text>
                </view>
              </view>
              <view class="td cell-op">
                <view class="op-links">
                  <text class="op-link" @click="handleEdit(item)">编辑</text>
                  <text class="op-split">|</text>
                  <text class="op-link danger" @click="handleDelete(item)">删除</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 4. 分页控制 -->
        <view class="pagination-footer">
          <view class="page-total">
            <text class="total-txt">共 {{ total }} 条</text>
          </view>
          <view class="page-btns">
            <text class="p-btn" :class="{ disabled: page <= 1 }" @click="onPrevPage">‹</text>
            <text class="p-btn active">{{ page }}</text>
            <text class="p-btn" :class="{ disabled: dataList.length < pageSize }" @click="onNextPage">›</text>
          </view>
        </view>
      </view>
    </view>
  </AdminLayout>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import AdminLayout from '@/layouts/admin/AdminLayout.uvue'
import { fetchGroupbuyActivities, saveGroupbuyActivity, deleteGroupbuyActivity, GroupbuyActivity } from '@/services/admin/marketingService.uts'

const currentPage = ref('groupbuy-list')
const dataList = ref<GroupbuyActivity[]>([])
const isLoading = ref(false)
const searchQuery = ref('')
const page = ref(1)
const pageSize = 15
const total = ref(0)

onMounted(() => {
  loadData()
})

async function loadData() {
  isLoading.value = true
  try {
    const res = await fetchGroupbuyActivities({
      search: searchQuery.value,
      page: page.value,
      pageSize: pageSize
    })
    dataList.value = res.items
    total.value = res.total
  } catch (e) {
    uni.showToast({ title: '加载数据失败', icon: 'none' })
  } finally {
    isLoading.value = false
  }
}

function handleSearch() {
  page.value = 1
  loadData()
}

async function toggleStatus(item : GroupbuyActivity) {
  if (item.id == null) return
  const nextStatus = !item.status
  const success = await saveGroupbuyActivity({ ...item, status: nextStatus } as GroupbuyActivity)
  if (success) {
    item.status = nextStatus
    uni.showToast({ title: '修改成功', icon: 'success' })
  }
}

function handleAdd() {
  uni.showToast({ title: '添加功能开发中', icon: 'none' })
}

function handleEdit(item : GroupbuyActivity) {
  uni.showToast({ title: '编辑功能开发中', icon: 'none' })
}

async function handleDelete(item : GroupbuyActivity) {
  if (item.id == null) return
  uni.showModal({
    title: '提示',
    content: '确定要删除该团购活动吗？',
    success: async (res) => {
      if (res.confirm) {
        const success = await deleteGroupbuyActivity(item.id!)
        if (success) {
          uni.showToast({ title: '删除成功' })
          loadData()
        }
      }
    }
  })
}

function onPrevPage() {
  if (page.value > 1) {
    page.value--
    loadData()
  }
}

function onNextPage() {
  if (dataList.value.length >= pageSize) {
    page.value++
    loadData()
  }
}

function formatTime(iso: string): string {
  if (!iso) return '-'
  return iso.substring(0, 10)
}
</script>

<style scoped lang="scss">
.marketing-groupbuy-list {
  min-height: 100vh;
  background: #f0f2f5;
  padding: 16px;
}

.border-shadow {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-card { padding: 24px; margin-bottom: 16px; }
.filter-row { display: flex; flex-direction: row; align-items: center; gap: 24px; }
.filter-item { display: flex; flex-direction: row; align-items: center; }
.label { font-size: 14px; color: #606266; }
.input-mock {
  width: 240px; height: 32px; border: 1px solid #dcdfe6; border-radius: 4px;
  padding: 0 12px; font-size: 13px;
}
.btn-query {
  width: 64px; height: 32px; background-color: #1890ff; color: #fff;
  font-size: 14px; border: none; border-radius: 4px; cursor: pointer;
}

.action-bar { margin-bottom: 16px; }
.btn-add {
  padding: 0 16px; height: 32px; background-color: #1890ff; color: #fff;
  font-size: 14px; border: none; border-radius: 4px; cursor: pointer;
}

.table-card { padding: 24px; position: relative; }
.table-container { min-height: 400px; position: relative; }
.loading-mask {
  position: absolute; top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(255,255,255,0.7); display: flex; align-items: center; justify-content: center; z-index: 10;
}
.loading-text { color: #1890ff; font-size: 14px; }

.table-head {
  display: flex; flex-direction: row; background-color: #f8faff;
  border-bottom: 1px solid #e8eaec;
}
.th { padding: 12px 8px; font-size: 13px; color: #515a6e; font-weight: bold; text-align: center; }

.table-row {
  display: flex; flex-direction: row; border-bottom: 1px solid #e8eaec; align-items: center;
  &:hover { background-color: #fafafa; }
}
.td { padding: 16px 8px; text-align: center; display: flex; align-items: center; justify-content: center; }
.td-txt { font-size: 13px; color: #515a6e; }
.td-txt-small { font-size: 12px; color: #999; display: block; }
.danger { color: #f5222d; }

.cell-id { width: 60px; }
.cell-product { flex: 1.5; justify-content: flex-start; }
.cell-title { flex: 1; }
.cell-price { width: 100px; }
.cell-people { width: 100px; }
.cell-stock { width: 80px; }
.cell-time { width: 160px; }
.cell-status { width: 100px; }
.cell-op { width: 120px; }

.p-info { display: flex; flex-direction: row; align-items: center; gap: 8px; }
.p-img { width: 32px; height: 32px; border-radius: 4px; background: #f5f5f5; }
.p-name { font-size: 12px; color: #1890ff; text-align: left; }
.line-clamp-1 { display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; }

.switch-mock {
  width: 44px; height: 20px; background-color: #bfbfbf; border-radius: 10px;
  position: relative; transition: all 0.3s;
  &.active { background-color: #1890ff; }
}
.switch-dot {
  width: 16px; height: 16px; background-color: #fff; border-radius: 50%;
  position: absolute; top: 2px; left: 2px; transition: left 0.3s;
}
.active .switch-dot { left: 26px; }
.switch-txt { font-size: 10px; color: #fff; position: absolute; right: 6px; top: 2px; }
.active .switch-txt { left: 6px; right: auto; }

.op-links { display: flex; flex-direction: row; gap: 8px; }
.op-link { font-size: 13px; color: #1890ff; cursor: pointer; &.danger { color: #f5222d; } }
.op-split { color: #eee; }.pagination-footer {
  margin-top: 24px; display: flex; flex-direction: row; align-items: center; justify-content: flex-end; gap: 12px;
}
.total-txt { font-size: 13px; color: #999; }
.page-btns { display: flex; flex-direction: row; gap: 8px; }
.p-btn {
  width: 28px; height: 28px; border: 1px solid #dcdfe6; border-radius: 4px;
  display: flex; align-items: center; justify-content: center; font-size: 14px;
  &.active { background: #1890ff; color: #fff; border-color: #1890ff; }
  &.disabled { opacity: 0.5; cursor: not-allowed; }
}
.empty-row { padding: 60px 0; text-align: center; color: #999; }
</style>
