<template>
  <view class="page">
    <NavBar :title="isCreate ? '新建活动' : '活动详情'" :showBack="true" />

    <scroll-view class="detail-scroll" scroll-y>
      <view class="section">
        <text class="section-title">基本信息</text>
        <view class="form-item">
          <text class="form-label">活动名称</text>
          <input class="form-input" v-model="form.activityName" placeholder="请输入活动名称" />
        </view>
        <view class="form-item">
          <text class="form-label">活动类型</text>
          <picker :range="typeOptions" range-key="label" :value="typeIndex" @change="onTypeChange" :disabled="!isCreate">
            <view class="form-picker">{{ typeOptions[typeIndex]?.label || '请选择' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">开始时间</text>
          <picker mode="date" :value="form.startTime" @change="onStartDateChange">
            <view class="form-picker">{{ form.startTime || '请选择' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">结束时间</text>
          <picker mode="date" :value="form.endTime" @change="onEndDateChange">
            <view class="form-picker">{{ form.endTime || '请选择' }}</view>
          </picker>
        </view>
      </view>

      <view class="section" v-if="form.activityType === 2 || form.activityType === 3">
        <text class="section-title">优惠规则</text>
        <view class="form-item">
          <text class="form-label">{{ form.activityType === 2 ? '折扣比例(%)' : '满减金额(元)' }}</text>
          <input class="form-input" v-model="form.discountValue" type="digit" placeholder="请输入" />
        </view>
        <view class="form-item" v-if="form.activityType === 3">
          <text class="form-label">满减门槛(元)</text>
          <input class="form-input" v-model="form.thresholdAmount" type="digit" placeholder="请输入满减门槛" />
        </view>
      </view>

      <view class="section" v-if="!isCreate">
        <text class="section-title">统计数据</text>
        <view class="stats-grid" v-if="stats">
          <view class="stat-item"><text class="stat-value">{{ stats.totalOrders || 0 }}</text><text class="stat-label">订单数</text></view>
          <view class="stat-item"><text class="stat-value">{{ formatMoney(stats.totalAmount || 0) }}</text><text class="stat-label">销售额</text></view>
          <view class="stat-item"><text class="stat-value">{{ formatMoney(stats.discountAmount || 0) }}</text><text class="stat-label">优惠金额</text></view>
        </view>
      </view>
    </scroll-view>

    <view class="bottom-actions" v-if="!isCreate">
      <view class="action-row">
        <view v-if="form.status === 0" class="action-btn primary" @click="handlePublish"><text>发布</text></view>
        <view v-if="form.status === 1" class="action-btn warn" @click="handlePause"><text>暂停</text></view>
        <view v-if="form.status === 2" class="action-btn primary" @click="handleResume"><text>恢复</text></view>
        <view class="action-btn grey" @click="handleDelete"><text>删除</text></view>
      </view>
      <view class="save-btn" @click="handleSave"><text>保存</text></view>
    </view>

    <view class="bottom-actions" v-if="isCreate">
      <view class="save-btn" @click="handleCreate"><text>创建活动</text></view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import NavBar from '@/components/NavBar.vue';
import { getActivityById, createActivity, updateActivity, publishActivity, pauseActivity, resumeActivity, deleteActivity, getActivityStatistics } from '@/api/activity';
import { ActivityTypeText } from '@/utils/constants';
import { formatMoney as formatMoneyUtil, showToast, showConfirm } from '@/utils/common';

const typeOptions = [
  { label: ActivityTypeText[1], value: 1 },
  { label: ActivityTypeText[2], value: 2 },
  { label: ActivityTypeText[3], value: 3 },
  { label: ActivityTypeText[4], value: 4 }
];

const isCreate = ref(true);
const typeIndex = ref(0);
const form = ref<any>({ activityType: 1, startTime: '', endTime: '', discountValue: '', thresholdAmount: '' });
const stats = ref<any>(null);
const formatMoney = formatMoneyUtil;

onLoad((options?: Record<string, string>) => {
  const id = options?.id ? Number(options.id) : 0;
  if (id > 0) { isCreate.value = false; loadDetail(id); }
});

const loadDetail = async (id: number) => {
  try {
    const data = await getActivityById(id);
    form.value = data;
    typeIndex.value = typeOptions.findIndex(t => t.value === data.activityType);
    if (typeIndex.value < 0) typeIndex.value = 0;
    loadStats(id);
  } catch { showToast('加载失败'); uni.navigateBack(); }
};

const loadStats = async (id: number) => {
  try { stats.value = await getActivityStatistics(id); } catch (e) { console.error('加载活动统计失败', e); }
};

const onTypeChange = (e: any) => {
  typeIndex.value = e.detail.value;
  form.value.activityType = typeOptions[typeIndex.value].value;
};

const onStartDateChange = (e: any) => { form.value.startTime = e.detail.value; };
const onEndDateChange = (e: any) => { form.value.endTime = e.detail.value; };

const handleCreate = async () => {
  try {
    await createActivity(form.value);
    showToast('创建成功', 'success');
    setTimeout(() => uni.navigateBack(), 1500);
  } catch { showToast('创建失败'); }
};

const handleSave = async () => {
  try {
    await updateActivity(form.value.id, form.value);
    showToast('保存成功', 'success');
  } catch { showToast('保存失败'); }
};

const handlePublish = async () => {
  if (!(await showConfirm('确认发布？'))) return;
  try { await publishActivity(form.value.id); showToast('已发布', 'success'); form.value.status = 1; } catch { showToast('操作失败'); }
};
const handlePause = async () => {
  if (!(await showConfirm('确认暂停？'))) return;
  try { await pauseActivity(form.value.id); showToast('已暂停', 'success'); form.value.status = 2; } catch { showToast('操作失败'); }
};
const handleResume = async () => {
  try { await resumeActivity(form.value.id); showToast('已恢复', 'success'); form.value.status = 1; } catch { showToast('操作失败'); }
};
const handleDelete = async () => {
  if (!(await showConfirm('确认删除？'))) return;
  try { await deleteActivity(form.value.id); showToast('已删除', 'success'); setTimeout(() => uni.navigateBack(), 1500); } catch { showToast('操作失败'); }
};
</script>

<style lang="scss" scoped>
.page { height: 100vh; background: $bg-color-page; display: flex; flex-direction: column; padding-bottom: env(safe-area-inset-bottom); }
.detail-scroll { flex: 1; height: 0; }
.section { background: $bg-color-card; margin-bottom: $spacing-2; padding: $spacing-3 $spacing-4; }
.section-title { display: block; font-size: 28rpx; font-weight: 600; color: $text-color-primary; margin-bottom: $spacing-3; padding-bottom: $spacing-2; border-bottom: 1rpx solid $border-color-light; }
.form-item { display: flex; align-items: center; justify-content: space-between; padding: $spacing-2 0; border-bottom: 1rpx solid $border-color-light; }
.form-item:last-child { border-bottom: none; }
.form-label { font-size: 28rpx; color: $text-color-secondary; flex-shrink: 0; width: 180rpx; }
.form-input { flex: 1; text-align: right; font-size: 28rpx; color: $text-color-primary; }
.form-picker { flex: 1; text-align: right; font-size: 28rpx; color: $text-color-muted; }
.stats-grid { display: flex; }
.stat-item { flex: 1; display: flex; flex-direction: column; align-items: center; padding: $spacing-2; }
.stat-value { font-size: $font-size-xl; font-weight: 700; color: $text-color-primary; margin-bottom: $spacing-1; }
.stat-label { font-size: 22rpx; color: $text-color-muted; }
.bottom-actions { padding: $spacing-3 $spacing-4; padding-bottom: calc(24rpx + env(safe-area-inset-bottom)); background: $bg-color-card; border-top: 1rpx solid $border-color-light; flex-shrink: 0; }
.action-row { display: flex; gap: $spacing-2; margin-bottom: $spacing-3; }
.action-btn { flex: 1; padding: 20rpx 0; border-radius: $radius-base; display: flex; align-items: center; justify-content: center; }
.action-btn text { font-size: 28rpx; font-weight: 500; }
.action-btn.primary { background: $primary-color-bg; } .action-btn.primary text { color: $primary-color-dark; }
.action-btn.warn { background: $warning-color-bg; } .action-btn.warn text { color: $warning-color; }
.action-btn.grey { background: $bg-color-page; } .action-btn.grey text { color: $text-color-secondary; }
.save-btn { width: 100%; background: $primary-color; padding: 28rpx 0; border-radius: $radius-xl; display: flex; align-items: center; justify-content: center; }
.save-btn text { font-size: $font-size-lg; font-weight: 600; color: $text-color-primary; }
</style>

