import { Ref, watch, watchEffect } 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 { exclude = [] } = tableColumnsOperate.value;
  const { lotId, tableName } = tableColumnsOperate.value;
  // 解析
  exclude = parseExclude(exclude);

  const tableValue = tcoLocalStorage.get(lotId, tableName)?.value || [];
  let columns = originColumns;
  // 当存在缓存数据时才进行操作
  if (tableValue.length > 0) {
    // ✨ 排除不参与的列
    const columnsReady = originColumns.filter(
      (_: any) => !exclude.includes(_.dataIndex + '')
    );
    // ✨ 提取不参与的列（一般是操作列），用于追加到数组后面
    const columnsExclude = originColumns.filter((_: any) =>
      exclude.includes(_.dataIndex + '')
    );
    const columnsByTableValue = getColumnsByTableValue(
      columnsReady,
      tableValue
    );
    const columnsAOrM = getColumnsAOrM(columnsReady, tableValue);
    const arr = insertColumnsAOrM(columnsByTableValue, columnsAOrM);
    columns = [...arr, ...columnsExclude];
  }
  return columns;
};
export default reshow;
