import type {
  FinanceTransactionFilterState,
  FinanceTransactionPaginationState,
  QuickDateRangeKey,
} from '../../types';

/**
 * 文件职责：交易流水页面筛选与分页行为。
 */
import { message } from 'ant-design-vue';

import { isDateRangeInvalid, resolveQuickRangeDateRange } from './helpers';

interface FilterActionOptions {
  filters: FinanceTransactionFilterState;
  loadPageData: () => Promise<void>;
  pagination: FinanceTransactionPaginationState;
}

/** 创建筛选行为。 */
export function createFilterActions(options: FilterActionOptions) {
  function setType(value: string) {
    options.filters.type = (value ||
      'all') as FinanceTransactionFilterState['type'];
  }

  function setChannel(value: string) {
    options.filters.channel = (value ||
      'all') as FinanceTransactionFilterState['channel'];
  }

  function setPaymentMethod(value: string) {
    options.filters.paymentMethod = (value ||
      'all') as FinanceTransactionFilterState['paymentMethod'];
  }

  function setQuickRange(value: QuickDateRangeKey) {
    options.filters.quickRange = value;
    if (!value) {
      return;
    }

    const { startDate, endDate } = resolveQuickRangeDateRange(value);
    options.filters.startDate = startDate;
    options.filters.endDate = endDate;
  }

  function setStartDate(value: string) {
    options.filters.startDate = value;
    options.filters.quickRange = '';
  }

  function setEndDate(value: string) {
    options.filters.endDate = value;
    options.filters.quickRange = '';
  }

  function setKeyword(value: string) {
    options.filters.keyword = value;
  }

  async function handleSearch() {
    if (isDateRangeInvalid(options.filters)) {
      message.warning('开始日期不能晚于结束日期');
      return;
    }

    options.pagination.page = 1;
    await options.loadPageData();
  }

  async function handlePageChange(page: number, pageSize: number) {
    options.pagination.page = page;
    options.pagination.pageSize = pageSize;
    await options.loadPageData();
  }

  return {
    handlePageChange,
    handleSearch,
    setChannel,
    setEndDate,
    setKeyword,
    setPaymentMethod,
    setQuickRange,
    setStartDate,
    setType,
  };
}
