import { Ref } from 'vue';
import { TableColumnsOperate } from '../../types';
import TCOLocalStorage from './tcoLocalStorage';
import {
  getColumnsAOrM,
  getColumnsByTableValue,
  insertColumnsAOrM,
  parseExclude
} from './utils';

/**
 * 表格列回显
 */
const reshow = (
  originColumns: any[],
  tableColumnsOperate: Ref<TableColumnsOperate>,
  tcoLocalStorage: TCOLocalStorage
) => {
  let { excludeHead, excludeTail, initHidden } = tableColumnsOperate.value;
  const { exclude, lotId, tableName } = tableColumnsOperate.value;

  excludeHead = parseExclude(excludeHead);
  excludeTail = parseExclude(excludeTail || exclude);
  initHidden = parseExclude(initHidden);

  const tableValue = tcoLocalStorage.get(lotId, tableName)?.value || [];
  let columns = originColumns;
  // [initHidden，没有缓存的场景]排除初始化就需要隐藏的列
  columns = columns.filter((_: any) => !initHidden!.includes(_.dataIndex + ''));

  // 当存在缓存数据时才进行操作
  if (tableValue.length > 0) {
    // ✨ 排除不参与的列
    let columnsReady = originColumns.filter(
      (_: any) => !excludeHead!.includes(_.dataIndex + '')
    );
    columnsReady = columnsReady.filter(
      (_: any) => !excludeTail!.includes(_.dataIndex + '')
    );

    // ✨ 提取不参与的头部列，用于追加到数组前面
    const columnsExcludeHead = originColumns.filter((_: any) =>
      excludeHead!.includes(_.dataIndex + '')
    );
    // ✨ 提取不参与的列（一般是操作列），用于追加到数组后面
    const columnsExcludeTail = originColumns.filter((_: any) =>
      excludeTail!.includes(_.dataIndex + '')
    );
    const columnsByTableValue = getColumnsByTableValue(
      columnsReady,
      tableValue
    );

    let columnsAOrM = getColumnsAOrM(columnsReady, tableValue);
    // [initHidden，有缓存的场景]排除初始化就需要隐藏的列，从上面对比判断出这个列是后面新增的，且还需要判断这个列是否有被加入初始化不展示
    columnsAOrM = columnsAOrM.filter(
      (_: any) => !initHidden!.includes(_.item.dataIndex + '')
    );

    const arr = insertColumnsAOrM(columnsByTableValue, columnsAOrM);
    columns = [...columnsExcludeHead, ...arr, ...columnsExcludeTail];
  }
  return columns;
};
export default reshow;
