import { Hot } from '@/types/components';
import { on, query } from '@/utils/frontend/dom';

// 获取鼠标点击的区域相关代码
export default function useClickPosition(wrapperDOM: HTMLElement, tableSettings: Hot.ISettings): any {
  const { onClickPosition } = tableSettings;
  if (typeof onClickPosition !== 'function') return undefined;
  let whichKey: Hot.MouseKey;
  let clickPosition: Hot.ClickPosition;

  const $masterCore = query(wrapperDOM, '.ht_master.handsontable .htCore') as HTMLElement;
  const $masterBorders = query(wrapperDOM, '.ht_master.handsontable .htBorders') as HTMLElement;
  const $topCore = query(wrapperDOM, '.ht_clone_top.handsontable .htCore') as HTMLElement;
  const $topBorders = query(wrapperDOM, '.ht_clone_top.handsontable .htBorders') as HTMLElement;
  const $bottomCore = query(wrapperDOM, '.ht_clone_bottom.handsontable .htCore') as HTMLElement;
  const $bottomBorders = query(wrapperDOM, '.ht_clone_bottom.handsontable .htBorders') as HTMLElement;
  const $leftCore = query(wrapperDOM, '.ht_clone_left.handsontable .htCore') as HTMLElement;
  const $leftBorders = query(wrapperDOM, '.ht_clone_left.handsontable .htBorders') as HTMLElement;
  const $topLeftCore = query(wrapperDOM, '.ht_clone_top_left_corner.handsontable .htCore') as HTMLElement;
  const $topLeftBorders = query(wrapperDOM, '.ht_clone_top_left_corner.handsontable .htBorders') as HTMLElement;

  const containers = [
    $masterCore,
    $masterBorders,
    $topCore,
    $topBorders,
    $bottomCore,
    $bottomBorders,
    $leftCore,
    $leftBorders,
    $topLeftCore,
    $topLeftBorders,
  ];
  // 是否是内容区域
  const isContent = (target: Node) => containers.some(container => container && container.contains(target));

  const handleClick = (event: Event) => {
    const e = event as MouseEvent;
    switch (e.button) {
      case 0:
        whichKey = 'left';
        break;
      case 1:
        whichKey = 'middle';
        break;
      case 2:
      default:
        whichKey = 'right';
        break;
    }
    const target = event.target as Node;
    if (wrapperDOM.contains(target)) clickPosition = isContent(target) ? 'content' : 'barren';
    else clickPosition = 'outside';

    onClickPosition(whichKey, clickPosition);
  };
  on(document.body, 'mouseup', handleClick);
  return handleClick;
}
