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

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

import type {
  MarketingFullReductionActivityType,
  MarketingFullReductionChannel,
  MarketingFullReductionGiftScopeType,
  MarketingFullReductionSecondHalfDiscountType,
  MarketingFullReductionStoreScopeMode,
} from '#/api/marketing';

import {
  Button,
  DatePicker,
  Drawer,
  Form,
  Input,
  InputNumber,
  Radio,
  Select,
  Spin,
} from 'ant-design-vue';
/**
 * 文件职责：满减活动编辑抽屉。
 * 1. 承载活动类型、规则、时间、范围等编辑 UI。
 * 2. 抛出字段变更、范围选择与保存事件。
 */
import dayjs from 'dayjs';

import {
  FULL_REDUCTION_CHANNEL_OPTIONS,
  FULL_REDUCTION_EDITOR_ACTIVITY_OPTIONS,
  FULL_REDUCTION_GIFT_SCOPE_OPTIONS,
  FULL_REDUCTION_SECOND_HALF_DISCOUNT_OPTIONS,
  FULL_REDUCTION_STACK_OPTIONS,
  FULL_REDUCTION_STORE_SCOPE_OPTIONS,
} from '../composables/full-reduction-page/constants';
import { resolveScopeSummary } from '../composables/full-reduction-page/helpers';

defineProps<{
  form: FullReductionEditorForm;
  loading: boolean;
  open: boolean;
  storeOptions: Array<{ label: string; value: string }>;
  submitText: string;
  submitting: boolean;
  title: string;
}>();

const emit = defineEmits<{
  (event: 'addReduceTier'): void;
  (event: 'close'): void;
  (event: 'openGiftApplicablePicker'): void;
  (event: 'openGiftScopePicker'): void;
  (event: 'openSecondHalfApplicablePicker'): void;
  (event: 'removeReduceTier', index: number): void;
  (event: 'setActivityType', value: MarketingFullReductionActivityType): void;
  (event: 'setChannels', value: MarketingFullReductionChannel[]): void;
  (event: 'setDescription', value: string): void;
  (event: 'setFormStoreIds', value: string[]): void;
  (event: 'setGiftBuyQuantity', value: null | number): void;
  (event: 'setGiftGiftQuantity', value: null | number): void;
  (event: 'setGiftScopeType', value: MarketingFullReductionGiftScopeType): void;
  (event: 'setName', value: string): void;
  (event: 'setReduceTierMeetAmount', index: number, value: null | number): void;
  (
    event: 'setReduceTierReduceAmount',
    index: number,
    value: null | number,
  ): void;
  (
    event: 'setSecondHalfDiscountType',
    value: MarketingFullReductionSecondHalfDiscountType,
  ): void;
  (event: 'setStackWithCoupon', value: boolean): void;
  (
    event: 'setStoreScopeMode',
    value: MarketingFullReductionStoreScopeMode,
  ): void;
  (event: 'setValidDateRange', value: [Dayjs, Dayjs] | null): void;
  (event: 'submit'): void;
}>();

function onActivityTypeChange(value: unknown) {
  if (value === 'reduce' || value === 'gift' || value === 'second_half') {
    emit('setActivityType', value);
  }
}

function onGiftScopeTypeChange(value: unknown) {
  if (value === 'same_lowest' || value === 'specified') {
    emit('setGiftScopeType', value);
  }
}

function onSecondHalfDiscountTypeChange(value: unknown) {
  if (
    value === 'half' ||
    value === 'sixty' ||
    value === 'seventy' ||
    value === 'free'
  ) {
    emit('setSecondHalfDiscountType', value);
  }
}

function onStoreScopeModeChange(value: unknown) {
  if (value === 'all' || value === 'stores') {
    emit('setStoreScopeMode', value);
  }
}

function onDateRangeChange(value: [Dayjs, Dayjs] | [string, string] | null) {
  if (!value) {
    emit('setValidDateRange', null);
    return;
  }

  const [start, end] = value;
  if (typeof start === 'string' || typeof end === 'string') {
    emit('setValidDateRange', [dayjs(String(start)), dayjs(String(end))]);
    return;
  }

  emit('setValidDateRange', value as [Dayjs, Dayjs]);
}

function onStoreIdsChange(value: unknown) {
  if (!Array.isArray(value)) {
    emit('setFormStoreIds', []);
    return;
  }
  emit('setFormStoreIds', value.map(String));
}

function resolveToggledChannels(
  channels: MarketingFullReductionChannel[],
  channel: MarketingFullReductionChannel,
) {
  if (channels.includes(channel)) {
    return channels.filter((item) => item !== channel);
  }
  return [...channels, channel];
}

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

<template>
  <Drawer
    :open="open"
    :title="title"
    width="560"
    :destroy-on-close="false"
    class="mfr-editor-drawer"
    @close="emit('close')"
  >
    <Spin :spinning="loading">
      <Form layout="vertical" class="mfr-editor-form">
        <Form.Item label="活动类型" required>
          <Radio.Group
            :value="form.activityType"
            button-style="solid"
            @update:value="onActivityTypeChange"
          >
            <Radio.Button
              v-for="item in FULL_REDUCTION_EDITOR_ACTIVITY_OPTIONS"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </Radio.Button>
          </Radio.Group>
        </Form.Item>

        <Form.Item label="活动名称" required>
          <Input
            :value="form.name"
            :maxlength="64"
            placeholder="如：午市满减优惠"
            @update:value="(value) => emit('setName', String(value ?? ''))"
          />
        </Form.Item>

        <template v-if="form.activityType === 'reduce'">
          <div class="mfr-section-title">满减规则</div>
          <Form.Item
            v-for="(tier, index) in form.reduceTiers"
            :key="`tier-${index}`"
            class="mfr-tier-item"
          >
            <div class="mfr-inline-fields">
              <span>满</span>
              <InputNumber
                :value="tier.meetAmount ?? undefined"
                :min="0.01"
                :precision="2"
                placeholder="金额"
                @update:value="
                  (value) =>
                    emit(
                      'setReduceTierMeetAmount',
                      index,
                      parseNullableNumber(value),
                    )
                "
              />
              <span>元减</span>
              <InputNumber
                :value="tier.reduceAmount ?? undefined"
                :min="0.01"
                :precision="2"
                placeholder="金额"
                @update:value="
                  (value) =>
                    emit(
                      'setReduceTierReduceAmount',
                      index,
                      parseNullableNumber(value),
                    )
                "
              />
              <span>元</span>
              <button
                type="button"
                class="mfr-tier-delete"
                :disabled="form.reduceTiers.length <= 1"
                @click="emit('removeReduceTier', index)"
              >
                删除
              </button>
            </div>
          </Form.Item>

          <Form.Item>
            <button
              type="button"
              class="mfr-add-tier"
              @click="emit('addReduceTier')"
            >
              + 添加阶梯
            </button>
          </Form.Item>
        </template>

        <template v-if="form.activityType === 'gift'">
          <div class="mfr-section-title">满赠规则</div>
          <Form.Item label="赠送条件" required>
            <div class="mfr-inline-fields">
              <span>购买满</span>
              <InputNumber
                :value="form.giftRule.buyQuantity ?? undefined"
                :min="1"
                :precision="0"
                placeholder="如：2"
                @update:value="
                  (value) =>
                    emit('setGiftBuyQuantity', parseNullableNumber(value))
                "
              />
              <span>件赠</span>
              <InputNumber
                :value="form.giftRule.giftQuantity ?? undefined"
                :min="1"
                :precision="0"
                placeholder="如：1"
                @update:value="
                  (value) =>
                    emit('setGiftGiftQuantity', parseNullableNumber(value))
                "
              />
              <span>件</span>
            </div>
          </Form.Item>

          <Form.Item label="赠品范围类型" required>
            <Radio.Group
              :value="form.giftRule.giftScopeType"
              button-style="solid"
              @update:value="onGiftScopeTypeChange"
            >
              <Radio.Button
                v-for="item in FULL_REDUCTION_GIFT_SCOPE_OPTIONS"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </Radio.Button>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="适用商品范围" required>
            <div class="mfr-scope-line">
              <Button @click="emit('openGiftApplicablePicker')">
                选择商品/分类
              </Button>
              <span class="mfr-scope-text">
                {{ resolveScopeSummary(form.giftRule.applicableScope) }}
              </span>
            </div>
          </Form.Item>

          <Form.Item
            v-if="form.giftRule.giftScopeType === 'specified'"
            label="指定赠品范围"
            required
          >
            <div class="mfr-scope-line">
              <Button @click="emit('openGiftScopePicker')">选择赠品</Button>
              <span class="mfr-scope-text">
                {{ resolveScopeSummary(form.giftRule.giftScope) }}
              </span>
            </div>
          </Form.Item>
        </template>

        <template v-if="form.activityType === 'second_half'">
          <div class="mfr-section-title">第二份优惠</div>
          <Form.Item label="第二份折扣" required>
            <Radio.Group
              :value="form.secondHalfRule.discountType"
              button-style="solid"
              @update:value="onSecondHalfDiscountTypeChange"
            >
              <Radio.Button
                v-for="item in FULL_REDUCTION_SECOND_HALF_DISCOUNT_OPTIONS"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </Radio.Button>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="适用商品范围" required>
            <div class="mfr-scope-line">
              <Button @click="emit('openSecondHalfApplicablePicker')">
                选择商品/分类
              </Button>
              <span class="mfr-scope-text">
                {{ resolveScopeSummary(form.secondHalfRule.applicableScope) }}
              </span>
            </div>
          </Form.Item>
        </template>

        <div class="mfr-section-divider"></div>

        <Form.Item label="活动时间" required>
          <DatePicker.RangePicker
            :value="form.validDateRange ?? undefined"
            format="YYYY-MM-DD"
            class="mfr-range-picker"
            @update:value="onDateRangeChange"
          />
        </Form.Item>

        <Form.Item label="适用渠道" required>
          <div class="mfr-channel-pills">
            <button
              v-for="item in FULL_REDUCTION_CHANNEL_OPTIONS"
              :key="item.value"
              type="button"
              class="mfr-channel-pill"
              :class="{ checked: form.channels.includes(item.value) }"
              @click="
                emit(
                  'setChannels',
                  resolveToggledChannels(form.channels, item.value),
                )
              "
            >
              {{ item.label }}
            </button>
          </div>
        </Form.Item>

        <Form.Item label="适用门店" required>
          <Radio.Group
            :value="form.storeScopeMode"
            @update:value="onStoreScopeModeChange"
          >
            <Radio
              v-for="item in FULL_REDUCTION_STORE_SCOPE_OPTIONS"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </Radio>
          </Radio.Group>

          <Select
            v-if="form.storeScopeMode === 'stores'"
            mode="multiple"
            :value="form.storeIds"
            :options="storeOptions"
            class="mfr-store-multi"
            placeholder="请选择适用门店"
            @update:value="onStoreIdsChange"
          />
        </Form.Item>

        <Form.Item label="叠加规则">
          <div class="mfr-channel-pills">
            <button
              v-for="item in FULL_REDUCTION_STACK_OPTIONS"
              :key="String(item.value)"
              type="button"
              class="mfr-channel-pill"
              :class="{ checked: form.stackWithCoupon === item.value }"
              @click="emit('setStackWithCoupon', item.value)"
            >
              {{ item.label }}
            </button>
          </div>
        </Form.Item>

        <Form.Item label="活动说明">
          <Input.TextArea
            :value="form.description"
            :maxlength="512"
            :rows="3"
            placeholder="如：每单限享一次活动优惠"
            @update:value="
              (value) => emit('setDescription', String(value ?? ''))
            "
          />
        </Form.Item>
      </Form>
    </Spin>

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