import React, { useCallback, useRef, useState, useEffect, useImperativeHandle } from 'react';
// import { stringify } from 'querystring';
import { notification } from 'antd';
import request from '@/utils/request';
import TableList from './TableList';
import Pagination from './Pagination';

export default React.forwardRef((props, ref) => {
  const [loading, setLoading] = useState(false);
  const mounted = useRef(false);
  const [list, setList] = useState();
  const [pageTotal, setPageTotal] = useState(0);

  const { api, urlData, params, onPageChange, postData=()=>{}, page, ...tableProps } = props;
  const [pageConfig, setPageConfig] = useState({ current: 1, pageSize: page ? 500 : 10, ...(page || {}) });

  // 更新分页
  const updatePage = useCallback(
    (current, pageSize) => {
      const config = pageSize ? { current, pageSize } : { current, pageSize: pageConfig.pageSize };
      const newPage = {
        ...pageConfig,
        ...config,
      };

      setPageConfig(newPage);
      if (onPageChange) {
        onPageChange(newPage);
      }
    },
    [pageConfig],
  );

  // 获取远程数据
  const fetchData = useCallback(() => {
    setLoading(true);


    const queryParams = {
      pageNum: pageConfig.current,
      pageSize: pageConfig.pageSize,
      pageNumber: pageConfig.current,
      ...(postData(params) || params || {}),
    };

    request({ ...api, urlData: urlData || undefined, params: queryParams })
      .then(res => {
 
        if (res.records) {
          const { total, records = [] } = res;
          setLoading(false);
          setList(records);
          setPageTotal(total);
        } else if (res.list) {
          const { total, list = [] } = res;
          setLoading(false);
          setList(list);
          setPageTotal(total);
        } else if (res.result) {
          const { total, records = [] } = res.result;
          setLoading(false);
          setList(records);
          setPageTotal(total);
        }
      })
      .catch(err => {
        console.error(err);
        setLoading(false);
        notification.warn({ message: err.message });
      });
  }, [params, pageConfig, api]);

  // 监控查询参数的修改
  useEffect(() => {
    // 通过更新分页来触发查询
    updatePage(1);
  }, [params]);

  // 监控分页的修改
  useEffect(() => {
    // 首次加载不查询
    if (!mounted.current) {
      mounted.current = true;
      return;
    }

    fetchData();
  }, [pageConfig]);

  // 透传给父组件部分方法
  useImperativeHandle(ref, () => ({
    reload: fetchData,
  }));

  return (
    <>
      <TableList loading={loading} dataSource={list} {...tableProps} />
      {
        props.page !== false &&
        (
          <Pagination {...pageConfig} total={pageTotal} onChange={updatePage} />
        )
      }
    </>
  );
});
