// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Tabs } from 'antd'
import { RenderPageItem } from '../FormPage'
// 工具库
import { initFilter } from '../../utils/common'
// 样式
import classNames from 'classnames'
import styles from './combinationPage.css'

const TabPane = Tabs.TabPane
class CombinationPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      tables: [],
      tableData: {},
      activeKey: null
    }
  }

  componentDidMount () {
    // 获取组合表单配置
    const { formCode, login, dispatch } = this.props
    const { OrgId } = login
    const json = initFilter(OrgId, formCode)

    dispatch({
      type: 'listPage/getTablePageTables',
      payload: json
    }).then(res => {
      if (res && Array.isArray(res.Nav_Tables) && res.Nav_Tables.length) {
        const tables = []
        // 菜单参数
        const { currActivatedMenu } = this.props.app || {}
        const menuFormParameter = currActivatedMenu?.MENU_FORM_PARAMS
        res.Nav_Tables.forEach(item => {
          let isShow = !item.TABLE_CONDITION
          if (!isShow) {
            // 列表配置条件
            const conditionsOr = item.TABLE_CONDITION.split('|')
            const conditionsAnd = item.TABLE_CONDITION.split('&')
            if (conditionsOr.length === 1 && conditionsAnd.length === 1) {
              // 条件直接命中菜单参数，则直接显示
              if (item.TABLE_CONDITION === menuFormParameter) {
                isShow = true
              }
            } else if (conditionsOr.length > 1) {
              // 或条件
              for (let conditionOr of conditionsOr) {
                // 条件直接命中菜单参数，则直接显示
                if (conditionOr === menuFormParameter) {
                  isShow = true
                  break
                }
              }
            } else if (conditionsAnd.length > 1) {
              // 与条件
              const showResults = []
              for (let conditionAnd of conditionsAnd) {
                // 条件直接命中菜单参数，则直接显示
                if (conditionAnd === menuFormParameter) {
                  showResults.push(true)
                }
              }
              isShow = showResults.length === conditionsAnd.length
            }
          }
          isShow && tables.push(item)
        })
        tables.length && this.setState({ tables }, () => {
          this.getTableData(tables[0].ID)
        })
      }
    })
  }


  /**
   * 根据 tab key 获取对应的 table 数据
   * @param {*} paneKey
   */
  getTableData = paneKey => {
    const { tableData } = this.state
    // 加载过的数据做一个缓存
    !tableData[paneKey] && this.fetch(paneKey)
    // 设置激活tab
    this.setState({ activeKey: paneKey })
  }

  /**
   * 获取数据
   * @param {*} paneKey
   */
  fetch = paneKey => {
    const { tables, tableData } = this.state
    const { login, dispatch } = this.props

    const targetTable = tables.find(item => item.ID === paneKey)
    const formCode = targetTable.CODE

    dispatch({
      type: 'app/getFormByRedis',
      payload: { 'Key': formCode, 'orgid': login.OrgId },
      onComplete: (ret) => {
        if (ret) {
          this.setState({
            tableData: {
              ...tableData,
              [paneKey]: ret
            }
          })
        }
      }
    })
  }

  renderTabBar = () => {
    const { tables, activeKey } = this.state
    if (tables.length <= 1) return <div />
    return (
      <div className={styles.tabBar__wrap}>
        {
          tables.map(item => {
            return (
              <div
                key={`${item.ID}--customTabBar`}
                onClick={() => this.getTableData(item.ID)}
                className={classNames(styles.tabBar__tab, { [styles.activated]: item.ID === activeKey })}>
                {item.LABEL_NAME}
              </div>
            )
          })
        }
      </div>
    )
  }

  render () {
    const { tables, tableData, activeKey } = this.state
    return (
      <Tabs
        activeKey={activeKey}
        renderTabBar={this.renderTabBar}
        animated={false}
        className='combination-page__mainTab'>
        {
          tables.map(item => {
            return (
              <TabPane tab={item.LABEL_NAME} key={item.ID}>
                <div className={styles.mainTabContent}>
                  <RenderPageItem
                    props={this.props}
                    state={{ formData: tableData[item.ID] }}
                  />
                </div>
              </TabPane>
            )
          })
        }
      </Tabs>
    )
  }
}

export default connect(({ app, loading, listPage, login }) => ({ app, loading, listPage, login }))(CombinationPage)