import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { Spin, notification } from 'antd'

import SearchForm from './SearchForm'
import SearchBody from './SearchBody'
import BodyHeader from './BodyHeader'
import BodyPagination from './BodyPagination'
import { getStorageBuilder } from './utils'
import Style from './style.less'

class SearchList extends React.PureComponent {
  static propTypes = {
    storage: PropTypes.object,
    title: PropTypes.any,
    actions: PropTypes.any,
    search: PropTypes.object,
    body: PropTypes.object,
    pagination: PropTypes.object,
    service: PropTypes.func,
    ejectRetrieve: PropTypes.func,
  }

  state = {
    defaultStorage: this.props.storage || getStorageBuilder('PAGE-SearchList'),
    dataSource: [],
    conditions: this.getStorage().get('conditions') || {},
    loadding: false,
    pageConfig: {
      ...(this.getStorage().get('pagination') || { current: 1, pageSize: 10 }),
      total: 0,
    },
  }

  componentDidMount () {
    if (this.props.ejectRetrieve) {
      this.props.ejectRetrieve(this.queryData)
    }
  }
  
  getStorage() {
    return this.props.storage || this.state.defaultStorage
  }

  handlePageChange = (current, pageSize) => {
    this.getStorage().set('pagination', { current, pageSize: 10 })

    this.setState(
      (state) => ({
        ...state,
        pageConfig: {
          ...state.pageConfig,
          current,
          pageSize,
        }
      }),
      this.queryData,
    )
  }

  repondToSearch = (conditions) => {
    // 查询提交会重置页码
    const { pageConfig } = this.state
    const newPageConfig = { ...pageConfig, current: 1, total: 0 }

    this.getStorage().set('conditions', conditions)
    this.getStorage().set('pagination', newPageConfig)

    this.setState(
      (state) => ({
        ...state,
        conditions,
        pageConfig: newPageConfig,
      }),
      this.queryData,
    )
  }

  handleSearchSubmit = (conditions) => {
    console.log('------conditions-------->?', conditions)
    this.repondToSearch(conditions)
  }

  handleSearchCancel = () => {
    this.repondToSearch({})
  }

  queryData = () => {
    if (this.props.service) {
      const pageConfigProps = this.props.pagination || {}
      const keyOfPageNumber = pageConfigProps.keyOfPageNumber || 'pageNumber'
      const keyOfPageSize= pageConfigProps.keyOfPageSize || 'pageSize'
      const keyOfTotalSize= pageConfigProps.keyOfTotalSize || 'total'

      const { conditions = {}, pageConfig } = this.state

      this.setState({ loadding: true })

      this.props.service({
        ...conditions,
        ...{
          [`${keyOfPageNumber}`]: pageConfig.current,
          [`${keyOfPageSize}`]: pageConfig.pageSize,
        },
      }).then((res) => {
        const [dataSource, pageParams = {}] = res || []

        this.setState((state) => ({
          ...state,
          loadding: false,
          dataSource,
          pageConfig: {
            ...state.pageConfig,
            total: pageParams[keyOfTotalSize],
          },
        }))
      }).catch((e) => {
        this.setState({ loadding: false })
        console.error(e)
      })
    }
  }

  render() {
    const {
      keyOfPageNumber,
      keyOfPageSize,
      keyOfTotalSize,
      ...leftPageParams
    } = this.props.pagination || {}

    const pageConfig = {
      ...leftPageParams,
      ...this.state.pageConfig,
    }

    const storage = this.getStorage()

    return (
      <div className={Style['search-list']}>
        <div className={Style['head']}>
          <SearchForm storage={storage} onSubmit={this.handleSearchSubmit} onCancel={this.handleSearchCancel} configs={this.props.search} />
        </div>
        <div className={Style['body']}>
          <BodyHeader storage={storage} title={this.props.title} actions={this.props.actions} />
          <Spin spinning={this.state.loadding}>
            <SearchBody storage={storage} dataSource={this.state.dataSource} configs={this.props.body} />
          </Spin>
          <BodyPagination storage={storage} onChange={this.handlePageChange} configs={pageConfig} />
        </div>
      </div>
    )
  }
}

function withSearchList (configs = {}) {
  const cacheKey = `PAGE-${configs.name || 'SearchList'}`
  const storage = getStorageBuilder(cacheKey)

  return React.forwardRef((props, ref) => {
    return <SearchList storage={storage} {...props} ref={ref} />
  })
}

export default SearchList;
export { withSearchList }
