import {BaseResult} from '@models';
import {useMutation} from '@tanstack/react-query';
import {deleteConfirm} from '@utils';
import {useBoolean, useLatest} from 'ahooks';
import {message} from 'antd';
import {useCallback, useRef, useState} from 'react';

export function useTableModalEvent<T = string>(initValue?: T, init?: boolean) {
  const memoInitvalue = useRef<T>((initValue ?? '') as T);
  const [visible, {setFalse, setTrue}] = useBoolean(init);
  const [editId, setEditId] = useState(memoInitvalue.current);

  const onEdit = useCallback(
    function (state: T) {
      return function () {
        setEditId(state);
        setTrue();
      };
    },
    [setTrue],
  );

  const onAdd = useCallback(
    function () {
      setTrue();
      setEditId(memoInitvalue.current);
    },
    [setTrue],
  );

  return [
    {visible, editId},
    {onClose: setFalse, onEdit, onAdd},
  ] as const;
}

export function useTableDeleteEvent<P>(
  fn: (params: P) => BaseResult,
  onFetch: () => void,
  {label, findId}: {label: string; findId?: (state: P) => string},
) {
  const [pendingId, setPendingId] = useState('');

  const {mutate} = useMutation(fn, {
    onSuccess(data) {
      setPendingId('');

      if (data.msg === '200') {
        onFetch();
        message.success('删除成功');
      }
    },
  });

  const findPendintId = useLatest(findId);
  const onDelte = useCallback(
    function (params: P, title: string) {
      return function () {
        deleteConfirm(
          label,
          function () {
            const pendintValue = findPendintId.current
              ? findPendintId.current(params)
              : (params as string);
            setPendingId(pendintValue);
            mutate(params);
          },
          {title},
        );
      };
    },
    [label, findPendintId, mutate],
  );

  return [pendingId, onDelte] as const;
}
