/**
 * Coupon Management View
 */

const CouponManagement = {
  setup() {
    const { ref, onMounted } = Vue;
    const list = ref([]);
    const loading = ref(true);

    const fetchCoupons = async () => {
      loading.value = true;
      try {
        const adminPath = window.settings?.secure_path || 'admin';
        const response = await fetch(`/api/v2/${adminPath}/coupon/fetch`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({})
        });
        const result = await response.json();
        if (result.data) {
          list.value = result.data;
        }
      } catch (err) {
        console.error('Fetch coupons failed', err);
      } finally {
        loading.value = false;
      }
    };

    const handleDelete = async (id) => {
      if (!confirm('确定删除吗?')) return;
      try {
        const adminPath = window.settings?.secure_path || 'admin';
        const response = await fetch(`/api/v2/${adminPath}/coupon/drop`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id })
        });
        const result = await response.json();
        if (result.data) {
          fetchCoupons();
        }
      } catch (err) { alert('删除失败'); }
    };

    onMounted(fetchCoupons);

    return { list, loading, handleDelete };
  },
  template: `
    <div class="coupon-management animate-in">
      <div class="page-header">
        <h3>优惠券管理</h3>
        <button class="btn btn-primary">创建优惠券</button>
      </div>

      <div class="card">
        <table class="admin-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>名称</th>
              <th>代码</th>
              <th>类型</th>
              <th>价值</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody v-if="!loading">
            <tr v-for="coupon in list" :key="coupon.id">
              <td>{{ coupon.id }}</td>
              <td>{{ coupon.name }}</td>
              <td><code>{{ coupon.code }}</code></td>
              <td>{{ coupon.type === 1 ? '金额' : '比例' }}</td>
              <td>{{ coupon.type === 1 ? (coupon.value / 100).toFixed(2) : coupon.value + '%' }}</td>
              <td>{{ formatTime(coupon.created_at) }}</td>
              <td class="row-actions">
                <a href="#">编辑</a>
                <span class="sep">|</span>
                <a href="#" class="text-danger" @click.prevent="handleDelete(coupon.id)">删除</a>
              </td>
            </tr>
          </tbody>
        </table>
        <div v-if="loading" class="loading">加载中...</div>
      </div>
    </div>
  `,
  methods: {
    formatTime(ts) {
      if (!ts) return '-';
      return new Date(ts * 1000).toLocaleString();
    }
  }
};

export default CouponManagement;
