import { nextTick, Ref } from 'vue';
import { response } from '/@/utils/tools';


/**
 * 获取 El-Table的数据并处理total和loading
 * @param apiFunction 请求的接口函数
 * @param query 请求参数
 * @param tableData El-Table的数据
 * @param total El-Table数据的总条数
 * @param loading El-Table的loading状态
 */

export async function useElTableData(apiFunction: Function, query: any, tableData: Ref<any[]>, total: Ref<number>, loading: Ref<boolean>) {
  try {
    loading.value = true;
    const response = await apiFunction(query);
    let responseData = response.data;
    if (!Array.isArray(responseData)) {
      responseData = [ responseData ];
    }
    total.value = response.total;
    tableData.value = responseData;
    return { success: true, data: responseData, code: response.code, msg: response.msg };
  } catch (error) {
    console.error('Error in useElTableData==> ', error);
    return { success: false, error };
  } finally {
    loading.value = false;
    await nextTick();
    window.dispatchEvent(new Event('resize'));
  }
}
