import { RecordType } from '@/components/Stars/interface';
import { StarModel } from '@/components/Stars/StarModel';
import StarTable from '@/components/Stars/StarTable';
import { StarTableProps } from '@/components/Stars/StarTable/interface';
import { observer } from 'mobx-react';
import { useEffect } from 'react';

const PageTable = (
  props: StarTableProps & {
    model: StarModel;
    defaultParams?: RecordType;
    defaultOrders?: RecordType;
    onLoading?: () => void;
  },
) => {
  const {
    model,
    model: {
      data: { page: data },
      params: { page: params },
    },
    columns,
    defaultParams,
    defaultOrders,
    onLoading,
    onQueryClick,
    ...rest
  } = props;

  /**
   * 页面初始化加载数据
   */
  useEffect(() => {
    onLoading ? onLoading!() : model.page({ page: 1, size: 10, params: defaultParams, orders: defaultOrders });
  }, []);

  const ds = data && data.data ? data.data.map((d: any) => ({ key: d.id, ...d })) : [];

  return (
    <StarTable
      columns={columns}
      dataSource={ds}
      pagination={{
        pageSize: data.size,
        current: data.page,
        total: data.total,
      }}
      onQueryClick={(values: RecordType) => {
        params.page = 1;
        params.params = { ...defaultParams };
        for (const key of Object.keys(values)) {
          if (values[key] !== undefined && values[key] !== null && values[key] !== '') {
            params.params[key] = values[key];
          }
        }
        model.page(params);
        onQueryClick && onQueryClick(values);
      }}
      onPageChanged={(page, size) => {
        params.page = page;
        params.size = size;
        model.page(params);
      }}
      onRemoveClick={async (v) => {
        await model.remove(v);
        model.page(params);
      }}
      onSaveClick={async (values: any, mode) => {
        if (mode === 'add') await model.add(values);
        else await model.update(values);
        model.page(params);
      }}
      operation
      toolbar
      autoForm
      autoQuery
      {...rest}
    />
  );
};
const ObserverPageTable = observer(PageTable);
export default ObserverPageTable;
