import type { Ref } from 'vue';

import type { PunchCardEditorForm } from '#/views/marketing/punch-card/types';

/**
 * 文件职责：次卡主抽屉动作。
 */
import { message } from 'ant-design-vue';

import {
  getMarketingPunchCardDetailApi,
  saveMarketingPunchCardApi,
} from '#/api/marketing';

import {
  mapDetailToEditorForm,
  mapEditorFormToSaveDto,
  resetEditorForm,
} from './helpers';

interface CreateDrawerActionsOptions {
  canManage: Ref<boolean>;
  drawerMode: Ref<'create' | 'edit'>;
  form: PunchCardEditorForm;
  isDrawerLoading: Ref<boolean>;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  loadPunchCardList: () => Promise<void>;
  loadUsageRecords: () => Promise<void>;
  openProductPicker: (
    initialProductIds: string[],
    onConfirm: (selectedProductIds: string[]) => void,
  ) => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  function setDrawerOpen(value: boolean) {
    options.isDrawerOpen.value = value;
  }

  function setFormName(value: string) {
    options.form.name = value;
  }

  function setFormCoverImageUrl(value: string) {
    options.form.coverImageUrl = value;
  }

  function setFormSalePrice(value: null | number) {
    options.form.salePrice = value;
  }

  function setFormOriginalPrice(value: null | number) {
    options.form.originalPrice = value;
  }

  function setFormTotalTimes(value: null | number) {
    options.form.totalTimes = value;
  }

  function setFormValidityType(value: PunchCardEditorForm['validityType']) {
    options.form.validityType = value;
    if (value === 'days') {
      options.form.validDateRange = null;
      return;
    }

    options.form.validityDays = null;
  }

  function setFormValidityDays(value: null | number) {
    options.form.validityDays = value;
  }

  function setFormValidDateRange(value: [any, any] | null) {
    options.form.validDateRange = value;
  }

  function setFormScopeType(value: PunchCardEditorForm['scope']['scopeType']) {
    options.form.scope.scopeType = value;
    options.form.scope.categoryIds = [];
    options.form.scope.tagIds = [];
    options.form.scope.productIds = [];
  }

  function setScopeCategoryIds(value: string[]) {
    options.form.scope.categoryIds = [...value];
  }

  function setScopeTagIds(value: string[]) {
    options.form.scope.tagIds = [...value];
  }

  function setScopeProductIds(value: string[]) {
    options.form.scope.productIds = [...value];
  }

  function setFormUsageMode(value: PunchCardEditorForm['usageMode']) {
    options.form.usageMode = value;
    if (value === 'free') {
      options.form.usageCapAmount = null;
    }
  }

  function setFormUsageCapAmount(value: null | number) {
    options.form.usageCapAmount = value;
  }

  function setFormDailyLimit(value: null | number) {
    options.form.dailyLimit = value;
  }

  function setFormPerOrderLimit(value: null | number) {
    options.form.perOrderLimit = value;
  }

  function setFormPerUserPurchaseLimit(value: null | number) {
    options.form.perUserPurchaseLimit = value;
  }

  function setFormAllowTransfer(value: boolean) {
    options.form.allowTransfer = value;
  }

  function setFormExpireStrategy(value: PunchCardEditorForm['expireStrategy']) {
    options.form.expireStrategy = value;
  }

  function setFormDescription(value: string) {
    options.form.description = value;
  }

  function toggleNotifyChannel(value: string) {
    if (options.form.notifyChannels.includes(value)) {
      options.form.notifyChannels = options.form.notifyChannels.filter(
        (item) => item !== value,
      );
      return;
    }

    options.form.notifyChannels = [...options.form.notifyChannels, value];
  }

  async function openCreateDrawer() {
    if (!options.canManage.value) {
      return;
    }

    options.drawerMode.value = 'create';
    resetEditorForm(options.form);
    options.isDrawerOpen.value = true;
  }

  async function openEditDrawer(id: string) {
    if (!options.canManage.value) {
      return;
    }

    if (!options.selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    options.drawerMode.value = 'edit';
    options.isDrawerLoading.value = true;
    options.isDrawerOpen.value = true;

    try {
      const detail = await getMarketingPunchCardDetailApi({
        storeId: options.selectedStoreId.value,
        punchCardId: id,
      });
      Object.assign(options.form, mapDetailToEditorForm(detail));
    } catch (error) {
      console.error(error);
      options.isDrawerOpen.value = false;
      message.error('加载次卡详情失败');
    } finally {
      options.isDrawerLoading.value = false;
    }
  }

  async function openScopeProductPicker() {
    if (!options.canManage.value) {
      return;
    }

    await options.openProductPicker(
      options.form.scope.productIds,
      (selectedProductIds) => {
        options.form.scope.scopeType = 'product';
        options.form.scope.productIds = [...selectedProductIds];
      },
    );
  }

  async function submitDrawer() {
    if (!options.canManage.value) {
      return;
    }

    if (!options.selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    const name = options.form.name.trim();
    if (!name) {
      message.warning('请输入次卡名称');
      return;
    }

    if (!options.form.salePrice || options.form.salePrice <= 0) {
      message.warning('售价必须大于 0');
      return;
    }

    if (!options.form.totalTimes || options.form.totalTimes <= 0) {
      message.warning('总次数必须大于 0');
      return;
    }

    if (
      options.form.originalPrice !== null &&
      options.form.originalPrice !== undefined &&
      options.form.originalPrice > 0 &&
      options.form.originalPrice < options.form.salePrice
    ) {
      message.warning('原价不能小于售价');
      return;
    }

    if (
      options.form.validityType === 'days' &&
      (!options.form.validityDays || options.form.validityDays <= 0)
    ) {
      message.warning('请输入有效天数');
      return;
    }

    if (options.form.validityType === 'range' && !options.form.validDateRange) {
      message.warning('请选择有效日期范围');
      return;
    }

    if (
      options.form.scope.scopeType === 'category' &&
      options.form.scope.categoryIds.length === 0
    ) {
      message.warning('请至少选择一个分类');
      return;
    }

    if (
      options.form.scope.scopeType === 'tag' &&
      options.form.scope.tagIds.length === 0
    ) {
      message.warning('请至少选择一个标签');
      return;
    }

    if (
      options.form.scope.scopeType === 'product' &&
      options.form.scope.productIds.length === 0
    ) {
      message.warning('请至少选择一个商品');
      return;
    }

    if (
      options.form.usageMode === 'cap' &&
      (!options.form.usageCapAmount || options.form.usageCapAmount <= 0)
    ) {
      message.warning('请输入单次金额上限');
      return;
    }

    if (options.form.notifyChannels.length === 0) {
      message.warning('请至少选择一种购买通知方式');
      return;
    }

    options.isDrawerSubmitting.value = true;
    try {
      const payload = mapEditorFormToSaveDto(
        options.form,
        options.selectedStoreId.value,
      );
      await saveMarketingPunchCardApi(payload);
      message.success('保存成功');
      options.isDrawerOpen.value = false;
      await Promise.all([
        options.loadPunchCardList(),
        options.loadUsageRecords(),
      ]);
    } catch (error) {
      console.error(error);
      message.error('保存失败');
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  return {
    openCreateDrawer,
    openEditDrawer,
    openScopeProductPicker,
    setDrawerOpen,
    setFormAllowTransfer,
    setFormCoverImageUrl,
    setFormDailyLimit,
    setFormDescription,
    setFormExpireStrategy,
    setFormName,
    setFormOriginalPrice,
    setFormPerOrderLimit,
    setFormPerUserPurchaseLimit,
    setFormSalePrice,
    setFormScopeType,
    setFormTotalTimes,
    setFormUsageCapAmount,
    setFormUsageMode,
    setFormValidDateRange,
    setFormValidityDays,
    setFormValidityType,
    setScopeCategoryIds,
    setScopeProductIds,
    setScopeTagIds,
    submitDrawer,
    toggleNotifyChannel,
  };
}
