import {retryErrorInterface} from '@apis';
import {GSErrorListData} from '@models';
import {useMutation} from '@tanstack/react-query';
import {
  NORMAL_TABLE_WIDTH,
  HUGE_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
  MIDDLE_TABLE_WIDTH,
} from '@utils';
import {Button, message} from 'antd';
import {ColumnsType} from 'antd/es/table';
import {useState} from 'react';

const columns: ColumnsType<GSErrorListData> = [
  {title: '请求地址', dataIndex: 'url', width: NORMAL_TABLE_WIDTH},
  {title: '错误信息', dataIndex: 'errorInfo', width: HUGE_TABLE_WIDTH},
  {title: '请求内容', dataIndex: 'dataVal', width: HUGE_TABLE_WIDTH},
  {title: '请求类型', dataIndex: 'type', width: SMALL_TABLE_WIDTH},
  {title: '请求时间', dataIndex: 'scrq', width: MIDDLE_TABLE_WIDTH},
];

function useRetry(refetch: () => void) {
  const [pendingId, setPendingId] = useState('');

  const {mutate} = useMutation({
    mutationFn: retryErrorInterface,
    onSuccess({msg}) {
      if (msg === '200') {
        message.success('已重试');
        refetch();
      }
    },
    onSettled() {
      setPendingId('');
    },
  });

  function onRetry(data: GSErrorListData) {
    return function () {
      const {id} = data;
      setPendingId(id);
      mutate(data);
    };
  }

  return [pendingId, onRetry] as const;
}

export function useColumns(fetch: () => void) {
  const [retryId, onRetry] = useRetry(fetch);

  const tableColumns: ColumnsType<GSErrorListData> = [
    ...columns,
    {
      title: '操作',
      width: SMALL_TABLE_WIDTH,
      fixed: 'right',
      dataIndex: 'id',
      render(_, data) {
        const {transmissionType, id} = data;

        return (
          <Button
            type='text'
            className='ant-text-btn-color-primary'
            disabled={transmissionType === 0}
            loading={retryId === id}
            onClick={onRetry(data)}
          >
            {transmissionType === 0 ? '已重试' : '重试'}
          </Button>
        );
      },
    },
  ];

  return tableColumns;
}
