import type {
  FinanceSettlementFilterState,
  FinanceSettlementPaginationState,
} from '../../types';

/**
 * 文件职责：到账查询页面筛选与分页行为。
 */
import { message } from 'ant-design-vue';

import { isDateRangeInvalid } from './helpers';

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

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

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

  function setEndDate(value: string) {
    options.filters.endDate = 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,
    setStartDate,
  };
}
