<script setup lang="ts">
/**
 * 文件职责：营销中心-次卡管理页面主视图。
 */
import type {
  MarketingPunchCardStatus,
  MarketingPunchCardUsageFilterStatus,
} from '#/api/marketing';

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

import { Button, Empty, Input, Pagination, Select, Spin } from 'ant-design-vue';

import PunchCardEditorDrawer from './components/PunchCardEditorDrawer.vue';
import PunchCardProductPickerDrawer from './components/PunchCardProductPickerDrawer.vue';
import PunchCardStatsCards from './components/PunchCardStatsCards.vue';
import PunchCardTemplateCard from './components/PunchCardTemplateCard.vue';
import PunchCardUsageRecordTable from './components/PunchCardUsageRecordTable.vue';
import PunchCardUsageStatsCards from './components/PunchCardUsageStatsCards.vue';
import {
  PUNCH_CARD_RECORD_STATUS_FILTER_OPTIONS,
  PUNCH_CARD_STATUS_FILTER_OPTIONS,
} from './composables/punch-card-page/constants';
import { useMarketingPunchCardPage } from './composables/useMarketingPunchCardPage';

const {
  activeTab,
  applyListFilters,
  applyRecordFilters,
  canManage,
  drawerSubmitText,
  drawerTitle,
  exportUsageRecords,
  form,
  handleListPageChange,
  handlePickerCategoryChange,
  handlePickerSearch,
  handleRecordPageChange,
  hasStore,
  isDrawerLoading,
  isDrawerOpen,
  isDrawerSubmitting,
  isListLoading,
  isPickerLoading,
  isPickerOpen,
  isRecordLoading,
  isStoreLoading,
  listFilterForm,
  listKeyword,
  listPage,
  listPageSize,
  listRows,
  listStats,
  listTotalCount,
  openCreateDrawer,
  openEditDrawer,
  openScopeProductPicker,
  pickerCategoryFilterId,
  pickerCategoryOptions,
  pickerKeyword,
  pickerProducts,
  pickerSelectedProductIds,
  recordFilterForm,
  recordKeyword,
  removeCard,
  resetListFilters,
  resetRecordFilters,
  scopeCategoryOptions,
  scopeTagOptions,
  selectedStoreId,
  setActiveTab,
  setDrawerOpen,
  setFormAllowTransfer,
  setFormCoverImageUrl,
  setFormDailyLimit,
  setFormDescription,
  setFormExpireStrategy,
  setFormName,
  setFormOriginalPrice,
  setFormPerOrderLimit,
  setFormPerUserPurchaseLimit,
  setFormSalePrice,
  setFormScopeType,
  setFormTotalTimes,
  setFormUsageCapAmount,
  setFormUsageMode,
  setFormValidDateRange,
  setFormValidityDays,
  setFormValidityType,
  setListKeyword,
  setListStatusFilter,
  setPickerKeyword,
  setPickerOpen,
  setRecordKeyword,
  setRecordStatusFilter,
  setRecordTemplateFilter,
  setScopeCategoryIds,
  setScopeProductIds,
  setScopeTagIds,
  setSelectedStoreId,
  storeOptions,
  submitDrawer,
  submitPicker,
  templateOptions,
  toggleNotifyChannel,
  togglePickerProduct,
  toggleStatus,
  usagePager,
  usageStats,
} = useMarketingPunchCardPage();

function onListStatusFilterChange(value: unknown) {
  const next =
    typeof value === 'string' && value
      ? (value as MarketingPunchCardStatus)
      : '';
  setListStatusFilter(next);
  void applyListFilters();
}

function onRecordStatusFilterChange(value: unknown) {
  const next =
    typeof value === 'string' && value
      ? (value as MarketingPunchCardUsageFilterStatus)
      : '';
  setRecordStatusFilter(next);
  void applyRecordFilters();
}

function onRecordTemplateFilterChange(value: unknown) {
  const next = typeof value === 'string' ? value : '';
  setRecordTemplateFilter(next);
  void applyRecordFilters();
}
</script>

<template>
  <Page title="次卡管理" content-class="page-marketing-punch-card">
    <div class="mpc-page">
      <div class="mpc-toolbar mpc-toolbar-top">
        <Select
          class="mpc-store-select"
          :value="selectedStoreId"
          :options="storeOptions"
          :loading="isStoreLoading"
          placeholder="请选择门店"
          @update:value="(value) => setSelectedStoreId(String(value ?? ''))"
        />

        <div class="mpc-segments">
          <button
            type="button"
            class="mpc-segment-item"
            :class="{ active: activeTab === 'list' }"
            @click="setActiveTab('list')"
          >
            次卡列表
          </button>
          <button
            type="button"
            class="mpc-segment-item"
            :class="{ active: activeTab === 'records' }"
            @click="setActiveTab('records')"
          >
            使用记录
          </button>
        </div>

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

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

      <template v-else>
        <section v-show="activeTab === 'list'" class="mpc-tab-panel">
          <PunchCardStatsCards :stats="listStats" />

          <div class="mpc-toolbar">
            <Select
              class="mpc-filter-select"
              :value="listFilterForm.status"
              :options="PUNCH_CARD_STATUS_FILTER_OPTIONS"
              placeholder="全部状态"
              @update:value="onListStatusFilterChange"
            />

            <Input
              class="mpc-search"
              :value="listKeyword"
              placeholder="搜索次卡名称"
              allow-clear
              @update:value="(value) => setListKeyword(String(value ?? ''))"
              @press-enter="applyListFilters"
            />

            <Button @click="applyListFilters">搜索</Button>
            <Button @click="resetListFilters">重置</Button>

            <span class="mpc-spacer"></span>
            <Button
              type="primary"
              :disabled="!canManage"
              @click="openCreateDrawer"
            >
              创建次卡
            </Button>
          </div>

          <Spin :spinning="isListLoading">
            <div v-if="listRows.length > 0" class="mpc-card-grid">
              <PunchCardTemplateCard
                v-for="item in listRows"
                :key="item.id"
                :item="item"
                :can-manage="canManage"
                @edit="(row) => openEditDrawer(row.id)"
                @toggle-status="toggleStatus"
                @remove="removeCard"
              />
            </div>

            <div v-else class="mpc-empty">
              <Empty description="暂无次卡" />
            </div>

            <div v-if="listRows.length > 0" class="mpc-pagination">
              <Pagination
                :current="listPage"
                :page-size="listPageSize"
                :total="listTotalCount"
                show-size-changer
                :page-size-options="['4', '8', '12', '20']"
                :show-total="(value) => `共 ${value} 条`"
                @change="handleListPageChange"
              />
            </div>
          </Spin>
        </section>

        <section v-show="activeTab === 'records'" class="mpc-tab-panel">
          <div class="mpc-toolbar">
            <Select
              class="mpc-filter-select"
              :value="recordFilterForm.templateId"
              :options="[
                { label: '全部次卡', value: '' },
                ...templateOptions.map((item) => ({
                  label: item.name,
                  value: item.templateId,
                })),
              ]"
              placeholder="全部次卡"
              @update:value="onRecordTemplateFilterChange"
            />

            <Select
              class="mpc-filter-select"
              :value="recordFilterForm.status"
              :options="PUNCH_CARD_RECORD_STATUS_FILTER_OPTIONS"
              placeholder="全部状态"
              @update:value="onRecordStatusFilterChange"
            />

            <Input
              class="mpc-search"
              :value="recordKeyword"
              placeholder="搜索会员/商品"
              allow-clear
              @update:value="(value) => setRecordKeyword(String(value ?? ''))"
              @press-enter="applyRecordFilters"
            />

            <Button @click="applyRecordFilters">搜索</Button>
            <Button @click="resetRecordFilters">重置</Button>

            <span class="mpc-spacer"></span>
            <Button :disabled="!canManage" @click="exportUsageRecords">
              导出
            </Button>
          </div>

          <PunchCardUsageStatsCards :stats="usageStats" />

          <div class="mpc-table-panel">
            <PunchCardUsageRecordTable
              :records="usagePager.items"
              :loading="isRecordLoading"
              :page="usagePager.page"
              :page-size="usagePager.pageSize"
              :total="usagePager.totalCount"
              @page-change="handleRecordPageChange"
            />
          </div>
        </section>
      </template>
    </div>

    <PunchCardEditorDrawer
      :open="isDrawerOpen"
      :title="drawerTitle"
      :submit-text="drawerSubmitText"
      :submitting="isDrawerSubmitting"
      :loading="isDrawerLoading"
      :can-manage="canManage"
      :form="form"
      :category-options="scopeCategoryOptions"
      :tag-options="scopeTagOptions"
      :scope-product-names="
        form.scope.productIds.map((id) => {
          const product = pickerProducts.find((item) => item.id === id);
          return {
            id,
            name: product?.name ?? id,
          };
        })
      "
      @close="setDrawerOpen(false)"
      @set-name="setFormName"
      @set-cover-image-url="setFormCoverImageUrl"
      @set-sale-price="setFormSalePrice"
      @set-original-price="setFormOriginalPrice"
      @set-total-times="setFormTotalTimes"
      @set-validity-type="setFormValidityType"
      @set-validity-days="setFormValidityDays"
      @set-valid-date-range="setFormValidDateRange"
      @set-scope-type="setFormScopeType"
      @set-scope-category-ids="setScopeCategoryIds"
      @set-scope-tag-ids="setScopeTagIds"
      @set-scope-product-ids="setScopeProductIds"
      @open-scope-product-picker="openScopeProductPicker"
      @set-usage-mode="setFormUsageMode"
      @set-usage-cap-amount="setFormUsageCapAmount"
      @set-daily-limit="setFormDailyLimit"
      @set-per-order-limit="setFormPerOrderLimit"
      @set-per-user-purchase-limit="setFormPerUserPurchaseLimit"
      @set-allow-transfer="setFormAllowTransfer"
      @set-expire-strategy="setFormExpireStrategy"
      @set-description="setFormDescription"
      @toggle-notify-channel="toggleNotifyChannel"
      @submit="submitDrawer"
    />

    <PunchCardProductPickerDrawer
      :open="isPickerOpen"
      :loading="isPickerLoading"
      :keyword="pickerKeyword"
      :category-filter-id="pickerCategoryFilterId"
      :category-options="pickerCategoryOptions"
      :products="pickerProducts"
      :selected-product-ids="pickerSelectedProductIds"
      @close="setPickerOpen(false)"
      @set-keyword="setPickerKeyword"
      @set-category-filter-id="handlePickerCategoryChange"
      @toggle-product="togglePickerProduct"
      @search="handlePickerSearch"
      @submit="submitPicker"
    />
  </Page>
</template>

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