/*
 * @Author: renxin renxin0828@163.com
 * @Date: 2023-05-23 19:36:07
 * @LastEditors: renxin renxin0828@163.com
 * @LastEditTime: 2023-05-25 17:55:12
 * @FilePath: \yx-admin\src\hooks\web\useBatchDeleteString.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
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;
    selectedRowIds.value = selectedRowKeys.toString();
  };

  // 全选按钮
  const onSelectAll = (_, selectedRows, __) => {
    const selectedRowKeys = selectedRows.map((item) => item.id);
    selectedRowIds.value = selectedRowKeys.toString();
  };
  const handleDeleteOrBatchDelete = async (record: Recordable | null) => {
    setProps({
      loading: true,
    });
    try {
      if (record) {
        await deleteFn((record.id).toString());
        createMessage.success('删除成功');
      } else {
        await deleteFn(selectedRowIds.value);
        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 };
}
