import {Modal, TabPaneProps, TabsProps} from 'antd';
import {ReactNode} from 'react';
import {useStore} from 'zustand';
import {tabStore} from '@stores';
import {useContextMenu, ItemParams} from 'react-contexify';
import {DragEndEvent} from '@dnd-kit/core';
import {arrayMove} from '@dnd-kit/sortable';
import {shallowEqual} from '@utils';

// 为了首页采购单列表中的更多可以点击触发新增tab
(window as any).tabAddDispatch = function (options: {
  key: string;
  url: string;
  label: string;
}) {
  const {dispatch} = tabStore.getState();

  dispatch({type: 'ADD', payload: options});
};

export type Tab = {
  key: string;
  label: ReactNode;
} & Omit<TabPaneProps, 'tab'>;

export function useTabItems() {
  const {originalTab, dispatch} = useStore(
    tabStore,
    function (state) {
      return {
        dispatch: state.dispatch,
        originalTab: state.tabList,
      };
    },
    shallowEqual,
  );

  function onDragEnd({active, over}: DragEndEvent) {
    if (!over) return;

    const {id: fromId} = active,
      {id: toId} = over;
    const fromIdx = originalTab.findIndex(val => val.key === fromId),
      toIdx = originalTab.findIndex(val => val.key === toId);

    dispatch({
      type: 'SORT',
      payload: arrayMove(originalTab, fromIdx, toIdx),
    });
  }

  return [originalTab, onDragEnd] as const;
}

export function useTabActive() {
  const dispatch = useStore(tabStore, state => state.dispatch);
  const {activeKey, setActiveKey} = useStore(
    tabStore,
    function (state) {
      return {activeKey: state.activeKey, setActiveKey: state.setActiveKey};
    },
    shallowEqual,
  );

  function onClear() {
    Modal.confirm({
      title: '清除标签页',
      content: '你确定要关闭所有标签页吗？',
      onOk() {
        dispatch({type: 'CLEAR'});
      },
    });
  }

  const onEdit: TabsProps['onEdit'] = function (target, action) {
    if (action === 'remove' && typeof target === 'string') {
      dispatch({type: 'REMOVE', payload: target});
    }
  };

  return [activeKey, {onChange: setActiveKey, onClear, onEdit}] as const;
}

export function useMenu() {
  const {show} = useContextMenu({id: 'content_menu'});
  const dispatch = useStore(tabStore, state => state.dispatch);

  function onMenuitemClick(e: ItemParams<{key: string}, any>) {
    const {props, id} = e;
    if (!id || !props?.key) return;
    const {key} = props;
    switch (id) {
      case 'clear':
        dispatch({type: 'CLEAR'});
        break;
      case 'remove':
        dispatch({type: 'REMOVE', payload: key});
        break;
      case 'remove_other':
        dispatch({type: 'REMOVE_OTHER', payload: key});
        break;
      case 'remove_right':
        dispatch({type: 'REMOVE_RIGHT', payload: key});
        break;
    }
  }

  return {show, onMenuitemClick};
}
