<template>
  <div class="marketing-page">
    <el-card shadow="never" class="tabs-card">
      <div class="mkt-tabs">
        <div v-for="t in tabs" :key="t.key" class="mkt-tab" :class="{active:activeTab===t.key}" @click="switchTab(t.key)">
          <span>{{ t.icon }}</span> {{ t.label }}
        </div>
      </div>
    </el-card>

    <!-- 优惠券管理 -->
    <div v-show="activeTab==='coupon'">
      <div class="action-bar"><el-button type="primary" @click="openCoupon()"><el-icon><Plus /></el-icon>新增优惠券</el-button></div>
      <el-card shadow="never">
        <el-table :data="couponList" border v-loading="couponLoad" style="width:100%">
          <el-table-column prop="name" label="名称" min-width="140" />
          <el-table-column label="类型" width="80" align="center"><template #default="{row}"><el-tag :type="row.type==='fixed'?'primary':'success'" size="small">{{ row.type==='fixed'?'满减':'折扣' }}</el-tag></template></el-table-column>
          <el-table-column label="优惠" width="120" align="center"><template #default="{row}">{{ row.type==='fixed'?`满¥${row.min_amount}减¥${row.value}`:`${row.value}折` }}</template></el-table-column>
          <el-table-column label="总量/已用" width="100" align="center"><template #default="{row}">{{ row.total_count||'∞' }}/{{ row.used_count||0 }}</template></el-table-column>
          <el-table-column label="每人限领" width="80" align="center"><template #default="{row}">{{ row.per_limit||1 }}</template></el-table-column>
          <el-table-column label="有效期" min-width="180" align="center"><template #default="{row}">{{ row.start_time||'-' }} ~ {{ row.end_time||'-' }}</template></el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'启用':'停用' }}</el-tag></template></el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{row}"><el-button size="small" @click="openCoupon(row)">编辑</el-button><el-popconfirm title="删除？" @confirm="delCoupon(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrap"><el-pagination v-model:page-size="cpPS" v-model:current-page="cpP" :total="cpTotal" layout="total,prev,pager,next" @current-change="fetchCoupons" /></div>
      </el-card>
    </div>

  <!-- ==================== 营销自动化 ==================== -->
  <div v-show="activeTab==='automation'">
    <div class="action-bar">
      <el-button type="primary" @click="openAuto()"><el-icon><Plus /></el-icon>新增自动化规则</el-button>
      <el-button size="default" @click="fetchAutoStats()">刷新统计</el-button>
    </div>
    <el-row :gutter="12" style="margin-bottom:12px">
      <el-col :span="6"><el-card shadow="never"><div style="font-size:12px;color:#999">累计触发</div><div style="font-size:24px;font-weight:700">{{ autoStats.totalIssued||0 }}</div></el-card></el-col>
      <el-col :span="6"><el-card shadow="never"><div style="font-size:12px;color:#999">购物车召回</div><div style="font-size:24px;font-weight:700;color:#FF6A00">{{ autoStatCnt('cart_remind','ok') }}</div></el-card></el-col>
      <el-col :span="6"><el-card shadow="never"><div style="font-size:12px;color:#999">复购券</div><div style="font-size:24px;font-weight:700;color:#409eff">{{ autoStatCnt('repurchase','ok') }}</div></el-card></el-col>
      <el-col :span="6"><el-card shadow="never"><div style="font-size:12px;color:#999">生日/首单礼</div><div style="font-size:24px;font-weight:700;color:#e74c3c">{{ autoStatCnt('birthday_gift','ok')+autoStatCnt('first_order','ok') }}</div></el-card></el-col>
    </el-row>
    <el-radio-group v-model="autoSub" style="margin-bottom:12px" @change="autoSubChange">
      <el-radio-button value="rules">规则配置</el-radio-button>
      <el-radio-button value="logs">执行日志</el-radio-button>
    </el-radio-group>

    <!-- 规则配置 -->
    <el-card v-show="autoSub==='rules'" shadow="never">
      <el-table :data="autoList" border v-loading="autoLoad" style="width:100%">
        <el-table-column prop="trigger_type" label="触发类型" width="130" align="center"><template #default="{row}">{{ autoTypeLabel(row.trigger_type) }}</template></el-table-column>
        <el-table-column prop="name" label="规则名" min-width="130"><template #default="{row}">{{ row.name }}</template></el-table-column>
        <el-table-column label="关联券" width="130" align="center"><template #default="{row}">{{ row.coupon_name||'未发券' }}</template></el-table-column>
        <el-table-column label="阈值" width="140" align="center"><template #default="{row}">{{ autoThresh(row) }}</template></el-table-column>
        <el-table-column label="最近执行" width="150" align="center"><template #default="{row}">{{ row.last_run_at||'-' }}</template></el-table-column>
        <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.enabled?'success':'info'" size="small">{{ row.enabled?'启用':'停用' }}</el-tag></template></el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{row}">
            <el-button size="small" @click="openAuto(row)">编辑</el-button>
            <el-button size="small" :type="row.enabled?'warning':'success'" @click="toggleAuto(row)">{{ row.enabled?'停用':'启用' }}</el-button>
            <el-button size="small" type="primary" @click="runAuto(row)">立即执行</el-button>
            <el-popconfirm title="删除？" @confirm="delAuto(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 执行日志 -->
    <el-card v-show="autoSub==='logs'" shadow="never">
      <el-table :data="autoLogs" border v-loading="autoLogLoad" style="width:100%">
        <el-table-column label="类型" width="120" align="center"><template #default="{row}">{{ autoTypeLabel(row.trigger_type) }}</template></el-table-column>
        <el-table-column label="用户" width="140"><template #default="{row}">{{ row.nickname||('#'+row.user_id) }}</template></el-table-column>
        <el-table-column label="状态" width="90" align="center"><template #default="{row}"><el-tag :type="autoLogType(row.status)" size="small">{{ {success:'成功',skipped:'跳过',error:'失败'}[row.status]||row.status }}</el-tag></template></el-table-column>
        <el-table-column prop="reason" label="说明" min-width="180"><template #default="{row}">{{ row.reason||'-' }}</template></el-table-column>
        <el-table-column prop="created_at" label="时间" width="160" align="center"></el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <el-pagination background layout="prev, pager, next" :total="autoLogTotal" :page-size="10" :current-page="autoLogP" @current-change="autoLogPage" />
      </div>
    </el-card>

    <!-- 规则编辑弹窗 -->
    <el-dialog v-model="autoVis" title="自动化规则" width="520">
      <el-form label-width="100px">
        <el-form-item label="触发类型">
          <el-select v-model="autoForm.trigger_type" :disabled="!!autoEdit">
            <el-option v-for="t in autoTypes" :key="t.value" :label="t.label" :value="t.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则名"><el-input v-model="autoForm.name" placeholder="规则名称" /></el-form-item>
        <el-form-item label="关联优惠券">
          <el-select v-model="autoForm.coupon_id" clearable placeholder="选择要发放的券(可不发)">
            <el-option v-for="c in couponList" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="autoForm.trigger_type==='cart_remind'" label="召回小时数"><el-input-number v-model="autoForm.threshold_hours" :min="1" /> 小时未下单</el-form-item>
        <el-form-item v-if="autoForm.trigger_type==='repurchase'" label="复购天数"><el-input-number v-model="autoForm.repurchase_days" :min="1" /> 天</el-form-item>
        <el-form-item label="券有效期(天)"><el-input-number v-model="autoForm.valid_days" :min="1" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="autoForm.enabled" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="autoVis=false">取消</el-button><el-button type="primary" @click="saveAuto">保存</el-button></template>
    </el-dialog>
  </div>


    <!-- 秒杀管理 -->
    <div v-show="activeTab==='seckill'">
      <div class="action-bar"><el-button type="primary" @click="openSeckill()"><el-icon><Plus /></el-icon>新增秒杀</el-button></div>
      <el-card shadow="never">
        <el-table :data="seckillList" border v-loading="skLoad" style="width:100%">
          <el-table-column label="商品" min-width="200"><template #default="{row}"><div style="display:flex;align-items:center;gap:8px"><el-image :src="row.image" style="width:40px;height:40px;border-radius:4px" /><span>{{ row.name }}</span></div></template></el-table-column>
          <el-table-column label="原价" width="90" align="center"><template #default="{row}">¥{{ row.original_price||row.price||'?' }}</template></el-table-column>
          <el-table-column label="秒杀价" width="90" align="center"><template #default="{row}"><span style="color:#e74c3c;font-weight:700">¥{{ row.seckill_price }}</span></template></el-table-column>
          <el-table-column label="库存" width="80" align="center"><template #default="{row}">{{ row.stock }}</template></el-table-column>
          <el-table-column label="限购" width="60" align="center"><template #default="{row}">{{ row.per_limit }}</template></el-table-column>
          <el-table-column label="开始/结束" min-width="200" align="center"><template #default="{row}">{{ row.start_time }}<br>{{ row.end_time }}</template></el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'进行':'结束' }}</el-tag></template></el-table-column>
          <el-table-column label="操作" width="120" align="center"><template #default="{row}"><el-button size="small" @click="openSeckill(row)">编辑</el-button><el-popconfirm title="删除？" @confirm="delSeckill(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template></el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 拼团管理 -->
    <div v-show="activeTab==='groupbuy'">
      <div class="action-bar"><el-button type="primary" @click="openGroupBuy()"><el-icon><Plus /></el-icon>新增拼团</el-button></div>
      <el-card shadow="never">
        <el-table :data="groupList" border v-loading="gbLoad" style="width:100%">
          <el-table-column label="商品" min-width="200"><template #default="{row}"><div style="display:flex;align-items:center;gap:8px"><el-image :src="row.image" style="width:40px;height:40px;border-radius:4px" /><span>{{ row.name }}</span></div></template></el-table-column>
          <el-table-column label="原价" width="90" align="center"><template #default="{row}">¥{{ row.original_price||row.price||'?' }}</template></el-table-column>
          <el-table-column label="拼团价" width="90" align="center"><template #default="{row}"><span style="color:#e74c3c;font-weight:700">¥{{ row.group_price }}</span></template></el-table-column>
          <el-table-column label="成团人数" width="80" align="center"><template #default="{row}">{{ row.min_people }}人</template></el-table-column>
          <el-table-column label="库存" width="70" align="center"><template #default="{row}">{{ row.stock }}</template></el-table-column>
          <el-table-column label="开始/结束" min-width="200" align="center"><template #default="{row}">{{ row.start_time }}<br>{{ row.end_time }}</template></el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'进行':'结束' }}</el-tag></template></el-table-column>
          <el-table-column label="操作" width="120" align="center"><template #default="{row}"><el-button size="small" @click="openGroupBuy(row)">编辑</el-button><el-popconfirm title="删除？" @confirm="delGroupBuy(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template></el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 积分设置 -->
    <div v-show="activeTab==='points'">
      <el-card shadow="never">
        <h3 class="section-title">💰 积分设置</h3>
        <el-form label-width="180px" style="max-width:500px">
          <el-form-item label="开启积分"><el-switch v-model="pt.enabled" active-value="1" inactive-value="0" /></el-form-item>
          <el-form-item label="消费1元得"><el-input-number v-model="pt.earn_rate" :min="0" :max="100" style="width:160px" /><span style="margin-left:8px">积分</span></el-form-item>
          <el-form-item label="积分抵扣上限"><el-input-number v-model="pt.max_deduct" :min="0" :max="100" style="width:160px" /><span style="margin-left:8px">%</span></el-form-item>
          <el-form-item label="x积分=1元"><el-input-number v-model="pt.exchange_rate" :min="1" :max="9999" style="width:160px" /></el-form-item>
          <el-form-item label="新用户注册送"><el-input-number v-model="pt.register_give" :min="0" style="width:160px" /><span style="margin-left:8px">积分</span></el-form-item>
          <el-form-item><el-button type="primary" @click="savePoints">保存积分设置</el-button></el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 满减满送 -->
    <div v-show="activeTab==='promotions'">
      <div class="action-bar">
        <el-button type="primary" @click="openPromotion()"><el-icon><Plus /></el-icon>新增活动</el-button>
        <el-select v-model="pmF.status" placeholder="全部状态" clearable style="width:140px" @change="fetchPromotions">
          <el-option label="未开始" :value="0" /><el-option label="进行中" :value="1" />
          <el-option label="已结束" :value="2" /><el-option label="已关闭" :value="3" />
        </el-select>
        <el-select v-model="pmF.type" placeholder="全部类型" clearable style="width:140px" @change="fetchPromotions">
          <el-option label="满减" value="full_reduce" /><el-option label="满送券" value="full_gift_coupon" />
          <el-option label="满送积分" value="full_gift_points" /><el-option label="满件打折" value="full_discount" />
          <el-option label="阶梯满减" value="step_reduce" />
        </el-select>
        <el-input v-model="pmF.keyword" placeholder="搜索活动" clearable style="width:180px" @clear="fetchPromotions" @keyup.enter="fetchPromotions" />
      </div>
      <el-card shadow="never">
        <el-row :gutter="12" style="margin-bottom:16px">
          <el-col :span="6"><div class="stat-card"><div class="num">{{pmStats.total}}</div><div class="lbl">总活动</div></div></el-col>
          <el-col :span="6"><div class="stat-card"><div class="num">{{pmStats.active}}</div><div class="lbl">进行中</div></div></el-col>
          <el-col :span="6"><div class="stat-card"><div class="num">¥{{pmStats.totalBenefit}}</div><div class="lbl">优惠总额</div></div></el-col>
          <el-col :span="6"><div class="stat-card"><div class="num">{{pmStats.participants}}</div><div class="lbl">参与人数</div></div></el-col>
        </el-row>
        <el-table :data="pmList" border v-loading="pmLoad" style="width:100%">
          <el-table-column prop="name" label="活动名称" min-width="160" />
          <el-table-column label="类型" width="90" align="center"><template #default="{row}"><el-tag size="small">{{ {'full_reduce':'满减','full_gift_coupon':'送券','full_gift_points':'送积分','full_discount':'打折','step_reduce':'阶梯'}[row.type]||row.type }}</el-tag></template></el-table-column>
          <el-table-column label="规则" min-width="200"><template #default="{row}">{{ formatRules(row) }}</template></el-table-column>
          <el-table-column label="时间" min-width="220" align="center"><template #default="{row}">{{ row.is_forever?'永久有效':(row.start_time+'~'+(row.end_time||'无期限')) }}</template></el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="pmStatusType(row.status)" size="small">{{ pmStatusLabel(row.status) }}</el-tag></template></el-table-column>
          <el-table-column label="参与" width="60" align="center"><template #default="{row}">{{ row.order_count||0 }}</template></el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="{row}">
              <el-button size="small" @click="openPromotion(row)">编辑</el-button>
              <el-button size="small" :type="row.status===1?'warning':'success'" @click="togglePromotion(row)">{{ row.status===1?'下架':'上架' }}</el-button>
              <el-popconfirm title="删除？" @confirm="delPromotion(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrap"><el-pagination v-model:page-size="pmPS" v-model:current-page="pmP" :total="pmTotal" layout="total,prev,pager,next" @current-change="fetchPromotions" /></div>
      </el-card>
    </div>

    <!-- ===== 会员储值 ===== -->
    <div v-show="activeTab==='recharge'">
      <div style="margin-bottom:12px;display:flex;gap:8px">
        <el-button :type="rcTab==='plans'?'primary':'default'" size="small" @click="rcTab='plans';fetchRechargePlans()">充值套餐管理</el-button>
        <el-button :type="rcTab==='orders'?'primary':'default'" size="small" @click="rcTab='orders';fetchRechargeOrders()">充值订单管理</el-button>
      </div>
      <!-- 充值套餐管理 -->
      <div v-show="rcTab==='plans'">
        <div class="action-bar"><el-button type="primary" @click="openRechargePlan()"><el-icon><Plus /></el-icon>新增套餐</el-button></div>
        <el-card shadow="never">
          <el-table :data="rcPlans" border v-loading="rcPLoad" style="width:100%">
            <el-table-column prop="name" label="套餐名称" width="120" />
            <el-table-column prop="amount" label="充值金额" width="120" align="center"><template #default="{row}"><span style="color:#e74c3c;font-weight:700">¥{{ row.amount }}</span></template></el-table-column>
            <el-table-column prop="give_amount" label="赠送金额" width="100" align="center"><template #default="{row}"><span style="color:#52c41a">+¥{{ row.give_amount||0 }}</span></template></el-table-column>
            <el-table-column prop="give_points" label="赠送积分" width="100" align="center"><template #default="{row}">+{{ row.give_points||0 }}</template></el-table-column>
            <el-table-column prop="sort" label="排序" width="70" align="center" />
            <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.status===1?'success':'warning'" size="small">{{ row.status===1?'上架':'下架' }}</el-tag></template></el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template #default="{row}">
                <el-button size="small" @click="openRechargePlan(row)">编辑</el-button>
                <el-button size="small" :type="row.status===1?'warning':'success'" @click="toggleRechargePlan(row)">{{ row.status===1?'下架':'上架' }}</el-button>
                <el-popconfirm title="删除？" @confirm="delRechargePlan(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <!-- 充值订单管理 -->
      <div v-show="rcTab==='orders'">
        <div style="margin-bottom:12px;display:flex;gap:8px">
          <el-select v-model="rcOStatus" placeholder="全部状态" clearable style="width:140px" @change="rcOP=1;fetchRechargeOrders()">
            <el-option label="待支付" value="pending" />
            <el-option label="已成功" value="success" />
            <el-option label="已失败" value="failed" />
          </el-select>
        </div>
        <el-card shadow="never">
          <el-table :data="rcOrders" border v-loading="rcOLoad" style="width:100%">
            <el-table-column prop="order_no" label="充值单号" width="170" />
            <el-table-column label="用户" width="130"><template #default="{row}">{{ row.nickname||'-' }}<br><span style="font-size:12px;color:#999">{{ row.phone||'-' }}</span></template></el-table-column>
            <el-table-column label="充值金额" width="100" align="center"><template #default="{row}">¥{{ row.amount }}</template></el-table-column>
            <el-table-column label="赠送金额" width="90" align="center"><template #default="{row}">+¥{{ row.give_amount||0 }}</template></el-table-column>
            <el-table-column label="赠送积分" width="90" align="center"><template #default="{row}">+{{ row.give_points||0 }}</template></el-table-column>
            <el-table-column label="支付方式" width="80" align="center"><template #default="{row}">{{ row.payment_method||'-' }}</template></el-table-column>
            <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.status==='success'?'success':'warning'" size="small">{{ row.status==='success'?'已成功':row.status==='pending'?'待支付':'失败' }}</el-tag></template></el-table-column>
            <el-table-column label="时间" width="160" align="center"><template #default="{row}">{{ row.created_at||'-' }}</template></el-table-column>
          </el-table>
          <div class="pagination-wrap"><el-pagination v-model:page-size="rcOPS" v-model:current-page="rcOP" :total="rcOTotal" layout="total,prev,pager,next" @current-change="fetchRechargeOrders" /></div>
        </el-card>
      </div>
    </div>

    <!-- ===== 团购预售 ===== -->
    <div v-show="activeTab==='presale_bulk'">
      <div style="margin-bottom:12px;display:flex;gap:8px">
        <el-button :type="pbTab==='presale_acts'?'primary':'default'" size="small" @click="pbTab='presale_acts'">预售活动管理</el-button>
        <el-button :type="pbTab==='bulk_acts'?'primary':'default'" size="small" @click="pbTab='bulk_acts'">团购活动管理</el-button>
        <el-button :type="pbTab==='presale_orders'?'primary':'default'" size="small" @click="pbTab='presale_orders'">预售订单管理</el-button>
        <el-button :type="pbTab==='bulk_orders'?'primary':'default'" size="small" @click="pbTab='bulk_orders'">团购订单管理</el-button>
      </div>

      <!-- 预售活动管理 -->
      <div v-show="pbTab==='presale_acts'">
        <div class="action-bar">
          <el-button type="primary" @click="openPresale()"><el-icon><Plus /></el-icon>新增预售活动</el-button>
        </div>
        <el-card shadow="never">
          <el-table :data="presaleList" border v-loading="psLoad" style="width:100%">
            <el-table-column prop="name" label="活动名称" min-width="140" />
            <el-table-column label="关联商品" min-width="180">
              <template #default="{row}">
                <div style="display:flex;align-items:center;gap:8px">
                  <el-image :src="row.image" style="width:36px;height:36px;border-radius:4px" fit="cover">
                    <template #error><div style="width:36px;height:36px;background:#eee;border-radius:4px">📷</div></template>
                  </el-image>
                  <span>{{ row.product_name||row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="定金" width="100" align="center">
              <template #default="{row}"><span style="color:#e74c3c;font-weight:700">¥{{ row.deposit }}</span></template>
            </el-table-column>
            <el-table-column label="膨胀金额" width="90" align="center">
              <template #default="{row}">+¥{{ row.deposit_expand||0 }}</template>
            </el-table-column>
            <el-table-column label="总库存" width="70" align="center">
              <template #default="{row}">{{ row.stock }}</template>
            </el-table-column>
            <el-table-column label="限购" width="60" align="center">
              <template #default="{row}">{{ row.per_limit }}</template>
            </el-table-column>
            <el-table-column label="尾款期" min-width="200" align="center">
              <template #default="{row}">{{ row.final_start_time||'-' }}<br>{{ row.final_end_time||'-' }}</template>
            </el-table-column>
            <el-table-column label="预计发货" width="100" align="center">
              <template #default="{row}">{{ row.ship_time||'-' }}</template>
            </el-table-column>
            <el-table-column label="状态" width="70" align="center">
              <template #default="{row}"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'上架':'下架' }}</el-tag></template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template #default="{row}">
                <el-button size="small" @click="openPresale(row)">编辑</el-button>
                <el-button size="small" :type="row.status===1?'warning':'success'" @click="togglePresale(row)">{{ row.status===1?'下架':'上架' }}</el-button>
                <el-popconfirm title="删除？" @confirm="delPresale(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-wrap">
            <el-pagination v-model:page-size="psPS" v-model:current-page="psP" :total="psTotal" layout="total,prev,pager,next" @current-change="fetchPresaleList" />
          </div>
        </el-card>
      </div>

      <!-- 团购活动管理（阶梯团购） -->
      <div v-show="pbTab==='bulk_acts'">
        <div class="action-bar">
          <el-button type="primary" @click="openBulkGroup()"><el-icon><Plus /></el-icon>新增团购活动</el-button>
        </div>
        <el-card shadow="never">
          <el-table :data="bulkGroupList" border v-loading="bgLoad" style="width:100%">
            <el-table-column prop="name" label="活动名称" min-width="140" />
            <el-table-column label="关联商品" min-width="180">
              <template #default="{row}">
                <div style="display:flex;align-items:center;gap:8px">
                  <el-image :src="row.image" style="width:36px;height:36px;border-radius:4px" fit="cover">
                    <template #error><div style="width:36px;height:36px;background:#eee;border-radius:4px">📷</div></template>
                  </el-image>
                  <span>{{ row.product_name||row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="阶梯价格" min-width="200">
              <template #default="{row}">
                <div style="font-size:12px;color:#666">{{ formatStepPrice(row.step_price) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="库存" width="70" align="center">
              <template #default="{row}">{{ row.stock }}</template>
            </el-table-column>
            <el-table-column label="最少成团" width="80" align="center">
              <template #default="{row}">{{ row.min_people }}人</template>
            </el-table-column>
            <el-table-column label="限购" width="60" align="center">
              <template #default="{row}">{{ row.per_limit||'不限' }}</template>
            </el-table-column>
            <el-table-column label="开始/结束" min-width="200" align="center">
              <template #default="{row}">{{ row.start_time }}<br>{{ row.end_time }}</template>
            </el-table-column>
            <el-table-column label="状态" width="70" align="center">
              <template #default="{row}"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'上架':'下架' }}</el-tag></template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template #default="{row}">
                <el-button size="small" @click="openBulkGroup(row)">编辑</el-button>
                <el-button size="small" :type="row.status===1?'warning':'success'" @click="toggleBulkGroup(row)">{{ row.status===1?'下架':'上架' }}</el-button>
                <el-popconfirm title="删除？" @confirm="delBulkGroup(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-wrap">
            <el-pagination v-model:page-size="bgPS" v-model:current-page="bgP" :total="bgTotal" layout="total,prev,pager,next" @current-change="fetchBulkGroupList" />
          </div>
        </el-card>
      </div>

      <!-- 预售订单管理 -->
      <div v-show="pbTab==='presale_orders'">
        <div style="margin-bottom:12px;display:flex;gap:8px">
          <el-select v-model="psOStatus" placeholder="全部状态" clearable style="width:140px" @change="psOP=1;fetchPresaleOrders()">
            <el-option label="待付定金" value="deposit_pending" />
            <el-option label="已付定金" value="deposit_paid" />
            <el-option label="待付尾款" value="final_pending" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </div>
        <el-card shadow="never">
          <el-table :data="presaleOrderList" border v-loading="psOLoad" style="width:100%">
            <el-table-column prop="order_no" label="预售单号" width="180" />
            <el-table-column label="用户" width="120">
              <template #default="{row}">{{ row.nickname||'-' }}<br><span style="font-size:12px;color:#999">{{ row.phone||'-' }}</span></template>
            </el-table-column>
            <el-table-column label="商品" min-width="160">
              <template #default="{row}">
                <div style="display:flex;align-items:center;gap:6px">
                  <el-image :src="row.product_image" style="width:32px;height:32px;border-radius:4px" fit="cover">
                    <template #error><div style="width:32px;height:32px;background:#eee;border-radius:4px">📷</div></template>
                  </el-image>
                  <span>{{ row.product_name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="定金" width="80" align="center">
              <template #default="{row}">¥{{ row.deposit }}</template>
            </el-table-column>
            <el-table-column label="尾款" width="80" align="center">
              <template #default="{row}">¥{{ row.final_payment||0 }}</template>
            </el-table-column>
            <el-table-column label="数量" width="60" align="center">
              <template #default="{row}">{{ row.quantity }}</template>
            </el-table-column>
            <el-table-column label="状态" width="90" align="center">
              <template #default="{row}">
                <el-tag :type="psOStatusTag(row.status)" size="small">{{ psOStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="160" align="center">
              <template #default="{row}">{{ row.created_at||'-' }}</template>
            </el-table-column>
          </el-table>
          <div class="pagination-wrap">
            <el-pagination v-model:page-size="psOPS" v-model:current-page="psOP" :total="psOTotal" layout="total,prev,pager,next" @current-change="fetchPresaleOrders" />
          </div>
        </el-card>
      </div>

      <!-- 团购订单管理 -->
      <div v-show="pbTab==='bulk_orders'">
        <div style="margin-bottom:12px;display:flex;gap:8px">
          <el-select v-model="bgOStatus" placeholder="全部状态" clearable style="width:140px" @change="bgOP=1;fetchBulkGroupOrders()">
            <el-option label="待成团" value="pending" />
            <el-option label="已成团" value="success" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </div>
        <el-card shadow="never">
          <el-table :data="bulkGroupOrderList" border v-loading="bgOLoad" style="width:100%">
            <el-table-column prop="order_no" label="团购单号" width="180" />
            <el-table-column label="用户" width="120">
              <template #default="{row}">{{ row.nickname||'-' }}<br><span style="font-size:12px;color:#999">{{ row.phone||'-' }}</span></template>
            </el-table-column>
            <el-table-column label="商品" min-width="160">
              <template #default="{row}">
                <div style="display:flex;align-items:center;gap:6px">
                  <el-image :src="row.product_image" style="width:32px;height:32px;border-radius:4px" fit="cover">
                    <template #error><div style="width:32px;height:32px;background:#eee;border-radius:4px">📷</div></template>
                  </el-image>
                  <span>{{ row.product_name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="团购价" width="80" align="center">
              <template #default="{row}">¥{{ row.price }}</template>
            </el-table-column>
            <el-table-column label="数量" width="60" align="center">
              <template #default="{row}">{{ row.quantity }}</template>
            </el-table-column>
            <el-table-column label="成团人数" width="70" align="center">
              <template #default="{row}">{{ row.group_count||0 }}人</template>
            </el-table-column>
            <el-table-column label="状态" width="90" align="center">
              <template #default="{row}">
                <el-tag :type="bgOStatusTag(row.status)" size="small">{{ bgOStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="160" align="center">
              <template #default="{row}">{{ row.created_at||'-' }}</template>
            </el-table-column>
          </el-table>
          <div class="pagination-wrap">
            <el-pagination v-model:page-size="bgOPS" v-model:current-page="bgOP" :total="bgOTotal" layout="total,prev,pager,next" @current-change="fetchBulkGroupOrders" />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 优惠券弹窗 -->
    <el-dialog v-model="cpVis" :title="cpEdit?'编辑优惠券':'新增优惠券'" width="500px">
      <el-form :model="cpForm" label-width="100px">
        <el-form-item label="名称" required><el-input v-model="cpForm.name" maxlength="30" /></el-form-item>
        <el-form-item label="类型"><el-radio-group v-model="cpForm.type"><el-radio value="fixed">满减券</el-radio><el-radio value="discount">折扣券</el-radio></el-radio-group></el-form-item>
        <el-form-item :label="cpForm.type==='fixed'?'减免金额':'折扣率'"><el-input-number v-model="cpForm.value" :min="0.01" :precision="2" style="width:200px" /><span style="margin-left:8px">{{ cpForm.type==='fixed'?'元':'折' }}</span></el-form-item>
        <el-form-item label="满额条件"><el-input-number v-model="cpForm.min_amount" :min="0" :precision="2" style="width:200px" /><span style="margin-left:8px">满此金额可用，0为无门槛</span></el-form-item>
        <el-form-item label="发放总量"><el-input-number v-model="cpForm.total_count" :min="0" style="width:200px" /><span style="margin-left:8px">0为不限量</span></el-form-item>
        <el-form-item label="每人限领"><el-input-number v-model="cpForm.per_limit" :min="1" :max="999" style="width:200px" /></el-form-item>
        <el-form-item label="有效期类型"><el-radio-group v-model="cpForm.valid_type"><el-radio value="days">领后N天</el-radio><el-radio value="range">固定日期</el-radio></el-radio-group></el-form-item>
        <el-form-item v-if="cpForm.valid_type==='days'" label="有效天数"><el-input-number v-model="cpForm.valid_days" :min="1" :max="365" style="width:200px" /></el-form-item>
        <template v-if="cpForm.valid_type==='range'">
          <el-form-item label="开始日期"><el-date-picker v-model="cpForm.start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
          <el-form-item label="结束日期"><el-date-picker v-model="cpForm.end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
        </template>
      </el-form>
      <template #footer><el-button @click="cpVis=false">取消</el-button><el-button type="primary" @click="saveCoupon">保存</el-button></template>
    </el-dialog>

    <!-- 秒杀弹窗 -->
    <el-dialog v-model="skVis" :title="skEdit?'编辑秒杀':'新增秒杀'" width="500px">
      <el-form :model="skForm" label-width="100px">
        <el-form-item label="选择商品" required>
          <el-select v-model="skForm.product_id" filterable placeholder="搜索商品" style="width:100%">
            <el-option v-for="p in productList" :key="p.id" :label="p.name" :value="p.id">
              <span style="float:left">{{ p.name }}</span><span style="float:right;color:#999;font-size:12px">¥{{ p.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀价"><el-input-number v-model="skForm.seckill_price" :min="0.01" :precision="2" style="width:200px" /></el-form-item>
        <el-form-item label="秒杀库存"><el-input-number v-model="skForm.stock" :min="1" style="width:200px" /></el-form-item>
        <el-form-item label="每人限购"><el-input-number v-model="skForm.per_limit" :min="1" style="width:200px" /></el-form-item>
        <el-form-item label="开始时间"><el-date-picker v-model="skForm.start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
        <el-form-item label="结束时间"><el-date-picker v-model="skForm.end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="skVis=false">取消</el-button><el-button type="primary" @click="saveSeckill">保存</el-button></template>
    </el-dialog>

    <!-- 拼团弹窗 -->
    <el-dialog v-model="gbVis" :title="gbEdit?'编辑拼团':'新增拼团'" width="500px">
      <el-form :model="gbForm" label-width="100px">
        <el-form-item label="选择商品" required>
          <el-select v-model="gbForm.product_id" filterable placeholder="搜索商品" style="width:100%">
            <el-option v-for="p in productList" :key="p.id" :label="p.name" :value="p.id">
              <span style="float:left">{{ p.name }}</span><span style="float:right;color:#999;font-size:12px">¥{{ p.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拼团价"><el-input-number v-model="gbForm.group_price" :min="0.01" :precision="2" style="width:200px" /></el-form-item>
        <el-form-item label="成团人数"><el-input-number v-model="gbForm.min_people" :min="2" :max="999" style="width:200px" /></el-form-item>
        <el-form-item label="库存"><el-input-number v-model="gbForm.stock" :min="1" style="width:200px" /></el-form-item>
        <el-form-item label="开始时间"><el-date-picker v-model="gbForm.start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
        <el-form-item label="结束时间"><el-date-picker v-model="gbForm.end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="gbVis=false">取消</el-button><el-button type="primary" @click="saveGroupBuy">保存</el-button></template>
    </el-dialog>

    <!-- 满减满送活动弹窗 -->
    <el-dialog v-model="pmVis" :title="pmEdit?'编辑活动':'新增活动'" width="600px" top="5vh">
      <el-form :model="pmForm" label-width="100px">
        <el-form-item label="活动名称" required><el-input v-model="pmForm.name" maxlength="50" /></el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="pmForm.type" style="width:100%">
            <el-option label="满减（满X减Y）" value="full_reduce" />
            <el-option label="满送优惠券" value="full_gift_coupon" />
            <el-option label="满送积分" value="full_gift_points" />
            <el-option label="满件打折" value="full_discount" />
            <el-option label="阶梯满减（多档）" value="step_reduce" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则配置">
          <div v-for="(r,i) in pmForm.rules" :key="i" style="display:flex;gap:8px;margin-bottom:8px;align-items:center">
            <span style="font-size:12px;color:#999;width:70px">{{ r.cond_type==='amount'?'满金额':'满件数' }}</span>
            <el-input-number v-model="r.cond_val" :min="1" :precision="r.cond_type==='amount'?2:0" style="width:120px" @change="updatePromoRules" />
            <span style="font-size:12px;color:#999">{{ pmForm.type==='full_discount'?'打':'减/送' }}</span>
            <el-input-number v-model="r.benefit_val" :min="0.01" :precision="pmForm.type==='full_discount'?1:2" :step="pmForm.type==='full_discount'?0.1:10" style="width:120px" @change="updatePromoRules" />
            <span style="font-size:12px;color:#999">{{ pmForm.type==='full_discount'?'折':'元' }}</span>
            <el-button v-if="pmForm.rules.length>1" type="danger" link @click="removeRule(i)">×</el-button>
          </div>
          <el-button size="small" @click="addRule" v-if="pmForm.type==='step_reduce'">+ 添加阶梯</el-button>
        </el-form-item>
        <el-form-item label="有效时间" v-if="!pmForm.is_forever">
          <el-date-picker v-model="pmForm.start_time" type="datetime" placeholder="开始时间" value-format="YYYY-MM-DD HH:mm:ss" style="width:48%" />
          <span style="margin:0 8px">至</span>
          <el-date-picker v-model="pmForm.end_time" type="datetime" placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" style="width:48%" />
        </el-form-item>
        <el-form-item label="永久有效"><el-switch v-model="pmForm.is_forever" /></el-form-item>
        <el-form-item label="适用商品">
          <el-radio-group v-model="pmForm.scope_type">
            <el-radio value="all">全部商品</el-radio>
            <el-radio value="category">指定分类</el-radio>
            <el-radio value="product">指定商品</el-radio>
            <el-radio value="exclude">排除商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="限购">
          <el-radio-group v-model="pmForm.limit_type">
            <el-radio value="none">不限</el-radio>
            <el-radio value="total">总计限{{pmForm.limit_count}}次</el-radio>
            <el-radio value="daily">每日限{{pmForm.limit_count}}次</el-radio>
          </el-radio-group>
          <el-input-number v-if="pmForm.limit_type!=='none'" v-model="pmForm.limit_count" :min="1" style="width:100px;margin-left:8px" />
        </el-form-item>
        <el-form-item label="活动说明"><el-input v-model="pmForm.description" type="textarea" :rows="2" maxlength="200" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="pmVis=false">取消</el-button><el-button type="primary" @click="savePromotion">保存</el-button></template>
    </el-dialog>

    <!-- 充值套餐弹窗 -->
    <el-dialog v-model="rcPlanVis" :title="rcPlanEdit?'编辑充值套餐':'新增充值套餐'" width="500px">
      <el-form :model="rcPlanForm" label-width="100px">
        <el-form-item label="套餐名称" required><el-input v-model="rcPlanForm.name" placeholder="如：50元" /></el-form-item>
        <el-form-item label="充值金额"><el-input-number v-model="rcPlanForm.amount" :min="0.01" :precision="2" :step="10" style="width:200px" /><span style="margin-left:8px">元</span></el-form-item>
        <el-form-item label="赠送金额"><el-input-number v-model="rcPlanForm.give_amount" :min="0" :precision="2" :step="5" style="width:200px" /><span style="margin-left:8px">元</span></el-form-item>
        <el-form-item label="赠送积分"><el-input-number v-model="rcPlanForm.give_points" :min="0" :step="50" style="width:200px" /></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="rcPlanForm.sort" :min="0" style="width:200px" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="rcPlanVis=false">取消</el-button><el-button type="primary" @click="saveRechargePlan">保存</el-button></template>
    </el-dialog>

    <!-- 预售活动弹窗 -->
    <el-dialog v-model="psVis" :title="psEdit?'编辑预售活动':'新增预售活动'" width="550px">
      <el-form :model="psForm" label-width="110px">
        <el-form-item label="关联商品" required>
          <el-select v-model="psForm.product_id" filterable placeholder="搜索商品" style="width:100%">
            <el-option v-for="p in productList" :key="p.id" :label="p.name" :value="p.id">
              <span style="float:left">{{ p.name }}</span><span style="float:right;color:#999;font-size:12px">¥{{ p.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称" required><el-input v-model="psForm.name" maxlength="50" /></el-form-item>
        <el-form-item label="定金金额"><el-input-number v-model="psForm.deposit" :min="0.01" :precision="2" style="width:200px" /></el-form-item>
        <el-form-item label="膨胀金额"><el-input-number v-model="psForm.deposit_expand" :min="0" :precision="2" style="width:200px" /><span style="margin-left:8px;color:#999;font-size:12px">定金可抵用金额</span></el-form-item>
        <el-form-item label="尾款开始"><el-date-picker v-model="psForm.final_start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
        <el-form-item label="尾款结束"><el-date-picker v-model="psForm.final_end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
        <el-form-item label="预计发货"><el-date-picker v-model="psForm.ship_time" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item>
        <el-form-item label="活动库存"><el-input-number v-model="psForm.stock" :min="1" style="width:200px" /></el-form-item>
        <el-form-item label="每人限购"><el-input-number v-model="psForm.per_limit" :min="1" style="width:200px" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="psVis=false">取消</el-button><el-button type="primary" @click="savePresale">保存</el-button></template>
    </el-dialog>

    <!-- 团购活动弹窗（阶梯团购） -->
    <el-dialog v-model="bgVis" :title="bgEdit?'编辑团购活动':'新增团购活动'" width="550px">
      <el-form :model="bgForm" label-width="110px">
        <el-form-item label="关联商品" required>
          <el-select v-model="bgForm.product_id" filterable placeholder="搜索商品" style="width:100%">
            <el-option v-for="p in productList" :key="p.id" :label="p.name" :value="p.id">
              <span style="float:left">{{ p.name }}</span><span style="float:right;color:#999;font-size:12px">¥{{ p.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称" required><el-input v-model="bgForm.name" maxlength="50" /></el-form-item>
        <el-form-item label="阶梯价格">
          <el-input v-model="bgForm.step_price" type="textarea" :rows="4" style="width:100%" placeholder='[{"min_qty":2,"price":99},{"min_qty":5,"price":89}]' />
          <span style="font-size:12px;color:#999;margin-top:4px;display:block">JSON格式：达到最小购买量时的团购价</span>
        </el-form-item>
        <el-form-item label="活动库存"><el-input-number v-model="bgForm.stock" :min="1" style="width:200px" /></el-form-item>
        <el-form-item label="最少成团人数"><el-input-number v-model="bgForm.min_people" :min="2" style="width:200px" /></el-form-item>
        <el-form-item label="每人限购"><el-input-number v-model="bgForm.per_limit" :min="0" style="width:200px" /><span style="margin-left:8px;color:#999;font-size:12px">0为不限</span></el-form-item>
        <el-form-item label="开始时间"><el-date-picker v-model="bgForm.start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
        <el-form-item label="结束时间"><el-date-picker v-model="bgForm.end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="bgVis=false">取消</el-button><el-button type="primary" @click="saveBulkGroup">保存</el-button></template>
    </el-dialog>
  </div>

  <!-- ==================== 砍价 ==================== -->
  <div v-show="activeTab==='bargain'">
    <div style="margin-bottom:12px;display:flex;gap:8px">
      <el-button :type="bt==='acts'?'primary':'default'" size="small" @click="bt='acts'">砍价活动</el-button>
      <el-button :type="bt==='sessions'?'primary':'default'" size="small" @click="bt='sessions'">砍价单</el-button>
      <el-button :type="bt==='orders'?'primary':'default'" size="small" @click="bt='orders'">砍价订单</el-button>
    </div>

    <!-- 砍价活动管理 -->
    <div v-show="bt==='acts'">
      <div class="action-bar">
        <el-button type="primary" @click="openBargain()"><el-icon><Plus /></el-icon>新增砍价活动</el-button>
      </div>
      <el-card shadow="never">
        <el-table :data="bargainList" border v-loading="bkLoad" style="width:100%">
          <el-table-column prop="name" label="活动名称" min-width="140" />
          <el-table-column label="关联商品" min-width="160">
            <template #default="{row}"><div style="display:flex;align-items:center;gap:8px"><el-image :src="row.image||row.product_image" style="width:36px;height:36px;border-radius:4px" fit="cover"><template #error><div style="width:36px;height:36px;background:#eee;border-radius:4px">📷</div></template></el-image><span>{{ row.product_name||row.name }}</span></div></template>
          </el-table-column>
          <el-table-column label="原价" width="90" align="center"><template #default="{row}">¥{{ row.original_price }}</template></el-table-column>
          <el-table-column label="底价" width="90" align="center"><template #default="{row}"><span style="color:#e74c3c;font-weight:700">¥{{ row.floor_price }}</span></template></el-table-column>
          <el-table-column label="库存" width="70" align="center"><template #default="{row}">{{ row.stock }}</template></el-table-column>
          <el-table-column label="限购" width="60" align="center"><template #default="{row}">{{ row.limit_count||'∞' }}</template></el-table-column>
          <el-table-column label="砍价有效期" width="90" align="center"><template #default="{row}">{{ row.expire_hours }}h</template></el-table-column>
          <el-table-column label="开始/结束" min-width="190" align="center"><template #default="{row}">{{ row.start_time }}<br>{{ row.end_time }}</template></el-table-column>
          <el-table-column label="状态" width="70" align="center"><template #default="{row}"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'进行':'停用' }}</el-tag></template></el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="{row}">
              <el-button size="small" @click="openBargain(row)">编辑</el-button>
              <el-button size="small" :type="row.status===1?'warning':'success'" @click="toggleBargain(row)">{{ row.status===1?'停用':'启用' }}</el-button>
              <el-popconfirm title="删除？" @confirm="delBargain(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pager">
          <el-pagination background layout="total, prev, pager, next" :total="bkTotal" :page-size="bkPS" v-model:current-page="bkP" @current-change="fetchBargainList" />
        </div>
      </el-card>
    </div>

    <!-- 砍价单 -->
    <div v-show="bt==='sessions'">
      <el-card shadow="never">
        <div class="action-bar"><el-button @click="fetchBargainSessions">刷新</el-button></div>
        <el-table :data="bargainSessions" border v-loading="bksLoad" style="width:100%">
          <el-table-column prop="session_no" label="砍价单号" width="180" />
          <el-table-column prop="activity_name" label="活动" min-width="120" />
          <el-table-column prop="nickname" label="发起人" width="100" />
          <el-table-column label="当前价/底价" width="140" align="center"><template #default="{row}">¥{{ row.current_price }} <span style="color:#ccc">/</span> ¥{{ row.floor_price }}</template></el-table-column>
          <el-table-column label="已帮砍" width="80" align="center"><template #default="{row}">{{ row.helped_count }}人</template></el-table-column>
          <el-table-column label="状态" width="100" align="center"><template #default="{row}"><el-tag :type="bkStatusType(row.status)" size="small">{{ bkStatusLabel(row.status) }}</el-tag></template></el-table-column>
          <el-table-column prop="expire_at" label="截止时间" min-width="150" align="center" />
        </el-table>
        <div class="pager"><el-pagination background layout="total, prev, pager, next" :total="bksTotal" :page-size="bksPS" v-model:current-page="bksP" @current-change="fetchBargainSessions" /></div>
      </el-card>
    </div>

    <!-- 砍价订单 -->
    <div v-show="bt==='orders'">
      <el-card shadow="never">
        <div class="action-bar"><el-input v-model="bkoKeyword" placeholder="搜索单号/商品" clearable style="width:220px" @keyup.enter="bkoP=1;fetchBargainOrders()" /><el-button type="primary" @click="bkoP=1;fetchBargainOrders()">搜索</el-button></div>
        <el-table :data="bargainOrders" border v-loading="bkoLoad" style="width:100%">
          <el-table-column prop="order_no" label="订单号" width="180" />
          <el-table-column prop="product_names" label="商品" min-width="160" />
          <el-table-column prop="nickname" label="用户" width="100" />
          <el-table-column label="金额" width="100" align="center"><template #default="{row}"><span style="color:#e74c3c">¥{{ row.pay_amount }}</span></template></el-table-column>
          <el-table-column label="状态" width="110" align="center"><template #default="{row}"><el-tag size="small">{{ orderStatusLabel(row.status) }}</el-tag></template></el-table-column>
          <el-table-column prop="created_at" label="下单时间" min-width="150" align="center" />
        </el-table>
        <div class="pager"><el-pagination background layout="total, prev, pager, next" :total="bkoTotal" :page-size="bkoPS" v-model:current-page="bkoP" @current-change="fetchBargainOrders" /></div>
      </el-card>
    </div>

    <!-- 砍价活动编辑弹窗 -->
    <el-dialog v-model="bkVis" :title="bkEdit?'编辑砍价活动':'新增砍价活动'" width="560px">
      <el-form label-width="110px">
        <el-form-item label="关联商品"><el-select v-model="bkForm.product_id" filterable placeholder="选择商品" style="width:100%"><el-option v-for="p in productList" :key="p.id" :label="p.name" :value="p.id" /></el-select></el-form-item>
        <el-form-item label="活动名称"><el-input v-model="bkForm.name" placeholder="砍价活动名称" /></el-form-item>
        <el-form-item label="活动图"><el-input v-model="bkForm.image" placeholder="图片URL(留空用商品图)" /></el-form-item>
        <el-form-item label="原价"><el-input-number v-model="bkForm.original_price" :min="0" :precision="2" style="width:200px" /></el-form-item>
        <el-form-item label="底价"><el-input-number v-model="bkForm.floor_price" :min="0" :precision="2" style="width:200px" /><span style="margin-left:8px;color:#999">砍到底可下单</span></el-form-item>
        <el-form-item label="活动库存"><el-input-number v-model="bkForm.stock" :min="0" style="width:200px" /></el-form-item>
        <el-form-item label="每人限购"><el-input-number v-model="bkForm.limit_count" :min="0" style="width:200px" /><span style="margin-left:8px;color:#999">0不限</span></el-form-item>
        <el-form-item label="单活动有效期"><el-input-number v-model="bkForm.expire_hours" :min="1" style="width:200px" /><span style="margin-left:8px;color:#999">小时</span></el-form-item>
        <el-form-item label="开始时间"><el-date-picker v-model="bkForm.start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
        <el-form-item label="结束时间"><el-date-picker v-model="bkForm.end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="bkVis=false">取消</el-button><el-button type="primary" @click="saveBargain">保存</el-button></template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })

const tabs = [
  { key:'coupon', icon:'🎫', label:'优惠券管理' },
  { key:'seckill', icon:'⚡', label:'秒杀管理' },
  { key:'groupbuy', icon:'👥', label:'拼团管理' },
  { key:'points', icon:'💰', label:'积分设置' },
  { key:'promotions', icon:'🏷️', label:'满减满送' },
  { key:'recharge', icon:'💎', label:'会员储值' },
  { key:'presale_bulk', icon:'🏪', label:'团购预售' },
  { key:'bargain', icon:'🔪', label:'砍价管理' },
  { key:'automation', icon:'🤖', label:'营销自动化' },
]
const activeTab = ref('coupon')
function switchTab(k) {
  activeTab.value = k
  if(k==='coupon') fetchCoupons()
  else if(k==='seckill') fetchSeckill()
  else if(k==='groupbuy') fetchGroupBuy()
  else if(k==='points') fetchPoints()
  else if(k==='promotions') fetchPromotions()
  else if(k==='recharge') { fetchRechargePlans(); fetchRechargeOrders() }
  else if(k==='presale_bulk') { fetchPresaleList(); fetchBulkGroupList(); fetchPresaleOrders(); fetchBulkGroupOrders() }
  else if(k==='automation') { fetchAutoList(); fetchAutoStats(); fetchAutoLogs() }
}

// 商品列表（通用选择器）
const productList = ref([])
async function fetchProducts() { try { const r = await API.get('/products',{params:{pageSize:999}}); productList.value = r.data.data?.list||[] } catch {} }

// ===== 优惠券 =====
const couponList = ref([]); const couponLoad = ref(false)
const cpP = ref(1); const cpPS = ref(10); const cpTotal = ref(0)
const cpVis = ref(false); const cpEdit = ref(null)
const cpForm = reactive({ name:'', type:'fixed', value:0, min_amount:0, total_count:0, per_limit:1, valid_type:'days', valid_days:30, start_time:'', end_time:'' })

async function fetchCoupons() {
  couponLoad.value = true
  try { const r = await API.get('/coupons'); couponList.value = r.data.data||[]; cpTotal.value = couponList.value.length }
  catch { couponList.value = [] }
  finally { couponLoad.value = false }
}
function openCoupon(row) {
  cpEdit.value = row?.id||null
  if(row) { cpForm.name=row.name; cpForm.type=row.type; cpForm.value=row.value; cpForm.min_amount=row.min_amount; cpForm.total_count=row.total_count; cpForm.per_limit=row.per_limit; cpForm.valid_days=row.valid_days||30; cpForm.start_time=row.start_time||''; cpForm.end_time=row.end_time||''; cpForm.valid_type=row.start_time?'range':'days' }
  else { cpForm.name=''; cpForm.type='fixed'; cpForm.value=0; cpForm.min_amount=0; cpForm.total_count=0; cpForm.per_limit=1; cpForm.valid_type='days'; cpForm.valid_days=30; cpForm.start_time=''; cpForm.end_time='' }
  cpVis.value = true
}
async function saveCoupon() {
  if(!cpForm.name) return ElMessage.warning('请填写名称')
  try {
    if(cpEdit.value) await API.put('/coupons/'+cpEdit.value, cpForm)
    else await API.post('/coupons', cpForm)
    ElMessage.success('保存成功'); cpVis.value=false; fetchCoupons()
  } catch { ElMessage.error('保存失败') }
}
async function delCoupon(id) { try { await API.delete('/coupons/'+id); ElMessage.success('已删除'); fetchCoupons() } catch {} }

// ===== 秒杀 =====
const seckillList = ref([]); const skLoad = ref(false)
const skVis = ref(false); const skEdit = ref(null)
const skForm = reactive({ product_id:null, seckill_price:0, stock:10, per_limit:1, start_time:'', end_time:'' })

async function fetchSeckill() {
  skLoad.value = true
  try { const r = await API.get('/seckill'); seckillList.value = r.data.data||[] }
  catch { seckillList.value = [] }
  finally { skLoad.value = false }
}
function openSeckill(row) {
  skEdit.value = row?.id||null; fetchProducts()
  if(row) { skForm.product_id=row.product_id; skForm.seckill_price=row.seckill_price; skForm.stock=row.stock; skForm.per_limit=row.per_limit; skForm.start_time=row.start_time; skForm.end_time=row.end_time }
  else { skForm.product_id=null; skForm.seckill_price=0; skForm.stock=10; skForm.per_limit=1; skForm.start_time=''; skForm.end_time='' }
  skVis.value = true
}
async function saveSeckill() {
  if(!skForm.product_id) return ElMessage.warning('请选择商品')
  try {
    if(skEdit.value) await API.put('/seckill/'+skEdit.value, skForm)
    else await API.post('/seckill', skForm)
    ElMessage.success('保存成功'); skVis.value=false; fetchSeckill()
  } catch { ElMessage.error('保存失败') }
}
async function delSeckill(id) { try { await API.delete('/seckill/'+id); ElMessage.success('已删除'); fetchSeckill() } catch {} }

// ===== 拼团 =====
const groupList = ref([]); const gbLoad = ref(false)
const gbVis = ref(false); const gbEdit = ref(null)
const gbForm = reactive({ product_id:null, group_price:0, min_people:2, stock:10, start_time:'', end_time:'' })

async function fetchGroupBuy() {
  gbLoad.value = true
  try { const r = await API.get('/group-buy'); groupList.value = r.data.data||[] }
  catch { groupList.value = [] }
  finally { gbLoad.value = false }
}
function openGroupBuy(row) {
  gbEdit.value = row?.id||null; fetchProducts()
  if(row) { gbForm.product_id=row.product_id; gbForm.group_price=row.group_price; gbForm.min_people=row.min_people; gbForm.stock=row.stock; gbForm.start_time=row.start_time; gbForm.end_time=row.end_time }
  else { gbForm.product_id=null; gbForm.group_price=0; gbForm.min_people=2; gbForm.stock=10; gbForm.start_time=''; gbForm.end_time='' }
  gbVis.value = true
}
async function saveGroupBuy() {
  if(!gbForm.product_id) return ElMessage.warning('请选择商品')
  try {
    if(gbEdit.value) await API.put('/group-buy/'+gbEdit.value, gbForm)
    else await API.post('/group-buy', gbForm)
    ElMessage.success('保存成功'); gbVis.value=false; fetchGroupBuy()
  } catch { ElMessage.error('保存失败') }
}
async function delGroupBuy(id) { try { await API.delete('/group-buy/'+id); ElMessage.success('已删除'); fetchGroupBuy() } catch {} }

// ===== 积分设置 =====
const pt = reactive({ enabled:'1', earn_rate:1, max_deduct:50, exchange_rate:100, register_give:100 })
async function fetchPoints() {
  try { const r = await API.get('/config'); const g = r.data.data||{}; const cfg = g.points||[]; cfg.forEach(c=>{ if(c.key in pt) pt[c.key]=c.value }) } catch {}
}
async function savePoints() {
  try {
    const configs = Object.entries(pt).map(([k,v])=>({key:k, value:String(v)}))
    await API.put('/config', {configs})
    ElMessage.success('积分设置已保存')
  } catch { ElMessage.error('保存失败') }
}

// ===== 满减满送 =====
const pmList=ref([]);const pmLoad=ref(false);const pmP=ref(1);const pmPS=ref(10);const pmTotal=ref(0)
const pmF=reactive({keyword:'',type:'',status:''})
const pmStats=reactive({total:0,active:0,totalBenefit:0,participants:0})
const pmVis=ref(false);const pmEdit=ref(null)
const pmForm=reactive({name:'',type:'full_reduce',start_time:'',end_time:'',is_forever:0,scope_type:'all',scope_values:[],rules:[{cond_type:'amount',cond_val:100,benefit_type:'reduce',benefit_val:10}],limit_type:'none',limit_count:0,description:'',sort:0})

function pmStatusType(s){return {0:'info',1:'success',2:'',3:'danger'}[s]||'info'}
function pmStatusLabel(s){return {0:'未开始',1:'进行中',2:'已结束',3:'已关闭'}[s]||'?'}
function formatRules(row){try{const r=typeof row.rules==='string'?JSON.parse(row.rules):(row.rules||[]);return r.map(rr=>{if(row.type==='full_reduce')return '满¥'+rr.cond_val+'减¥'+rr.benefit_val;if(row.type==='full_discount')return '满'+rr.cond_val+'件打'+(rr.benefit_val*10)+'折';if(row.type==='step_reduce')return '满¥'+rr.cond_val+'减¥'+rr.benefit_val;return '满¥'+rr.cond_val+'送'+rr.benefit_val}).join(' | ')}catch{return ''}}
function addRule(){pmForm.rules.push({cond_type:pmForm.type==='full_discount'?'quantity':'amount',cond_val:100,benefit_type:pmForm.type==='full_gift_coupon'?'coupon':pmForm.type==='full_gift_points'?'points':pmForm.type==='full_discount'?'discount':'reduce',benefit_val:10})}
function removeRule(i){pmForm.rules.splice(i,1)}
function updatePromoRules(){}

async function fetchPromotions(){
  pmLoad.value=true
  try{const r=await API.get('/promotions',{params:{page:pmP.value,pageSize:pmPS.value,keyword:pmF.keyword||undefined,type:pmF.type||undefined,status:pmF.status!==''?pmF.status:undefined}})
    pmList.value=r.data.data?.list||[];pmTotal.value=r.data.data?.total||0}catch{pmList.value=[];pmTotal.value=0}
  finally{pmLoad.value=false}
  try{const r=await API.get('/promotions/stats/overview');const d=r.data.data||{};pmStats.total=d.total||0;pmStats.active=d.active||0;pmStats.totalBenefit=d.totalBenefit||0;pmStats.participants=d.participants||0}catch{}
}

function openPromotion(row){
  pmEdit.value=row?.id||null
  if(row){
    const r=typeof row.rules==='string'?JSON.parse(row.rules||'[]'):(row.rules||[])
    pmForm.name=row.name;pmForm.type=row.type;pmForm.start_time=row.start_time||'';pmForm.end_time=row.end_time||''
    pmForm.is_forever=row.is_forever||0;pmForm.scope_type=row.scope_type||'all';pmForm.scope_values=row.scope_values||[]
    pmForm.rules=r.length?r:[{cond_type:'amount',cond_val:100,benefit_type:'reduce',benefit_val:10}]
    pmForm.limit_type=row.limit_type||'none';pmForm.limit_count=row.limit_count||0;pmForm.description=row.description||'';pmForm.sort=row.sort||0
  }else{
    pmForm.name='';pmForm.type='full_reduce';pmForm.start_time='';pmForm.end_time='';pmForm.is_forever=0
    pmForm.scope_type='all';pmForm.scope_values=[];pmForm.rules=[{cond_type:'amount',cond_val:100,benefit_type:'reduce',benefit_val:10}]
    pmForm.limit_type='none';pmForm.limit_count=0;pmForm.description='';pmForm.sort=0
  }
  pmVis.value=true
}

async function savePromotion(){
  if(!pmForm.name)return ElMessage.warning('请输入活动名称')
  try{
    const rulesStr=JSON.stringify(pmForm.rules)
    const data={...pmForm,rules:rulesStr}
    if(pmEdit.value) await API.put('/promotions/'+pmEdit.value,data)
    else await API.post('/promotions',data)
    ElMessage.success('保存成功');pmVis.value=false;fetchPromotions()
  }catch{ElMessage.error('保存失败')}
}

async function togglePromotion(row){try{await API.post('/promotions/'+row.id+'/toggle');ElMessage.success('操作成功');fetchPromotions()}catch{}}
async function delPromotion(id){try{await API.delete('/promotions/'+id);ElMessage.success('已删除');fetchPromotions()}catch{}}

// ===== 会员储值 =====
const rcTab = ref('plans')
const rcPlans = ref([]); const rcPLoad = ref(false)
const rcPlanVis = ref(false); const rcPlanEdit = ref(null)
const rcPlanForm = reactive({ name:'', amount:0, give_amount:0, give_points:0, sort:0 })
const rcOrders = ref([]); const rcOLoad = ref(false)
const rcOP = ref(1); const rcOPS = ref(10); const rcOTotal = ref(0)
const rcOStatus = ref('')

async function fetchRechargePlans() {
  rcPLoad.value = true
  try { const r = await API.get('/recharge/plans'); rcPlans.value = r.data.data||[] }
  catch { rcPlans.value = [] }
  finally { rcPLoad.value = false }
}

function openRechargePlan(row) {
  rcPlanEdit.value = row?.id||null
  if(row) { rcPlanForm.name=row.name; rcPlanForm.amount=row.amount; rcPlanForm.give_amount=row.give_amount||0; rcPlanForm.give_points=row.give_points||0; rcPlanForm.sort=row.sort||0 }
  else { rcPlanForm.name=''; rcPlanForm.amount=0; rcPlanForm.give_amount=0; rcPlanForm.give_points=0; rcPlanForm.sort=0 }
  rcPlanVis.value = true
}

async function saveRechargePlan() {
  if(!rcPlanForm.name) return ElMessage.warning('请输入套餐名称')
  if(!rcPlanForm.amount||rcPlanForm.amount<=0) return ElMessage.warning('充值金额必须大于0')
  try {
    if(rcPlanEdit.value) await API.put('/recharge/plans/'+rcPlanEdit.value, rcPlanForm)
    else await API.post('/recharge/plans', rcPlanForm)
    ElMessage.success('保存成功'); rcPlanVis.value=false; fetchRechargePlans()
  } catch { ElMessage.error('保存失败') }
}

async function delRechargePlan(id) {
  try { await API.delete('/recharge/plans/'+id); ElMessage.success('已删除'); fetchRechargePlans() } catch {}
}

async function toggleRechargePlan(row) {
  try { await API.put('/recharge/plans/'+row.id+'/toggle'); ElMessage.success('操作成功'); fetchRechargePlans() } catch {}
}

async function fetchRechargeOrders() {
  rcOLoad.value = true
  try {
    const params = { page: rcOP.value, pageSize: rcOPS.value }
    if(rcOStatus.value) params.status = rcOStatus.value
    const r = await API.get('/recharge/orders', { params }); const d = r.data.data||{}
    rcOrders.value = d.list||[]; rcOTotal.value = d.total||0
  } catch { rcOrders.value = []; rcOTotal.value = 0 }
  finally { rcOLoad.value = false }
}

// ===== 团购预售（预售+阶梯团购） =====
const pbTab = ref('presale_acts')

// 预售活动管理
const presaleList = ref([]); const psLoad = ref(false)
const psP = ref(1); const psPS = ref(10); const psTotal = ref(0)
const psVis = ref(false); const psEdit = ref(null)
const psForm = reactive({
  product_id:null, name:'', deposit:0, deposit_expand:0,
  final_start_time:'', final_end_time:'', ship_time:'',
  stock:10, per_limit:1
})

async function fetchPresaleList() {
  psLoad.value = true
  try {
    const r = await API.get('/presale', { params:{ page:psP.value, pageSize:psPS.value } })
    const d = r.data.data||{}
    presaleList.value = d.list||[]; psTotal.value = d.total||0
  } catch { presaleList.value = []; psTotal.value = 0 }
  finally { psLoad.value = false }
}

function openPresale(row) {
  psEdit.value = row?.id||null; fetchProducts()
  if(row) {
    psForm.product_id=row.product_id; psForm.name=row.name
    psForm.deposit=row.deposit; psForm.deposit_expand=row.deposit_expand||0
    psForm.final_start_time=row.final_start_time||''; psForm.final_end_time=row.final_end_time||''
    psForm.ship_time=row.ship_time||''; psForm.stock=row.stock; psForm.per_limit=row.per_limit
  } else {
    psForm.product_id=null; psForm.name=''; psForm.deposit=0; psForm.deposit_expand=0
    psForm.final_start_time=''; psForm.final_end_time=''; psForm.ship_time=''
    psForm.stock=10; psForm.per_limit=1
  }
  psVis.value = true
}

async function savePresale() {
  if(!psForm.name) return ElMessage.warning('请填写活动名称')
  if(!psForm.product_id) return ElMessage.warning('请选择商品')
  try {
    if(psEdit.value) await API.put('/presale/'+psEdit.value, psForm)
    else await API.post('/presale', psForm)
    ElMessage.success('保存成功'); psVis.value=false; fetchPresaleList()
  } catch { ElMessage.error('保存失败') }
}

async function togglePresale(row) {
  try { await API.put('/presale/'+row.id+'/toggle'); ElMessage.success('操作成功'); fetchPresaleList() } catch {}
}

async function delPresale(id) {
  try { await API.delete('/presale/'+id); ElMessage.success('已删除'); fetchPresaleList() } catch {}
}

// 团购活动管理（阶梯团购）
const bulkGroupList = ref([]); const bgLoad = ref(false)
const bgP = ref(1); const bgPS = ref(10); const bgTotal = ref(0)
const bgVis = ref(false); const bgEdit = ref(null)
const bgForm = reactive({
  product_id:null, name:'', step_price:'', stock:10, min_people:2, per_limit:0,
  start_time:'', end_time:''
})

function formatStepPrice(step) {
  if(!step) return ''
  try {
    const arr = typeof step==='string' ? JSON.parse(step) : step
    return (arr||[]).map(s=>'≥'+s.min_qty+'件 ¥'+s.price).join(' | ')
  } catch { return '' }
}

async function fetchBulkGroupList() {
  bgLoad.value = true
  try {
    const r = await API.get('/bulk-group', { params:{ page:bgP.value, pageSize:bgPS.value } })
    const d = r.data.data||{}
    bulkGroupList.value = d.list||[]; bgTotal.value = d.total||0
  } catch { bulkGroupList.value = []; bgTotal.value = 0 }
  finally { bgLoad.value = false }
}

function openBulkGroup(row) {
  bgEdit.value = row?.id||null; fetchProducts()
  if(row) {
    bgForm.product_id=row.product_id; bgForm.name=row.name
    bgForm.step_price = typeof row.step_price==='string' ? row.step_price : JSON.stringify(row.step_price||[])
    bgForm.stock=row.stock; bgForm.min_people=row.min_people
    bgForm.per_limit=row.per_limit||0; bgForm.start_time=row.start_time||''; bgForm.end_time=row.end_time||''
  } else {
    bgForm.product_id=null; bgForm.name=''; bgForm.step_price=''
    bgForm.stock=10; bgForm.min_people=2; bgForm.per_limit=0
    bgForm.start_time=''; bgForm.end_time=''
  }
  bgVis.value = true
}

async function saveBulkGroup() {
  if(!bgForm.name) return ElMessage.warning('请填写活动名称')
  if(!bgForm.product_id) return ElMessage.warning('请选择商品')
  if(!bgForm.step_price) return ElMessage.warning('请填写阶梯价格')
  let stepPrice
  try {
    stepPrice = typeof bgForm.step_price==='string' ? JSON.parse(bgForm.step_price) : bgForm.step_price
  } catch { return ElMessage.warning('阶梯价格JSON格式错误，请检查') }
  const payload = { ...bgForm, step_price: JSON.stringify(stepPrice) }
  try {
    if(bgEdit.value) await API.put('/bulk-group/'+bgEdit.value, payload)
    else await API.post('/bulk-group', payload)
    ElMessage.success('保存成功'); bgVis.value=false; fetchBulkGroupList()
  } catch { ElMessage.error('保存失败') }
}

async function toggleBulkGroup(row) {
  try { await API.put('/bulk-group/'+row.id+'/toggle'); ElMessage.success('操作成功'); fetchBulkGroupList() } catch {}
}

async function delBulkGroup(id) {
  try { await API.delete('/bulk-group/'+id); ElMessage.success('已删除'); fetchBulkGroupList() } catch {}
}

// 预售订单管理
const presaleOrderList = ref([]); const psOLoad = ref(false)
const psOP = ref(1); const psOPS = ref(10); const psOTotal = ref(0)
const psOStatus = ref('')

function psOStatusTag(s) {
  return { deposit_pending:'warning', deposit_paid:'primary', final_pending:'', completed:'success', cancelled:'info' }[s]||'info'
}
function psOStatusLabel(s) {
  return { deposit_pending:'待付定金', deposit_paid:'已付定金', final_pending:'待付尾款', completed:'已完成', cancelled:'已取消' }[s]||s
}

async function fetchPresaleOrders() {
  psOLoad.value = true
  try {
    const params = { page: psOP.value, pageSize: psOPS.value }
    if(psOStatus.value) params.status = psOStatus.value
    const r = await API.get('/presale/orders', { params })
    const d = r.data.data||{}
    presaleOrderList.value = d.list||[]; psOTotal.value = d.total||0
  } catch { presaleOrderList.value = []; psOTotal.value = 0 }
  finally { psOLoad.value = false }
}

// 团购订单管理
const bulkGroupOrderList = ref([]); const bgOLoad = ref(false)
const bgOP = ref(1); const bgOPS = ref(10); const bgOTotal = ref(0)
const bgOStatus = ref('')

function bgOStatusTag(s) {
  return { pending:'warning', success:'primary', shipped:'', completed:'success', cancelled:'info' }[s]||'info'
}
function bgOStatusLabel(s) {
  return { pending:'待成团', success:'已成团', shipped:'已发货', completed:'已完成', cancelled:'已取消' }[s]||s
}

async function fetchBulkGroupOrders() {
  bgOLoad.value = true
  try {
    const params = { page: bgOP.value, pageSize: bgOPS.value }
    if(bgOStatus.value) params.status = bgOStatus.value
    const r = await API.get('/bulk-group/orders', { params })
    const d = r.data.data||{}
    bulkGroupOrderList.value = d.list||[]; bgOTotal.value = d.total||0
  } catch { bulkGroupOrderList.value = []; bgOTotal.value = 0 }
  finally { bgOLoad.value = false }
}

// ==================== 砍价 ====================
const bt = ref('acts')
const bargainList = ref([]); const bkLoad = ref(false)
const bkP = ref(1); const bkPS = ref(10); const bkTotal = ref(0)
const bkVis = ref(false); const bkEdit = ref(null)
const bkForm = reactive({
  product_id:null, name:'', image:'', original_price:0, floor_price:0,
  stock:10, limit_count:0, expire_hours:24, start_time:'', end_time:''
})
const bargainSessions = ref([]); const bksLoad = ref(false)
const bksP = ref(1); const bksPS = ref(10); const bksTotal = ref(0)
const bargainOrders = ref([]); const bkoLoad = ref(false)
const bkoP = ref(1); const bkoPS = ref(10); const bkoTotal = ref(0); const bkoKeyword = ref('')
const BK_STATUS_MAP = { bargaining:'砍价中', can_order:'可下单', ordered:'已下单', expired:'已过期' }
function bkStatusLabel(s){ return BK_STATUS_MAP[s]||s||'-' }
function bkStatusType(s){ return { can_order:'success', ordered:'primary', expired:'info', bargaining:'warning' }[s]||'info' }
function orderStatusLabel(s){ const m={pending_pay:'待付款',pending_ship:'待发货',shipped:'已发货',received:'已收货',completed:'已完成',closed:'已关闭'}; return m[s]||s||'-' }

async function fetchBargainList() {
  bkLoad.value = true
  try {
    const r = await API.get('/bargain/list', { params:{ page:bkP.value, pageSize:bkPS.value } })
    const d = r.data.data||{}
    bargainList.value = d.list||[]; bkTotal.value = d.total||0
  } catch { bargainList.value = []; bkTotal.value = 0 }
  finally { bkLoad.value = false }
}

function openBargain(row) {
  bkEdit.value = row?.id||null; fetchProducts()
  if(row) {
    bkForm.product_id=row.product_id; bkForm.name=row.name; bkForm.image=row.image||''
    bkForm.original_price=row.original_price; bkForm.floor_price=row.floor_price
    bkForm.stock=row.stock; bkForm.limit_count=row.limit_count||0; bkForm.expire_hours=row.expire_hours||24
    bkForm.start_time=row.start_time||''; bkForm.end_time=row.end_time||''
  } else {
    bkForm.product_id=null; bkForm.name=''; bkForm.image=''
    bkForm.original_price=0; bkForm.floor_price=0; bkForm.stock=10; bkForm.limit_count=0; bkForm.expire_hours=24
    bkForm.start_time=''; bkForm.end_time=''
  }
  bkVis.value = true
}

async function saveBargain() {
  if(!bkForm.name) return ElMessage.warning('请填写活动名称')
  if(!bkForm.product_id) return ElMessage.warning('请选择商品')
  if(!(bkForm.floor_price>0) || bkForm.floor_price>=bkForm.original_price) return ElMessage.warning('底价需大于0且低于原价')
  try {
    if(!bkForm.original_price && bkForm.product_id) {
      const p = productList.value.find(x=>x.id===bkForm.product_id)
      if(p) bkForm.original_price = p.price
    }
    if(bkEdit.value) await API.put('/bargain/'+bkEdit.value, bkForm)
    else await API.post('/bargain', bkForm)
    ElMessage.success('保存成功'); bkVis.value=false; fetchBargainList()
  } catch { ElMessage.error('保存失败') }
}

async function toggleBargain(row) {
  try { await API.post('/bargain/'+row.id+'/toggle'); ElMessage.success('操作成功'); fetchBargainList() } catch {}
}

async function delBargain(id) {
  try { await API.delete('/bargain/'+id); ElMessage.success('已删除'); fetchBargainList() } catch {}
}

async function fetchBargainSessions() {
  bksLoad.value = true
  try {
    const r = await API.get('/bargain/sessions', { params:{ page:bksP.value, pageSize:bksPS.value } })
    const d = r.data.data||{}
    bargainSessions.value = d.list||[]; bksTotal.value = d.total||0
  } catch { bargainSessions.value = []; bksTotal.value = 0 }
  finally { bksLoad.value = false }
}

async function fetchBargainOrders() {
  bkoLoad.value = true
  try {
    const params = { page:bkoP.value, pageSize:bkoPS.value }
    if(bkoKeyword.value) params.keyword = bkoKeyword.value
    const r = await API.get('/bargain/orders', { params })
    const d = r.data.data||{}
    bargainOrders.value = d.list||[]; bkoTotal.value = d.total||0
  } catch { bargainOrders.value = []; bkoTotal.value = 0 }
  finally { bkoLoad.value = false }
}


// ==================== 营销自动化 ====================
const autoSub = ref('rules')
const autoList = ref([]); const autoLoad = ref(false)
const autoEdit = ref(null); const autoVis = ref(false)
const autoLogs = ref([]); const autoLogLoad = ref(false); const autoLogP = ref(1); const autoLogTotal = ref(0)
const autoStats = ref({ byType:[], totalIssued:0 })
const autoTypes = [
  { value:'cart_remind', label:'🛒 购物车召回' },
  { value:'birthday_gift', label:'🎂 生日礼' },
  { value:'first_order', label:'🎁 首单礼' },
  { value:'repurchase', label:'🔁 复购券' },
]
const autoForm = reactive({ trigger_type:'cart_remind', name:'', coupon_id:null, threshold_hours:3, repurchase_days:15, valid_days:30, enabled:true })
function autoTypeLabel(t){ const x=autoTypes.find(i=>i.value===t); return x?x.label:t||'-' }
function autoThresh(row){ if(row.trigger_type==='cart_remind') return row.threshold_hours+'h 未下单'; if(row.trigger_type==='repurchase') return row.repurchase_days+'天'; if(row.trigger_type==='birthday_gift') return '生日当天'; if(row.trigger_type==='first_order') return '支付首单后'; return '-' }
function autoLogType(s){ return {success:'success',skipped:'info',error:'danger'}[s]||'info' }
function autoStatCnt(tp, field){
  const x=(autoStats.value.byType||[]).find(i=>i.trigger_type===tp)
  return (x && x[field]) || 0
}
async function fetchAutoList(){ autoLoad.value=true; try{ const r=await API.get('/marketing/automation/list'); autoList.value=r.data.data||[] } catch { autoList.value=[] } finally { autoLoad.value=false } }
async function fetchAutoStats(){ try{ const r=await API.get('/marketing/automation/stats'); autoStats.value=r.data.data||{byType:[]} } catch {} }
async function fetchAutoLogs(){ autoLogLoad.value=true; try{ const r=await API.get('/marketing/automation/logs',{params:{page:autoLogP.value,pageSize:10}}); const d=r.data.data||{}; autoLogs.value=d.list||[]; autoLogTotal.value=d.total||0 } catch { autoLogs.value=[] } finally { autoLogLoad.value=false } }
function autoLogPage(p){ autoLogP.value=p; fetchAutoLogs() }
function autoSubChange(v){ if(v==='logs') fetchAutoLogs() }
function openAuto(row){
  autoEdit.value = row?.id||null
  if(row){ autoForm.trigger_type=row.trigger_type; autoForm.name=row.name; autoForm.coupon_id=row.coupon_id||null; autoForm.threshold_hours=row.threshold_hours||3; autoForm.repurchase_days=row.repurchase_days||15; autoForm.valid_days=row.valid_days||30; autoForm.enabled=!!row.enabled }
  else { autoEdit.value=null; autoForm.trigger_type='cart_remind'; autoForm.name=''; autoForm.coupon_id=null; autoForm.threshold_hours=3; autoForm.repurchase_days=15; autoForm.valid_days=30; autoForm.enabled=true }
  autoVis.value = true
}
async function saveAuto(){
  const body = Object.assign({}, autoForm)
  if(body.coupon_id===null) body.coupon_id = 0
  if(autoEdit.value) body.id = autoEdit.value
  try {
    await API.post('/marketing/automation', body)
    ElMessage.success('已保存'); autoVis.value=false; fetchAutoList()
  } catch { ElMessage.error('保存失败') }
}
async function toggleAuto(row){ try{ await API.post('/marketing/automation/'+row.id+'/toggle'); ElMessage.success('已切换'); fetchAutoList() } catch { ElMessage.error('操作失败') } }
async function runAuto(row){ try{ const r=await API.post('/marketing/automation/'+row.id+'/run'); const d=r.data.data||{}; ElMessage.success('执行完成: 命中'+d.processed+' 成功'+d.ok+' 跳过'+d.skip+' 失败'+d.err); fetchAutoLogs() } catch { ElMessage.error('执行失败') } }
async function delAuto(id){ try{ await API.delete('/marketing/automation/'+id); ElMessage.success('已删除'); fetchAutoList() } catch { ElMessage.error('删除失败') } }


onMounted(() => { fetchCoupons(); fetchPromotions() })
</script>

<style scoped>
.marketing-page { max-width: 1400px; }
.tabs-card { margin-bottom:16px; padding:4px 0; }
.mkt-tabs { display:flex; gap:4px; }
.mkt-tab { display:flex; align-items:center; gap:6px; padding:10px 18px; border-radius:8px; cursor:pointer; font-size:14px; transition:all .2s; }
.mkt-tab:hover { background:#f5f7fa; }
.mkt-tab.active { background:#ecf5ff; color:#409eff; font-weight:600; }
.action-bar { margin-bottom:16px; }
.pagination-wrap { display:flex; justify-content:flex-end; padding:16px 0 0; }
.section-title { font-size:16px; font-weight:600; color:#333; margin:0 0 20px 0; }
</style>
