import { ref, computed } from 'vue';
import { BasicTableProps } from '/@/components/Table';
import { useMessage } from '/@/hooks/web/useMessage';

/**
 *
 * @param deleteFn 要删除的API接口方法
 * @param handleSuccess  刷新表格的方法
 * @param setProps 用于设置表格的loading状态函数 - 防止页面重复提交
 *
 * @returns {
 * hasBatchDelete: 是否可以删除
 * selectionOptions 表格复选框配置项
 * handleDeleteOrBatchDelete 删除方法，适用单一删除和批量删除。参数为null为批量删除
 * resetSelectedRowKeys 重置选中的数据
 * }
 *
 */
interface selectionOptions {
  rowKey: string;
  clickToRowSelect: boolean;
  rowSelection: {
    onSelect: (_, __, selectedRowKeys: string[]) => void;
    onSelectAll: (_, selectedRows: string[], __) => void;
    type: 'radio' | 'checkbox';
  };
}
export function useBatchDelete(
  deleteFn: (deleteIds: string[]) => Promise<void>,
  handleSuccess: () => void,
  setProps: (props: Partial<BasicTableProps>) => void
) {
  const { createMessage } = useMessage();
  const selectedRowIds = ref<string[]>([]);
  const hasBatchDelete = computed(() => selectedRowIds.value.length <= 0);
  // 复选框选择事件
  const onSelect = (_, __, selectedRows) => {
    const selectedRowKeys = selectedRows.map((item) => item.id);
    selectedRowIds.value = selectedRowKeys;
  };

  // 全选按钮
  const onSelectAll = (_, selectedRows, __) => {
    const selectedRowKeys = selectedRows.map((item) => item.id);
    selectedRowIds.value = selectedRowKeys;
  };
  const handleDeleteOrBatchDelete = async (record: Recordable | null) => {
    setProps({
      loading: true,
    });
    try {
      if (record) {
        var res = await deleteFn([record.id]);
        if (res.resp_code == 1) {
          createMessage.error(res.resp_msg);
        } else if (res.resp_code == 0) {
          createMessage.success('删除成功');
        }
      } else {
        var res = await deleteFn(selectedRowIds.value);
        if (res.resp_code == 1) {
          createMessage.error(res.resp_msg);
        } else if (res.resp_code == 0) {
          createMessage.success('删除成功');
        }
        selectedRowIds.value = [];
      }
    } finally {
      setProps({
        loading: false,
      });
      handleSuccess();
    }
  };

  const resetSelectedRowKeys = () => {
    selectedRowIds.value = [];
  };

  const selectionOptions: selectionOptions = {
    rowKey: 'id',
    clickToRowSelect: false,
    rowSelection: {
      onSelect,
      onSelectAll,
      type: 'checkbox',
    },
  };
  return { hasBatchDelete, selectionOptions, handleDeleteOrBatchDelete, resetSelectedRowKeys };
}
