import React from 'react'
import { connect } from 'dva'
import { Result, Tabs, Icon } from 'antd'
import { IFComponent } from '@woowalker/feui'
import { initFilter } from '../../../utils/common'
import { $consts } from '../../../plugins'
import config from "../../../config.js"
import classNames from 'classnames'
import styles from '../../Combination/combinationPage.css'

const { TabPane } = Tabs

class BDPowerCabinetHmiPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      activeKey: null,
      hmi: []
    }
  }

  componentDidMount () {
    this.getCabinetHmi()
  }

  componentDidUpdate (prevProps, prevState) {
    prevState.activeKey !== this.state.activeKey && this.checkInActiveIframes()
  }

  getCabinetHmi = () => {
    const { formCode, dispatch, login, data } = this.props
    const { OrgId: ORG_ID } = login
    const treeSelect = data.TreeSelected.join(',')
    const json = initFilter(ORG_ID, treeSelect, formCode, 0, 1)
    dispatch({
      type: 'app/getDataByPost',
      url: 'BD/BDPowerCabinet/GetHmiByNode',
      payload: json
    }).then(ret => {
      if (ret) {
        this.setState({
          hmi: ret,
          activeKey: ret[0]?.ID
        })
      }
    })
  }

  checkInActiveIframes = () => {
    const { activeKey, hmi } = this.state
    const inActiveIframes = hmi.filter(item => item.ID !== activeKey)
    inActiveIframes.forEach(({ ID }) => {
      const iframe = document.getElementById(`iframe_${ID}`)
      this.postMsg(iframe, $consts['HMI/EVENT_PREVENT_REQUEST'])
    })
    const activeIframe = hmi.find(item => item.ID === activeKey)
    this.postMsg(activeIframe, $consts['HMI/EVENT_CONTINUE_REQUEST'])
  }

  postMsg = (iframe, type) => {
    iframe && iframe.contentWindow && iframe.contentWindow.postMessage({ type }, '*')
  }

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

  render () {
    const { activeKey, hmi } = this.state
    const loading = this.props.loading.effects['app/getDataByPost']

    if (!hmi.length) {
      return (
        <IFComponent
          IF={loading}
          ELSE={
            <div style={{ width: '100%', height: '100%', textAlign: 'center', backgroundColor: 'white' }}>
              <img className={styles.img} src={require('../../../assets/no-hmi.png')} alt='无HMI' />
            </div>
          }
        >
          <Result
            icon={<Icon type='loading' />}
            title='数据加载中，请稍后...'
          />
        </IFComponent>
      )
    }

    return (
      <Tabs
        activeKey={activeKey}
        animated={false}
        renderTabBar={this.renderTabBar}
        className='combination-page__mainTab'
      >
        {
          hmi.map(item => {
            const url = `${config.hmiUrl}preview?code=${item.ID}&sysCode=optiEnergy&hideTool=true`
            return (
              <TabPane tab={item.NAME} key={item.ID}>
                <iframe
                  id={`iframe_${item.ID}`}
                  style={{ width: '100%', height: '100%', border: 'none' }}
                  title='hmi'
                  src={url}
                />
              </TabPane>
            )
          })
        }
      </Tabs>
    )
  }
}

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