import type { OrderAllFilterState, OrderAllPaginationState } from '../../types';

import { message } from 'ant-design-vue';

import { createDefaultFilters } from './constants';
import { isDateRangeInvalid } from './helpers';

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

/**
 * 文件职责：全部订单筛选与分页行为。
 */
export function createFilterActions(options: FilterActionOptions) {
  function setStatus(value: string) {
    options.filters.status = (value || 'all') as OrderAllFilterState['status'];
  }

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

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

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

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

  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 handleReset() {
    const defaults = createDefaultFilters();
    options.filters.status = defaults.status;
    options.filters.channel = defaults.channel;
    options.filters.paymentMethod = defaults.paymentMethod;
    options.filters.keyword = defaults.keyword;
    options.filters.startDate = defaults.startDate;
    options.filters.endDate = defaults.endDate;
    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,
    handleReset,
    handleSearch,
    setChannel,
    setEndDate,
    setKeyword,
    setPaymentMethod,
    setStartDate,
    setStatus,
  };
}
