import { computed, reactive, ref } from 'vue';
import type { PaginationProps } from 'naive-ui';
import { useLoading } from '@sa/hooks';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { jsonClone } from '~/packages/utils/src/klona';

// itemCount 数据回来，赋值一下，例如
// async function getData() {
//   warningList<Api.AbilityWarn.Warn[]>().then(res => {
//     alarmData.value = res.data as Api.AbilityWarn.Warn[];
//     updatePagination({ itemCount: res.response.data.total });
//   });
// }

export function usePagination(config?: {
  queryParams?: Record<string, any>;
  getData?: () => Promise<void>;
  showTotal?: boolean; // 是否显示总数
}) {
  const appStore = useAppStore();

  const { loading, startLoading, endLoading } = useLoading();

  const isMobile = computed(() => appStore.isMobile);

  const showTotal = config?.showTotal ?? true;

  const searchParams: Record<string, any> = ref({});

  const pagination: PaginationProps = reactive({
    page: 1,
    pageSize: config?.queryParams?.pageSize || 10,
    showSizePicker: true,
    pageSizes: [1, 2, 3, 4, 5].map(item => (config?.queryParams?.pageSize || 10) * item),
    onUpdatePage: async (page: number) => {
      pagination.page = page;

      updateSearchParams({
        pageNum: page,
        pageSize: pagination.pageSize!
      });

      config?.getData?.();
    },
    onUpdatePageSize: async (pageSize: number) => {
      pagination.pageSize = pageSize;
      pagination.page = 1;

      updateSearchParams({
        pageNum: pagination.page,
        pageSize
      });

      config?.getData?.();
    },
    ...(showTotal
      ? {
          prefix: page => $t('datatable.itemCount', { total: page.itemCount })
        }
      : {})
  });

  if (config?.queryParams) {
    searchParams.value = jsonClone(config.queryParams);
    config.queryParams.pageNum ||= pagination.page;
    config.queryParams.pageSize ||= pagination.pageSize;
    initSearchParams();
  }

  // 更新搜索参数中的分页参数
  function updateSearchParams(params: Record<string, any>) {
    if (!config || !config.queryParams) return;
    Object.assign(searchParams.value, params);
  }

  function initSearchParams() {
    if (!config || !config.queryParams) return;
    updateSearchParams({
      pageNum: 1,
      pageSize: pagination.pageSize!
    });
  }

  // 移动端看判断是否显示总数，页码个数也变更
  const mobilePagination = computed(() => {
    const p: PaginationProps = {
      ...pagination,
      pageSlot: isMobile.value ? 3 : 9,
      prefix: !isMobile.value && showTotal ? pagination.prefix : undefined
    };

    return p;
  });

  function updatePagination(update: Partial<PaginationProps>) {
    Object.assign(pagination, update);
  }

  /**
   * 按页码获取数据
   *
   * @param pageNum the page number. default is 1
   */
  async function getDataByPage(pageNum: number = 1) {
    updatePagination({
      page: pageNum
    });

    updateSearchParams({
      pageNum,
      pageSize: pagination.pageSize!
    });

    await config?.getData?.();
  }

  // 重置分页
  function resetPagination() {
    updatePagination({
      page: 1
    });

    updateSearchParams({
      pageNum: 1
    });
  }

  function resetSearchParams() {
    if (!config || !config.queryParams) return;
    searchParams.value = jsonClone(config?.queryParams);
  }

  return {
    loading,
    startLoading,
    endLoading,
    isMobile,
    pagination,
    mobilePagination,
    searchParams,
    updatePagination,
    getDataByPage,
    resetPagination,
    initSearchParams,
    updateSearchParams,
    resetSearchParams
  };
}
