import type { FormModelValue, FormProInst } from "@/components";
import type { Page, PageParams, PageResult, TableProProps } from "../interface";
import { ref, type Ref, type ShallowRef } from "vue";

type TableProType = TableProProps<any, any>;

export default (
  api: TableProType["requestApi"],
  searFormInst: ShallowRef<FormProInst | null>,
  searchFormParams: Ref<FormModelValue>,
  isPageTable: boolean,
  dataCallBack?: TableProType["dataCallback"],
  requestError?: TableProType["requestError"]
) => {
  const datasource = ref<any[]>([]);
  const loading = ref(false);
  const page = ref<Page>({
    current: 1,
    size: 10,
    total: 0,
  });

  /**
   * 请求加载数据
   * @param needValidate 是否需要校验表单
   */
  const requestGetTableData = async (needValidate: boolean = true) => {
    try {
      //校验表单
      needValidate && (await searFormInst.value?.validate());
      //根据表格类型组装参数
      let totalSearchParams;
      if (isPageTable) {
        totalSearchParams = {
          params: searchFormParams.value,
          page: {
            current: page.value.current,
            size: page.value.size,
          },
        } as PageParams;
      } else {
        totalSearchParams = searchFormParams.value;
      }

      loading.value = true;

      const resp = await api(totalSearchParams);
      
      let tableData: any[];

      if (isPageTable) {
        const { current, records, size, total } = resp.data as PageResult<any>;
        //更新分页参数
        page.value = {
          current: parseInt(current),
          size: parseInt(size),
          total: parseInt(total),
        };
        tableData = records;
      } else {
        tableData = (resp.data || resp) as any[];
      }
     
      dataCallBack && (tableData = dataCallBack(tableData));
      datasource.value = tableData;
    } catch (error) {
      requestError?.(error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 重置表格状态 包括 dataSource loading page
   */
  const resetState = () => {
    datasource.value = [];
    loading.value = false;
    page.value = {
      current: 1,
      size: 10,
      total: 0,
    };
  };

  /**
   * 表格数据查询 与 requestGetTableData 区别是会将页面重置为1
   * 如果只做刷新数据请用 requestGetTableData
   */
  const search = async () => {
    page.value.current = 1;
    await requestGetTableData();
  };

  /**
   * @description 每页条数改变
   * @param current 当前页
   * @param {Number} size 页显示数量
   */
  const handleSizeChange = async (size: number) => {
    page.value.current = 1;
    page.value.size = size;
    await requestGetTableData();
  };

  /**
   * @description 当前页改变
   * @param current 当前页
   */
  const handleCurrentChange = async (current: number) => {
    page.value.current = current;
    await requestGetTableData();
  };

  return {
    datasource,
    loading,
    page,
    requestGetTableData,
    search,
    handleSizeChange,
    handleCurrentChange,
    resetState,
  };
};
