import {useTableModalEvent, useTableDeleteEvent, useSupertube} from '@hooks';
import {deleteDictionaryData} from '@apis';
import {DictionaryData} from '@models';
import {ColumnsType} from 'antd/es/table';
import {
  DOUBLE_BTN_WIDTH,
  MIDDLE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
} from '@utils';
import {Button} from 'antd';
import {useDicionaryType} from '../hooks';

const tableColumns: ColumnsType<DictionaryData> = [
  {title: '特来电ID', dataIndex: 'tldId', width: MIDDLE_TABLE_WIDTH},
  {title: '编号', dataIndex: 'code', width: NORMAL_TABLE_WIDTH},
  {title: '名称', dataIndex: 'name', width: NORMAL_TABLE_WIDTH},
];

export function useHandle(refetch: () => void) {
  const paramsType = useDicionaryType();
  const [{editId, visible}, {onAdd, onClose}] = useTableModalEvent({
    id: '',
    tldId: '',
  });
  const [pendingId, onDelete] = useTableDeleteEvent(
    deleteDictionaryData,
    refetch,
    {
      label: paramsType,
      findId: state => state.id,
    },
  );
  const isSuper = useSupertube();

  const [
    {editId: storeId, visible: editStoreVisible},
    {onEdit, onClose: onEditStoreClose},
  ] = useTableModalEvent({type: '', id: ''});

  const btnColumns: ColumnsType<DictionaryData> = [
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width:
        isSuper && paramsType === '仓库' ? DOUBLE_BTN_WIDTH : SMALL_TABLE_WIDTH,
      fixed: 'right',
      render(_, {id, warehouseType, name}) {
        return (
          <>
            {paramsType === '仓库' && (
              <Button
                type='text'
                className='ant-text-btn-color-primary'
                disabled={pendingId === id}
                onClick={onEdit({id, type: warehouseType ?? ''})}
              >
                修改
              </Button>
            )}
            {isSuper && (
              <Button
                type='text'
                danger
                loading={pendingId === id}
                onClick={onDelete({id, type: paramsType}, name)}
              >
                删除
              </Button>
            )}
          </>
        );
      },
    },
  ];

  const finalColumns: ColumnsType<DictionaryData> =
    paramsType === '仓库'
      ? [
          ...tableColumns,
          {
            title: '仓库类型',
            dataIndex: 'warehouseType',
            width: SMALL_TABLE_WIDTH,
          },
        ]
      : tableColumns;

  const columns =
    isSuper || paramsType === '仓库'
      ? [...finalColumns, ...btnColumns]
      : tableColumns;

  return [
    {columns, editId, visible, storeId, editStoreVisible},
    {onAdd, onClose, onEditStoreClose},
  ] as const;
}
