import React from 'react'
import { connect } from 'dva'
import { Empty } from 'antd'
import { IFComponent } from '@woowalker/feui'
import DataLoading from '../../common/DataLoading'
import config from '../../../config.js'
import { getRequestHeaders } from '../../../utils/request'
import storage from '../../../utils/storage'
class BDWordPreviewPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      loading: false,
      recordId: '',
      hmiID: '',
      dataApi: ''
    }
  }

  componentWillMount () {
    const { recordId, templateCode, login, dispatch } = this.props
    if (templateCode) {
      this.setState({ loading: true })
      dispatch({
        type: 'app/getDataByPost',
        url: 'BD/BDWordTemplate/GetTemplate',
        payload: {
          keyword: templateCode,
          OrgId: login.OrgId
        }
      }).then(res => {
        if (res) {
          this.setState({
            recordId,
            hmiID: res.ID,
            dataApi: res.DATA_API
          })
        }
      }).finally(() => {
        this.setState({ loading: false })
      })
    }
  }

  postMsg = (type) => {
    const headers = getRequestHeaders('BD/BDWordTemplate/GetTemplate')
    const iframe = document.getElementById(this.state.recordId)
    iframe && iframe.contentWindow.postMessage({ type, data: headers }, '*')
  }

  render () {
    const { loading, recordId, hmiID, dataApi } = this.state
    const tenant = storage('lacal').getItem('Tenant').val
    const orgId = storage('lacal').getItem('webOrgId').val
    return (
      <div className='full_height' style={{ overflow: 'hidden' }}>
        <IFComponent
          IF={!!(hmiID && recordId)}
          ELSE={
            <IFComponent IF={loading} ELSE={<Empty />}>
              <DataLoading style={{ height: 300 }} />
            </IFComponent>
          }
        >
          <iframe
            id={recordId}
            onLoad={() => this.postMsg('event_set_request_header')}
            style={{ width: '100%', height: '100%', border: 'none' }}
            title='word'
            src={`${config.hmiUrl}a4-preview?code=${hmiID}&recordId=${recordId}&dataApi=${dataApi}&sysCode=optiEnergy&tenant=${tenant}&orgId=${orgId}`}
          />
        </IFComponent>
      </div>
    )
  }
}

export default connect(({ login }) => ({ login }))(BDWordPreviewPage)