<template>
  <div class="admin-page">
    <Breadcrumb />

    <a-card :bordered="false" class="page-card">
      <template #title>
        <div class="card-title-row">
          <span>优惠码管理</span>
          <a-button type="primary" @click="goEdit()">
            <template #icon><icon-plus /></template>
            新建优惠码
          </a-button>
        </div>
      </template>

      <a-form :model="query" layout="inline" class="filter-form">
        <a-form-item label="关键词">
          <a-input v-model="query.keyword" placeholder="优惠码 / 名称" allow-clear style="width: 200px" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model="query.state" :options="stateOptions" style="width: 120px" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="search"><template #icon><icon-search /></template>搜索</a-button>
            <a-button @click="reset"><template #icon><icon-refresh /></template>重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table
        :data="list"
        :loading="loading"
        :pagination="{
          total: pagination.total,
          current: pagination.current,
          pageSize: pagination.pageSize,
          showTotal: true,
          showPageSize: true
        }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #columns>
          <a-table-column title="优惠码" data-index="code" :width="140">
            <template #cell="{ record }">
              <a-tag color="arcoblue">{{ record.code }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="名称" data-index="name" ellipsis />
          <a-table-column title="折扣" :width="120">
            <template #cell="{ record }">{{ formatDiscount(record) }}</template>
          </a-table-column>
          <a-table-column title="用户范围" :width="100">
            <template #cell="{ record }">{{ record.user_scope === 1 ? '指定用户' : '所有人' }}</template>
          </a-table-column>
          <a-table-column title="商品范围" :width="100">
            <template #cell="{ record }">{{ record.goods_scope === 1 ? '指定商品' : '全部商品' }}</template>
          </a-table-column>
          <a-table-column title="已用/总量" :width="110">
            <template #cell="{ record }">
              {{ record.used_count }} / {{ record.total_limit > 0 ? record.total_limit : '∞' }}
            </template>
          </a-table-column>
          <a-table-column title="状态" :width="90">
            <template #cell="{ record }">
              <a-tag :color="record.state === 1 ? 'green' : 'gray'">
                {{ record.state === 1 ? '启用' : '停用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="有效期" :width="200">
            <template #cell="{ record }">{{ formatValidity(record) }}</template>
          </a-table-column>
          <a-table-column title="操作" :width="100" :fixed="tableFixed('right')">
            <template #cell="{ record }">
              <a-button type="text" size="small" @click="goEdit(record.id)">编辑</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { adminCouponList } from '@/api/coupon'
import { Notification } from '@arco-design/web-vue'
import { formatStoreTime } from '@/utils/storeFormat'
import { useResponsiveTable } from '@/hooks/useResponsiveTable'

const { tableFixed } = useResponsiveTable()

const router = useRouter()
const loading = ref(false)
const list = ref([])

const query = reactive({ keyword: '', state: -1 })
const pagination = reactive({ total: 0, current: 1, pageSize: 15 })

const stateOptions = [
  { label: '全部', value: -1 },
  { label: '启用', value: 1 },
  { label: '停用', value: 0 }
]

const formatDiscount = (row) => {
  if (row.discount_type === 'percent') return `${row.discount_value}% 折扣`
  return `立减 ¥${row.discount_value}`
}

const formatValidity = (row) => {
  const start = row.start_time ? formatStoreTime(row.start_time) : '不限'
  const end = row.end_time ? formatStoreTime(row.end_time) : '不限'
  return `${start} ~ ${end}`
}

const fetchList = async () => {
  try {
    loading.value = true
    const params = {
      keyword: query.keyword || undefined,
      current: pagination.current,
      pagesize: pagination.pageSize
    }
    if (query.state !== -1 && query.state !== '-1') {
      params.state = query.state
    }
    const res = await adminCouponList(params)
    if (!res || res.code !== 0) {
      return Notification.error({ title: '获取失败', content: res?.msg })
    }
    list.value = res.data || []
    pagination.total = res.pagination?.total ?? 0
  } catch (e) {
    Notification.error({ title: '获取失败', content: e.message })
  } finally {
    loading.value = false
  }
}

const search = () => {
  pagination.current = 1
  fetchList()
}

const reset = () => {
  query.keyword = ''
  query.state = -1
  pagination.current = 1
  fetchList()
}

const onPageChange = (p) => {
  pagination.current = p
  fetchList()
}

const onPageSizeChange = (s) => {
  pagination.pageSize = s
  pagination.current = 1
  fetchList()
}

const goEdit = (id) => {
  if (id) router.push(`/goodsManage/goods/couponEdit/${id}`)
  else router.push('/goodsManage/goods/couponEdit')
}

onMounted(fetchList)
</script>

<style scoped>
.admin-page {
  padding: 0 20px 20px;
}
.page-card {
  border-radius: 12px;
}
.card-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.filter-form {
  margin-bottom: 16px;
}
</style>
