// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Search, FullDatePicker } from '@woowalker/feui'
import EditListTable from '../../EditListTable'
// 工具库
import { isEqual } from 'lodash'
import moment from 'moment'

class KRDosageEnergyClassPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      dateType: '0',
      dateString: moment().format('YYYY'),
      searchParams: {},
      searchSize: undefined
    }
    this.refOfTable = null
  }

  updateRelatedFieldConfigs = () => {
    const { dateType, dateString } = this.state
    /**
     * payload: {
     *  code: 'EM079', // 配置了导出按钮的表格（ListPage或者ListTable）的 formCode 
     *  relatedTo: 'EM048', // 需要额外插入查询条件的 Search 组件的 formCode，如果是 LocalSearch 则这个属性可以缺省
     *  extraRows: ['额外插入的标题'] // 导出按钮需要插入的额外的导出标题
     * }
     * relatedTo 可以缺省，缺省的话只是插入 extraRows 作为额外的标题，
     * 不缺省的话，通过 relatedTo 关联的 formCode 获取到对应的 Search 组件，并进一步获取到查询条件，
     * 然后把查询条件连同 extraRows 一同作为额外的标题，插入到导出的文件中
     */
    this.props.dispatch({
      type: 'search/setRelatedFieldConfigs',
      payload: {
        code: 'KR038',
        extraRows: [`${dateString}${dateType === '0' ? '年' : dateType === '1' ? '月' : '日'}`]
      }
    })
  }

  handleSearch = (value) => {
    this.updateRelatedFieldConfigs()
    const { dateType, dateString } = this.state
    value.rules.push({
      field: 'Parameter2',
      operator: 0,
      value: dateType,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter3',
      operator: 0,
      value: dateString,
      isCustom: true,
      isSysParam: false,
    }) 

    // 搜索动作由 LocalSearch DidMount 之后发起，这时候 refOfTable 还没被赋值，所以需要 setState 之后，再发起 table 的接口请求
    this.setState({ searchParams: value }, () => {
      this.refOfTable && this.refOfTable.loadData(this.state.searchParams)
    })
  }

  handleSize = (searchSize) => {
    !isEqual(searchSize, this.state.searchSize) && this.setState({ searchSize })
  }

  render () {
    const { formId, formCode } = this.props
    const { searchSize,dateType, dateString, } = this.state
    return (
      <>
       <Search
          preventDefaultSearch
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          extraSearch={[
            <FullDatePicker
              dateType={dateType}
              dateString={dateString}
              onlyItem
              onChange={({ dateString, dateType }) => this.setState({ dateString, dateType })}
              options={['0', '1', '3']}
            />
          ]}
          maxShowContentNum={3}
        />
        <EditListTable
          preventDefaultSearch
          formCode={'KR038'}
          data={this.state.searchRules}
          onRef={ref => this.refOfTable = ref}
          style={{ height: `calc(100% - ${searchSize?.fullHeight || 0}px)` }}
        />
      </>
    )
  }
}

export default connect(({ search }) => ({ search }))(KRDosageEnergyClassPage)
