import React, { useEffect } from 'react'
import { useActions, useGetAction } from '@ttk/app-loader'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { closeTabAction, openIframeTabAction } from '@/apps/portal/app-root/action'
import "./style.less"
import MD5 from 'md5.js'

const { Fragment } = React

export default React.memo(Page)
function Page(props) {

  const { history, location } = props
  let { iframeUrl } = props.meta
  let className = classNames({
    'app-iframe': true,
		[props.className]: !!props.className
  })
  const dispatch = useDispatch()

  useEffect(() => {
    const onMessage = (e) => {
      let data
      if (typeof (e.data) == "string") {
        data = JSON.parse(e.data)
      } else {
        data = e.data
      }
      let { iframeUrl, name, method } = data
      switch (method) {
        case 'openNewTab':
          iframeUrl && dispatch(openIframeTabAction(data))
          break;
        case 'closeCurrentTab':
          iframeUrl && dispatch(closeTabAction(null, null, data))
          break;
        default:
          break
      }
    }

    if (window.addEventListener) {
      window.addEventListener('message', onMessage, false)
    } else if (window.attachEvent) {
        window.attachEvent('onmessage', onMessage)
    } else {
        window.onmessage = this.onMessage
    }

    // 返回函数，组件销毁时会自动调用函数以清除监听
    return () => {
      if (window.removeEventListener) {
        window.removeEventListener('message', onMessage, false)
      } else if (window.detachEvent) {
          window.detachEvent('onmessage', this.onMessage)
      } else {
          window.onmessage = undefined
      }
    }
  })

  return (
    <Fragment>
      { iframeUrl && <iframe className={className} src={iframeUrl} width="100%" height="300px"></iframe> }
    </Fragment>
  )
}


