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

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

import type {
  MarketingSeckillActivityType,
  MarketingSeckillChannel,
} from '#/api/marketing';

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

/**
 * 文件职责：秒杀活动主编辑抽屉。
 */
import {
  SECKILL_ACTIVITY_TYPE_OPTIONS,
  SECKILL_CHANNEL_OPTIONS,
} from '../composables/seckill-page/constants';
import { formatCurrency } from '../composables/seckill-page/helpers';

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

const emit = defineEmits<{
  (event: 'addSession'): void;
  (event: 'close'): void;
  (event: 'openProductPicker'): void;
  (event: 'removeProduct', index: number): void;
  (event: 'removeSession', index: number): void;
  (event: 'setActivityType', value: MarketingSeckillActivityType): void;
  (event: 'setName', value: string): void;
  (event: 'setPerUserLimit', value: null | number): void;
  (event: 'setPreheatEnabled', value: boolean): void;
  (event: 'setPreheatHours', value: null | number): void;
  (event: 'setProductPerUserLimit', index: number, value: null | number): void;
  (event: 'setProductSeckillPrice', index: number, value: null | number): void;
  (event: 'setProductStockLimit', index: number, value: null | number): void;
  (event: 'setSessionDuration', index: number, value: null | number): void;
  (event: 'setSessionStartTime', index: number, value: string): void;
  (event: 'setTimeRange', value: [Dayjs, Dayjs] | null): void;
  (event: 'setValidDateRange', value: [Dayjs, Dayjs] | null): void;
  (event: 'submit'): void;
  (event: 'toggleChannel', channel: MarketingSeckillChannel): 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="560"
    :destroy-on-close="false"
    class="sk-editor-drawer"
    @close="emit('close')"
  >
    <Spin :spinning="loading">
      <Form layout="vertical" class="sk-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="sk-pill-group">
            <button
              v-for="item in SECKILL_ACTIVITY_TYPE_OPTIONS"
              :key="item.value"
              type="button"
              class="sk-pill"
              :class="{ checked: form.activityType === item.value }"
              @click="emit('setActivityType', item.value)"
            >
              {{ item.label }}
            </button>
          </div>
        </Form.Item>

        <Form.Item
          v-if="form.activityType === 'timed'"
          label="活动时间"
          required
        >
          <DatePicker.RangePicker
            :value="form.validDateRange ?? undefined"
            format="YYYY-MM-DD"
            class="sk-range-picker"
            @update:value="onDateRangeChange"
          />
          <TimePicker.RangePicker
            :value="form.timeRange ?? undefined"
            format="HH:mm"
            class="sk-range-picker"
            style="margin-top: 8px"
            @update:value="onTimeRangeChange"
          />
        </Form.Item>

        <Form.Item v-else label="场次设置" required>
          <div class="sk-session-list">
            <div
              v-for="(session, index) in form.sessions"
              :key="session.key"
              class="sk-session-row"
            >
              <Input
                :value="session.startTime"
                type="time"
                class="sk-session-time"
                @update:value="
                  (value) =>
                    emit('setSessionStartTime', index, String(value ?? ''))
                "
              />
              <span class="sk-session-label">持续</span>
              <InputNumber
                :value="session.durationMinutes ?? undefined"
                :min="1"
                :precision="0"
                class="sk-session-duration"
                @update:value="
                  (value) =>
                    emit(
                      'setSessionDuration',
                      index,
                      parseNullableInteger(value),
                    )
                "
              />
              <span class="sk-session-label">分钟</span>
              <button
                type="button"
                class="sk-session-remove"
                @click="emit('removeSession', index)"
              >
                ×
              </button>
            </div>
          </div>
          <Button size="small" @click="emit('addSession')">+ 添加场次</Button>
        </Form.Item>

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

          <div
            v-for="(item, index) in form.products"
            :key="item.productId"
            class="sk-drawer-prod"
          >
            <div class="sk-drawer-prod-hd">
              <span>{{ item.name }}</span>
              <button
                type="button"
                class="sk-drawer-prod-remove"
                @click="emit('removeProduct', index)"
              >
                ×
              </button>
            </div>
            <div class="sk-drawer-prod-bd">
              <div class="sk-field">
                <label>原价</label>
                <Input :value="formatCurrency(item.originalPrice)" readonly />
              </div>
              <div class="sk-field">
                <label>秒杀价</label>
                <InputNumber
                  :value="item.seckillPrice ?? undefined"
                  :min="0.01"
                  :precision="2"
                  placeholder="请输入秒杀价"
                  @update:value="
                    (value) =>
                      emit(
                        'setProductSeckillPrice',
                        index,
                        parseNullableNumber(value),
                      )
                  "
                />
              </div>
              <div class="sk-field">
                <label>限量(份)</label>
                <InputNumber
                  :value="item.stockLimit ?? undefined"
                  :min="1"
                  :precision="0"
                  placeholder="如：50"
                  @update:value="
                    (value) =>
                      emit(
                        'setProductStockLimit',
                        index,
                        parseNullableInteger(value),
                      )
                  "
                />
              </div>
              <div class="sk-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="sk-pill-group">
            <button
              v-for="item in SECKILL_CHANNEL_OPTIONS"
              :key="item.value"
              type="button"
              class="sk-pill"
              :class="{ checked: form.channels.includes(item.value) }"
              @click="emit('toggleChannel', item.value)"
            >
              {{ item.label }}
            </button>
          </div>
        </Form.Item>

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

        <Form.Item label="预热设置">
          <div class="sk-preheat-row">
            <Switch
              :checked="form.preheatEnabled"
              @update:checked="
                (value) => emit('setPreheatEnabled', Boolean(value))
              "
            />
            <span class="sk-session-label">开启预热</span>
            <template v-if="form.preheatEnabled">
              <span class="sk-session-label">提前</span>
              <InputNumber
                :value="form.preheatHours ?? undefined"
                :min="1"
                :precision="0"
                @update:value="
                  (value) =>
                    emit('setPreheatHours', parseNullableInteger(value))
                "
              />
              <span class="sk-session-label">小时</span>
            </template>
          </div>
          <div class="g-hint">在商品页展示秒杀预告，吸引用户提前关注</div>
        </Form.Item>
      </Form>
    </Spin>

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