<script setup lang="ts">
import type { Dayjs } from 'dayjs';

import type { FlashSaleEditorForm } from '../types';

import type {
  MarketingFlashSaleChannel,
  MarketingFlashSaleCycleType,
  MarketingFlashSaleRecurringDateMode,
} from '#/api/marketing';

import {
  Button,
  DatePicker,
  Drawer,
  Form,
  Input,
  InputNumber,
  Spin,
  TimePicker,
} from 'ant-design-vue';

/**
 * 文件职责：限时折扣主编辑抽屉。
 */
import {
  FLASH_SALE_CHANNEL_OPTIONS,
  FLASH_SALE_CYCLE_OPTIONS,
  FLASH_SALE_RECURRING_DATE_MODE_OPTIONS,
  FLASH_SALE_WEEKDAY_OPTIONS,
} from '../composables/flash-sale-page/constants';
import {
  formatCurrency,
  resolveDiscountRateLabel,
} from '../composables/flash-sale-page/helpers';

defineProps<{
  form: FlashSaleEditorForm;
  loading: boolean;
  open: boolean;
  submitText: string;
  submitting: boolean;
  title: string;
}>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'openProductPicker'): void;
  (event: 'quickSelectWeekDays', mode: 'all' | 'weekday' | 'weekend'): void;
  (event: 'removeProduct', index: number): void;
  (event: 'setCycleType', value: MarketingFlashSaleCycleType): void;
  (event: 'setName', value: string): void;
  (event: 'setPerUserLimit', value: null | number): void;
  (event: 'setProductDiscountPrice', index: number, value: null | number): void;
  (event: 'setProductPerUserLimit', index: number, value: null | number): void;
  (
    event: 'setRecurringDateMode',
    value: MarketingFlashSaleRecurringDateMode,
  ): void;
  (event: 'setTimeRange', value: [Dayjs, Dayjs] | null): void;
  (event: 'setValidDateRange', value: [Dayjs, Dayjs] | null): void;
  (event: 'submit'): void;
  (event: 'toggleChannel', channel: MarketingFlashSaleChannel): void;
  (event: 'toggleWeekDay', day: number): void;
}>();

type RangePickerValue = [Dayjs, Dayjs] | [string, string] | null;

function normalizeDayjsRange(value: RangePickerValue): [Dayjs, Dayjs] | null {
  if (!value) {
    return null;
  }

  const [start, end] = value;
  if (typeof start === 'string' || typeof end === 'string') {
    return null;
  }

  return [start, end];
}

function onDateRangeChange(value: RangePickerValue) {
  emit('setValidDateRange', normalizeDayjsRange(value));
}

function onTimeRangeChange(value: RangePickerValue) {
  emit('setTimeRange', normalizeDayjsRange(value));
}

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

function parseNullableInteger(value: null | number | string) {
  if (value === null || value === undefined || value === '') {
    return null;
  }
  const numeric = Number(value);
  if (Number.isNaN(numeric)) {
    return null;
  }
  return Math.floor(numeric);
}
</script>

<template>
  <Drawer
    :open="open"
    :title="title"
    width="620"
    :destroy-on-close="false"
    class="fs-editor-drawer"
    @close="emit('close')"
  >
    <Spin :spinning="loading">
      <Form layout="vertical" class="fs-editor-form">
        <Form.Item label="活动名称" required>
          <Input
            :value="form.name"
            :maxlength="64"
            placeholder="请输入活动名称，如：午市特惠、新品尝鲜"
            @update:value="(value) => emit('setName', String(value ?? ''))"
          />
        </Form.Item>

        <Form.Item label="活动周期" required>
          <div class="fs-pill-group">
            <button
              v-for="item in FLASH_SALE_CYCLE_OPTIONS"
              :key="item.value"
              type="button"
              class="fs-pill"
              :class="{ checked: form.cycleType === item.value }"
              @click="emit('setCycleType', item.value)"
            >
              {{ item.label }}
            </button>
          </div>
          <div class="g-hint">
            周期循环适合固定日期的促销，如「疯狂星期四」、「周末特惠」。
          </div>
        </Form.Item>

        <Form.Item
          v-if="form.cycleType === 'recurring'"
          label="日期规则"
          required
        >
          <div class="fs-pill-group">
            <button
              v-for="item in FLASH_SALE_RECURRING_DATE_MODE_OPTIONS"
              :key="item.value"
              type="button"
              class="fs-pill"
              :class="{ checked: form.recurringDateMode === item.value }"
              @click="emit('setRecurringDateMode', item.value)"
            >
              {{ item.label }}
            </button>
          </div>
        </Form.Item>

        <Form.Item
          v-if="form.cycleType === 'once' || form.recurringDateMode === 'fixed'"
          label="活动时间"
          required
        >
          <DatePicker.RangePicker
            :value="form.validDateRange ?? undefined"
            format="YYYY-MM-DD"
            class="fs-range-picker"
            @update:value="onDateRangeChange"
          />
        </Form.Item>

        <Form.Item v-else label="活动时间（可选）">
          <DatePicker.RangePicker
            :value="form.validDateRange ?? undefined"
            format="YYYY-MM-DD"
            class="fs-range-picker"
            @update:value="onDateRangeChange"
          />
          <div class="g-hint">留空表示长期有效</div>
        </Form.Item>

        <Form.Item label="每日时段">
          <TimePicker.RangePicker
            :value="form.timeRange ?? undefined"
            format="HH:mm"
            class="fs-range-picker"
            @update:value="onTimeRangeChange"
          />
          <div class="g-hint">留空则全天有效</div>
        </Form.Item>

        <Form.Item
          v-if="form.cycleType === 'recurring'"
          label="循环日期"
          required
        >
          <div class="fs-day-sel">
            <button
              v-for="item in FLASH_SALE_WEEKDAY_OPTIONS"
              :key="item.value"
              type="button"
              class="fs-day"
              :class="{ active: form.weekDays.includes(item.value) }"
              @click="emit('toggleWeekDay', item.value)"
            >
              {{ item.label }}
            </button>
          </div>
          <div class="fs-day-quick">
            <Button
              size="small"
              @click="emit('quickSelectWeekDays', 'weekday')"
            >
              工作日
            </Button>
            <Button
              size="small"
              @click="emit('quickSelectWeekDays', 'weekend')"
            >
              周末
            </Button>
            <Button size="small" @click="emit('quickSelectWeekDays', 'all')">
              全选
            </Button>
          </div>
          <div class="g-hint">
            活动将在选中的每个星期自动生效，无需手动开启。
          </div>
        </Form.Item>

        <Form.Item label="折扣商品" required>
          <div v-if="form.products.length === 0" class="fs-product-empty">
            暂未添加折扣商品
          </div>

          <div
            v-for="(item, index) in form.products"
            :key="item.productId"
            class="fs-drawer-prod"
          >
            <div class="fs-drawer-prod-hd">
              <span>{{ item.name }}</span>
              <button
                type="button"
                class="fs-drawer-prod-remove"
                @click="emit('removeProduct', index)"
              >
                ×
              </button>
            </div>
            <div class="fs-drawer-prod-bd">
              <div class="fs-field">
                <label>原价</label>
                <Input :value="formatCurrency(item.originalPrice)" readonly />
              </div>
              <div class="fs-field">
                <label>折扣价</label>
                <InputNumber
                  :value="item.discountPrice ?? undefined"
                  :min="0.01"
                  :precision="2"
                  placeholder="请输入折扣价"
                  @update:value="
                    (value) =>
                      emit(
                        'setProductDiscountPrice',
                        index,
                        parseNullableNumber(value),
                      )
                  "
                />
              </div>
              <div class="fs-field">
                <label>折扣</label>
                <span class="fs-auto-rate">
                  {{
                    resolveDiscountRateLabel(
                      item.originalPrice,
                      item.discountPrice,
                    )
                  }}
                </span>
              </div>
              <div class="fs-field">
                <label>限购/人</label>
                <InputNumber
                  :value="item.perUserLimit ?? undefined"
                  :min="1"
                  :precision="0"
                  placeholder="不限则留空"
                  @update:value="
                    (value) =>
                      emit(
                        'setProductPerUserLimit',
                        index,
                        parseNullableInteger(value),
                      )
                  "
                />
              </div>
            </div>
          </div>

          <Button size="small" @click="emit('openProductPicker')">
            + 添加商品
          </Button>
        </Form.Item>

        <Form.Item label="适用渠道">
          <div class="fs-pill-group">
            <button
              v-for="item in FLASH_SALE_CHANNEL_OPTIONS"
              :key="item.value"
              type="button"
              class="fs-pill"
              :class="{ checked: form.channels.includes(item.value) }"
              @click="emit('toggleChannel', item.value)"
            >
              {{ item.label }}
            </button>
          </div>
        </Form.Item>

        <Form.Item label="每人限购">
          <div class="fs-limit-row">
            <InputNumber
              :value="form.perUserLimit ?? undefined"
              :min="1"
              :precision="0"
              placeholder="不限则留空"
              @update:value="
                (value) => emit('setPerUserLimit', parseNullableInteger(value))
              "
            />
            <span class="fs-unit">件</span>
          </div>
          <div class="g-hint">
            活动期间每人累计可购买的折扣商品总数，留空不限。
          </div>
        </Form.Item>
      </Form>
    </Spin>

    <template #footer>
      <div class="fs-drawer-footer">
        <Button @click="emit('close')">取消</Button>
        <Button type="primary" :loading="submitting" @click="emit('submit')">
          {{ submitText }}
        </Button>
      </div>
    </template>
  </Drawer>
</template>
