import { get, isEmpty } from 'lodash-es';
import type { DynamicTableProps } from '../dynamic-table';
import type { TableMethods, TableState } from './index';
import { exportJson2Excel } from '@/utils/Export2Excel';
import { getVisiCols } from '../hooks/commonMethods';

export type UseExportData2ExcelContext = {
  state: TableState;
  methods: TableMethods;
  props: DynamicTableProps;
};

export type ExportData2Excel = ReturnType<typeof useExportData2Excel>;

/**
 * 导出表格Excel
 */
export const useExportData2Excel = ({ props, state, methods }: UseExportData2ExcelContext) => {
  const exportData2Excel = async (type?: String) => {
    const {
      columns,
      exportFormatter,
      exportFileName,
      exportBookType,
      exportAutoWidth,
      autoClumns,
      exportColumns,
    } = props;
    const { getColumnKey, getAllTableData } = methods;
    const { tableData } = state;
    let showData: any = [];

    if (type) {
      showData = await getAllTableData();
    } else {
      showData = tableData.value;
    }

    //配置了导出列的情况下，优先使用导出列，如果没有导出列，从columns中取，前面两个都没有的话，从autoClumns中取
    const theaders =
      exportColumns.length > 0
        ? exportColumns
        : columns.length > 0
        ? columns.filter(
            (n) =>
              getColumnKey(n) &&
              getColumnKey(n) !== 'INDEX' &&
              getColumnKey(n) !== 'ACTION' &&
              getColumnKey(n) !== 'action' &&
              getColumnKey(n) !== 'SHOW',
          )
        : getVisiCols(autoClumns).filter(
            (n) =>
              getColumnKey(n) &&
              getColumnKey(n) !== 'INDEX' &&
              getColumnKey(n) !== 'ACTION' &&
              getColumnKey(n) !== 'action' &&
              getColumnKey(n) !== 'SHOW',
          );

    if (exportFormatter) {
      const { header, data } = exportFormatter(theaders, showData);
      if (isEmpty(header) || isEmpty(data)) {
        return;
      } else {
        exportJson2Excel({
          header,
          data,
          filename: exportFileName,
          bookType: exportBookType,
          autoWidth: exportAutoWidth,
        });
      }
    } else {
      exportJson2Excel({
        header: theaders.map((n) => n.title as string),
        data: showData.map((v) => theaders.map((header) => get(v, getColumnKey(header)!))),
        filename: exportFileName,
        bookType: exportBookType,
        autoWidth: exportAutoWidth,
      });
    }
  };
  return { exportData2Excel };
};
