/*
/!**
 * 组合组件；配置"筛选StandardFilter"、"列表StandardTable"
 * 不加业务相关的功能
 * @param {Object} dataSource 数据源
 *   @value {Array} list 列表数据
 *   @value {Object} pagination 页码配置
 * @param {Function} request 接口请求数据源
 * @param {Object} params 请求参数：页码、筛选条件等
 * @param {Object} defaultParams 默认参数，在筛选重置的情况下不会更改
 * request:
 *   1、列表接口数据
 * *!/
import React, { ReactNode, forwardRef, useEffect, useState, useCallback, useImperativeHandle, useMemo } from 'react'
import { StandardFilter, StandardTable, ButtonGroup, } from "fan-standard-comp";
import { useStyles } from './index.style'
import { commonUse } from "@/data";
import { Spin } from 'antd';
import dayjs from "dayjs";

interface FilterFormProps {
  formItemGroup: any[]
  buttonGroup?: any[] | ReactNode
  syncToUrl?: (values) => void // 从url上取值后进行转换
  dateFormatter?: 'dayjs' | 'string' // 日期类的控件是否将其格式转换
}

interface CompositeTableProps {
  dataSource?: any // 列表数据静态数据来源
  request?: Function // 接口数据
  params?: any // 请求参数/页码
  defaultParams?: any // 默认的参数，在筛选重置的情况下不会更改
  formItemGroup?: any[]
  buttonGroup?: any[] | ReactNode
  commonUse: any
  children?: ReactNode
  onChange?: (targetKey: string, data?: any) => void // 页码或表单触发更新
  formatForm?: (fields: any) => void; // 转换筛选表单值
  page?: number | string, // 页码
  size?: number | string  // 单页数量
  getTableData?: Function // 获取表格数据
  form?: FilterFormProps // 筛选表单
}


const CompositeTable = forwardRef((props: CompositeTableProps, ref) => {
  const {
    dataSource, buttonGroup = [], params = {}, defaultParams = {}, columns,  children, request,
    onChange,
    getTableData,
    form,
    title
  } = props;
  const {
    formItemGroup = [], syncToUrl,
  } = form
  const { styles, cx } = useStyles();
  const [resDataSource, setResDataSource] = useState({
    list: [],
    pagination: {},
    keywords: {}
  })
  const [formKeywords, setFormKeywords] = useState({})
  const [queryLoading, setQueryLoading] = useState(false)
  const [searchLoading, setSearchLoading] = useState(false)
  const [filterForm, setFilterForm] = useState({
    values: {},
    form: undefined,
  })
  const paramsKey = useMemo(() => {
    return params
  }, [params])

  const localPagination = {page:1, size: 10} // 基础页码

  // ref 的转发
  useImperativeHandle(ref, () => {
    return {
      ...filterForm,
      dataSource: resDataSource,
      setDataSource: setResDataSource,
      reload: (filter) => loadData('refresh', {}, filter) // 更新列表
    }
  });
  /!**
   * 加载数据方法
   * @param {string} updateKey 触发列表位置
   * @param {Object} pagination 分页选项器
   * @param {Object} filters 过滤条件
   * @param {Object} sorter 排序条件
   *!/
  const loadData: any = useCallback(async (updateKey: string, pagination?: any = {}, filters?: any = {}, sorter?: any = {},
  ) => {
    if (updateKey !== 'init') {
      handleChange(updateKey, updateKey === 'reset' ? {} : { ...pagination, ...filters, ...sorter })
    }
    if (request) {
      setQueryLoading(true)
      let parameter = Object.assign(
        { ...defaultParams },
        // updateKey === 'init' ? { ...params } : {}, // 重置条件下，会清空params
        syncToUrl ? syncToUrl(params) : { ...params },
        {
          page: pagination?.page || params?.page || localPagination.page,
          size: pagination?.size || params?.size || localPagination.size
        },
        {
          ...filters
        },
        // 排序与筛选待定
        // (sorter && sorter.field && {
        //   sortField: sorter.field
        // }) || {},
        // (sorter && sorter.order && {
        //   sortOrder: sorter.order
        // }) || {},
      )
      const response = await request(parameter)
      setQueryLoading(false)
      setSearchLoading(false)
      // 转换列表数据
      if (response.code === '200') {
        setResDataSource(Object.assign({
          list: response?.data?.records,
          total: response?.data?.total || 0,
          pagination: {
            total: response?.data?.total || 0,
            current: response?.data?.current || commonUse.basePagination.page,
            pageSize: response?.data?.pageSize || commonUse.basePagination.size,
          },
          keywords: parameter || {}, // 关键字搜索字段
        }),)
      } else {
        setResDataSource({
          list: [],
          pagination: {},
          keywords: {}
        })
      }
    } else if (dataSource) {
      setResDataSource(dataSource)
    }
  }, [params, formItemGroup, dataSource, request])
  // console.log('resDataSource', resDataSource.keywords)
  useEffect(() => {
    getTableData && getTableData(resDataSource)
  }, [resDataSource])
  const fetchData = () => {

  }
  const handleChange = (targetKey: string, data?: any) => {
    onChange && onChange(targetKey, data)
  }
  useEffect(() => {
    setFormKeywords(syncToUrl ? syncToUrl({ ...params }) : { ...params })
  }, [params, syncToUrl])
  useEffect(() => {
    loadData('init')
  }, [])
  return <div className={cx('f-composite-container', styles.CompositeContainerStyle)}>
    <StandardFilter   {...form}
                      formItemGroup={formItemGroup}
                      gridLayout={'horizontal'} // 表单组与按钮组的排版
                      formLayout={'horizontal'} // 表单控件组的排版
                      min={100}
                      itemGroupConfig={{
                        columnCount: 4
                      }}
                      getFormFields={(fields, form) => {
                        setFilterForm({ values: fields, form: form?.current })
                      }}
                      initialValues={formKeywords}
                      onFilterSearch={(fields) => {
                        setSearchLoading(true)
                        formItemGroup.forEach(fItem => {
                          if (fItem.searchTransform && fields[fItem.filedName]) {
                            // 筛选参数转换
                            let trans = fItem.searchTransform(fields[fItem.filedName])
                            delete fields[fItem.filedName] // 提交时，删除有格式转换的字段名
                            fields = { ...fields, ...trans }
                          }
                        })
                        loadData('search', { ...commonUse.basePagination }, fields)
                      }}
                      onFilterReset={() => {
                        loadData('reset', {page: 1,}, {})
                      }}
                      className={cx('f-composite-filter', styles.CompositeFilterStyle)}
                      confirmButtonProps={{
                        loading: searchLoading
                      }}
      // dateFormatter={'string'}
    />
    <StandardTable data={resDataSource} columns={columns}
                   title={title}
                   buttonGroup={buttonGroup}
                   className={cx('f-composite-table', styles.CompositeTableStyle)}
                   onChange={(pagination, filters, sorter,) => {
                     // console.log(' pagination, filters, sorter', pagination, filters, sorter)
                     loadData('table', {
                       page: pagination.current,
                       size: pagination.pageSize
                     }, filters, sorter)
                   }}
    />
    {children}
  </div>
})

export default CompositeTable
*/