<script setup lang="ts">
/**
 * 文件职责：营销中心-新客有礼页面主视图。
 * 1. 还原原型布局（工具栏、横幅、统计、配置区、邀请区、底部保存栏）。
 * 2. 编排新客券二级抽屉与页面保存行为。
 */
import type { MarketingNewCustomerCouponScene } from '#/api/marketing';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  InputNumber,
  Select,
  Spin,
  Switch,
} from 'ant-design-vue';

import NewCustomerCouponDrawer from './components/NewCustomerCouponDrawer.vue';
import NewCustomerCouponGroup from './components/NewCustomerCouponGroup.vue';
import NewCustomerInviteRecordTable from './components/NewCustomerInviteRecordTable.vue';
import NewCustomerStatsCards from './components/NewCustomerStatsCards.vue';
import {
  NEW_CUSTOMER_GIFT_TYPE_OPTIONS,
  NEW_CUSTOMER_SHARE_CHANNEL_OPTIONS,
} from './composables/new-customer-page/constants';
import { useMarketingNewCustomerPage } from './composables/useMarketingNewCustomerPage';

const {
  canManage,
  closeCouponDrawer,
  couponDrawerForm,
  couponDrawerScene,
  form,
  handleInvitePageChange,
  hasStore,
  invitePager,
  isCouponDrawerOpen,
  isDetailLoading,
  isInviteLoading,
  isSaving,
  isStoreLoading,
  openCouponDrawer,
  removeCoupon,
  resetSettings,
  saveSettings,
  selectedStoreId,
  setCouponDrawerMinimumSpend,
  setCouponDrawerType,
  setCouponDrawerValidDays,
  setCouponDrawerValue,
  setDirectMinimumSpend,
  setDirectReduceAmount,
  setGiftEnabled,
  setGiftType,
  setInviteEnabled,
  setSelectedStoreId,
  stats,
  storeOptions,
  submitCouponDrawer,
  toggleShareChannel,
  updatedAt,
} = useMarketingNewCustomerPage();

function parseNullableNumber(value: null | number | string) {
  if (value === null || value === undefined || value === '') {
    return null;
  }
  const parsed = Number(value);
  return Number.isNaN(parsed) ? null : parsed;
}

function openSceneCouponDrawer(scene: MarketingNewCustomerCouponScene) {
  openCouponDrawer(scene);
}
</script>

<template>
  <Page title="新客有礼" content-class="page-marketing-new-customer">
    <div class="mnc-page">
      <div class="mnc-toolbar">
        <Select
          class="mnc-store-select"
          :value="selectedStoreId"
          :options="storeOptions"
          :loading="isStoreLoading"
          placeholder="请选择门店"
          @update:value="(value) => setSelectedStoreId(String(value ?? ''))"
        />

        <span v-if="!canManage" class="mnc-readonly-tip">当前为只读权限</span>
      </div>

      <div class="mnc-banner">
        <span class="mnc-banner-icon">
          <IconifyIcon icon="lucide:gift" />
        </span>
        <div class="mnc-banner-text">
          <strong>新客有礼</strong>
          新用户首次下单自动发放优惠礼包，提升新客转化率。开启后，每位新注册用户将自动收到您配置的欢迎礼包。
        </div>
      </div>

      <NewCustomerStatsCards v-if="hasStore" :stats="stats" />

      <div v-if="!hasStore" class="mnc-empty">暂无门店，请先创建门店</div>

      <Spin v-else :spinning="isDetailLoading">
        <Card class="mnc-card" :bordered="false">
          <div class="mnc-section-title">新客礼包配置</div>

          <div class="mnc-row">
            <div class="mnc-row-label">启用状态</div>
            <div class="mnc-row-control">
              <Switch
                :checked="form.giftEnabled"
                :disabled="!canManage"
                @update:checked="(value) => setGiftEnabled(Boolean(value))"
              />
              <span class="mnc-row-hint">开启后新用户注册即发放礼包</span>
            </div>
          </div>

          <div class="mnc-row">
            <div class="mnc-row-label">礼包类型</div>
            <div class="mnc-row-control mnc-inline">
              <button
                v-for="item in NEW_CUSTOMER_GIFT_TYPE_OPTIONS"
                :key="item.value"
                type="button"
                class="mnc-pill"
                :class="{ checked: form.giftType === item.value }"
                :disabled="!canManage"
                @click="setGiftType(item.value)"
              >
                {{ item.label }}
              </button>
            </div>
          </div>

          <template v-if="form.giftType === 'coupon'">
            <div class="mnc-row mnc-row-block">
              <NewCustomerCouponGroup
                title="券包内容"
                add-text="添加优惠券"
                :coupons="form.welcomeCoupons"
                :can-manage="canManage"
                @add="openSceneCouponDrawer('welcome')"
                @remove="(index) => removeCoupon('welcome', index)"
              />
            </div>
          </template>

          <template v-else>
            <div class="mnc-row">
              <div class="mnc-row-label">直减金额</div>
              <div class="mnc-row-control">
                <div class="mnc-inline">
                  <span>¥</span>
                  <InputNumber
                    :value="form.directReduceAmount ?? undefined"
                    :min="0.01"
                    :precision="2"
                    :disabled="!canManage"
                    placeholder="如：10"
                    @update:value="
                      (value) =>
                        setDirectReduceAmount(parseNullableNumber(value))
                    "
                  />
                </div>
                <div class="mnc-row-hint">新用户首单自动减免的金额</div>
              </div>
            </div>

            <div class="mnc-row">
              <div class="mnc-row-label">使用门槛</div>
              <div class="mnc-row-control">
                <div class="mnc-inline">
                  <span>订单满</span>
                  <InputNumber
                    :value="form.directMinimumSpend ?? undefined"
                    :min="0"
                    :precision="2"
                    :disabled="!canManage"
                    placeholder="如：30"
                    @update:value="
                      (value) =>
                        setDirectMinimumSpend(parseNullableNumber(value))
                    "
                  />
                  <span>元可用</span>
                </div>
              </div>
            </div>
          </template>
        </Card>

        <Card class="mnc-card" :bordered="false">
          <div class="mnc-section-title">老带新分享</div>

          <div class="mnc-row">
            <div class="mnc-row-label">启用状态</div>
            <div class="mnc-row-control">
              <Switch
                :checked="form.inviteEnabled"
                :disabled="!canManage"
                @update:checked="(value) => setInviteEnabled(Boolean(value))"
              />
              <span class="mnc-row-hint">
                开启后顾客可在小程序内分享邀请好友
              </span>
            </div>
          </div>

          <div class="mnc-row mnc-row-block">
            <NewCustomerCouponGroup
              title="邀请人奖励"
              description="成功邀请新用户下单后发放"
              add-text="添加奖励券"
              :coupons="form.inviterCoupons"
              :can-manage="canManage"
              @add="openSceneCouponDrawer('inviter')"
              @remove="(index) => removeCoupon('inviter', index)"
            />
          </div>

          <div class="mnc-row mnc-row-block">
            <NewCustomerCouponGroup
              title="被邀请人奖励"
              description="新用户通过邀请注册后额外获得，叠加新客礼包"
              add-text="添加奖励券"
              :coupons="form.inviteeCoupons"
              :can-manage="canManage"
              @add="openSceneCouponDrawer('invitee')"
              @remove="(index) => removeCoupon('invitee', index)"
            />
          </div>

          <div class="mnc-row">
            <div class="mnc-row-label">分享渠道</div>
            <div class="mnc-row-control">
              <div class="mnc-inline">
                <button
                  v-for="item in NEW_CUSTOMER_SHARE_CHANNEL_OPTIONS"
                  :key="item.value"
                  type="button"
                  class="mnc-pill"
                  :class="{ checked: form.shareChannels.includes(item.value) }"
                  :disabled="!canManage"
                  @click="toggleShareChannel(item.value)"
                >
                  {{ item.label }}
                </button>
              </div>
              <div class="mnc-row-hint">
                顾客在小程序内可通过以上渠道分享邀请
              </div>
            </div>
          </div>

          <div class="mnc-row mnc-row-block">
            <div class="mnc-row-block-title">邀请记录（近期）</div>
            <div class="mnc-invite-table">
              <NewCustomerInviteRecordTable
                :records="invitePager.items"
                :page="invitePager.page"
                :page-size="invitePager.pageSize"
                :total="invitePager.totalCount"
                :loading="isInviteLoading"
                @page-change="handleInvitePageChange"
              />
            </div>
          </div>
        </Card>

        <Card class="mnc-save-card" :bordered="false">
          <div class="mnc-save-bar">
            <span v-if="updatedAt" class="mnc-updated-at">
              最近更新：{{ updatedAt }}
            </span>
            <Button :disabled="!canManage || isSaving" @click="resetSettings">
              重置
            </Button>
            <Button
              type="primary"
              :disabled="!canManage"
              :loading="isSaving"
              @click="saveSettings"
            >
              保存设置
            </Button>
          </div>
        </Card>
      </Spin>
    </div>

    <NewCustomerCouponDrawer
      :open="isCouponDrawerOpen"
      :form="couponDrawerForm"
      :scene="couponDrawerScene"
      @close="closeCouponDrawer"
      @set-coupon-type="setCouponDrawerType"
      @set-value="setCouponDrawerValue"
      @set-minimum-spend="setCouponDrawerMinimumSpend"
      @set-valid-days="setCouponDrawerValidDays"
      @submit="submitCouponDrawer"
    />
  </Page>
</template>

<style lang="less">
@import './styles/index.less';
</style>
