function buildColumnConfigMap(tableColumns, map = {}) {
  if (!tableColumns || !tableColumns.length) {
    return map;
  }
  tableColumns.forEach((col) => {
    if (col.prop) {
      map[col.prop] = col;
    }
    if (col.columnId) {
      map[`__id__${col.columnId}`] = col;
    }
    if (col.children && col.children.length) {
      buildColumnConfigMap(col.children, map);
    }
  });
  return map;
}

function enrichColumnList(columns, configMap) {
  if (!columns || !columns.length) {
    return columns;
  }
  return columns.map((col) => {
    const newCol = Object.assign({}, col);
    if (col.slots) {
      newCol.slots = Object.assign({}, col.slots);
    }
    const field = col.field;
    const columnId = col.params && col.params.columnId;
    const config =
      (field && configMap[field]) ||
      (columnId && configMap[`__id__${columnId}`]);
    if (config) {
      applyColumnLabelIcon(newCol, config);
    }
    if (col.children && col.children.length) {
      newCol.children = enrichColumnList(col.children, configMap);
    }
    return newCol;
  });
}

/**
 * Apply data-table column header icon config to vxe-table column definition.
 */
export function applyColumnLabelIcon(col, columnConfig) {
  if (!col || !columnConfig) {
    return col;
  }

  const iconClass = columnConfig.labelIconClass;
  const position = columnConfig.labelIconPosition || "rear";
  const tooltip = columnConfig.labelTooltip;
  const required = !!columnConfig.required;
  const title = col.title;

  if (!iconClass && !required) {
    return col;
  }

  const buildIcon = (h) => {
    const icon = h("i", { class: ["vxe-cell-help-icon", iconClass] });
    if (!tooltip) {
      return icon;
    }
    return h(
      "el-tooltip",
      {
        props: { content: tooltip, effect: "dark", placement: "top" },
      },
      [icon]
    );
  };

  if (iconClass && position === "front" && !required) {
    col.titlePrefix = {
      icon: iconClass,
      ...(tooltip ? { content: tooltip } : {}),
    };
    return col;
  }

  if (required && !iconClass) {
    col.titlePrefix = { icon: "vxe-cell--required-icon" };
    return col;
  }

  col.slots = col.slots || {};
  delete col.titlePrefix;

  col.slots.header = (params, h) => {
    const nodes = [];
    if (required) {
      nodes.push(h("i", { class: "vxe-cell--required-icon" }));
    }
    if (iconClass && position === "front") {
      nodes.push(buildIcon(h));
    }
    nodes.push(h("span", { class: "vxe-cell--title" }, title));
    if (iconClass && position === "rear") {
      nodes.push(buildIcon(h));
    }
    return nodes;
  };

  return col;
}

export function enrichTableColumnsWithLabelIcon(columns, tableColumns) {
  const configMap = buildColumnConfigMap(tableColumns || []);
  return enrichColumnList(columns, configMap);
}
