import { TableActionType } from '@/components/Table';
import { FormActionType } from '@/components/Form';
import { Ref, toRefs } from 'vue';

// 替换v2中迁移过来的JeecgListMixins，将组件的通用方法提取出来，放置此处

type UseTableMethod = TableActionType & {
  getForm: () => FormActionType;
};

interface ListOptions {
  tableContext: [
    (instance: TableActionType, formInstance: UseTableMethod) => void,
    TableActionType & {
      getForm: () => FormActionType;
    },
    {
      rowSelection: any;
      selectedRows: Ref<Recordable[]>;
      selectedRowKeys: Ref<any[]>;
    },
  ];

  modalFormRef: Ref<any>;
  formRef: Ref<any>;
  batchDelete: any;
  deleteOne: any;
}

export function useCommonList(options: ListOptions) {
  const batchDelete = options.batchDelete;
  const deleteOne = options.deleteOne;

  const { modalFormRef, formRef } = toRefs(options);

  const [
    registerTable,
    { reload, clearSelectedRowKeys, updateTableDataRecord, findTableDataRecord, getDataSource },
    { rowSelection, selectedRowKeys },
  ] = options.tableContext;

  /**
   * 成功回调
   */
  function handleReload() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    modalFormRef.value.title = '新增';
    modalFormRef.value.disableSubmit = false;
    modalFormRef.value.add();
  }

  /*
   *
   * 编辑*/
  function handleEdit(record) {
    modalFormRef.value.title = '编辑';
    modalFormRef.value.edit(record);
    modalFormRef.value.disableSubmit = false;
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    modalFormRef.value.disableSubmit = true;
    modalFormRef.value.edit(record);
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
    ];
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
      },
    ];
  }

  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  return {
    handleReload,
    handleEdit,
    getTableAction,
    batchHandleDelete,
    handleDetail,
    getDropDownAction,
    handleDelete,
    handleAdd,
    searchQuery,
    searchReset,
  };
}
