import Handsontable, { GridSettings } from '@sc/handsontable';
import { parse } from '@/utils/frontend/dom';
import { ProjectType, IReceivedShareProject } from '@sc/types';
import { bindPopover } from '@/components/popover/composables/usePopover';

const getIconName = (type: ProjectType) => {
  let iconName = '';
  switch (type) {
    case ProjectType.FOLDER:
      iconName = 'dsk-folder-open';
      break;
    case ProjectType.CONSTRUCTION:
      iconName = 'dsk-city-one';
      break;
    case ProjectType.SINGLE:
      iconName = 'dsk-home-two';
      break;
    default:
      break;
  }
  return iconName;
};

export default function (
  instance: Handsontable,
  row: number,
  col: number,
  prop: string | number,
  value: any,
  cellProperties: GridSettings
): HTMLElement {
  // 当前行的源数据
  const rowSourceData = instance.getSourceDataAtRow(row) as IReceivedShareProject;
  const children = rowSourceData.children;
  if (!children.length) {
    return parse('<div></div>') as HTMLElement;
  }

  const items = children.map(
    item =>
      `<div style="display: inline-flex; align-items: center; background: #EBEEF5; margin-left: 5px; padding: 0px 5px; height: calc(100% - 2px);">
        <i class="iconfont ${getIconName(item.type)}"></i>
        <span>${item.name}</span>
      </div>`
  );
  const template = `<div style="display: flex; align-items: center; height: 100%;">${items.join('')}</div>`;

  const td = parse('<div></div>') as HTMLElement;
  const container = parse(template) as HTMLElement;
  td.appendChild(container);
  const content = children
    .map(
      item => `<div> <i class="iconfont ${getIconName(item.type)}"></i>
  <span>${item.name}</span></div>`
    )
    .join('');
  if (content) {
    bindPopover(td, container, content);
  }

  return td;
}
