import React, { useEffect, useCallback, useState } from 'react'
import { Button, message, Input } from 'antd'
import { openTab } from '@/apps/portal/app-layout/action'
import { useData, useActions } from '@ttk/app-loader'
import { useDispatch } from 'react-redux'
import AppIframe from '@/apps/portal/app-iframe/app'
// import { openIframeTab } from '@/apps/portal/app-iframe/action'
import "./style.less"

export default React.memo(Page)
function Page(props) {
  const { history, location } = props
  const dispatch = useDispatch()
  
  const [value, setValue] = useState('')

  useEffect(() => {
    const onMessage = (e) => {
      let msg
      if (typeof (e.data) == "string") {
        msg = JSON.parse(e.data)
      } else {
        msg = e.data
      }
      let { method, body } = msg
      switch (method) {
        case 'senMsgToTop':
          message.info(`收到来自子iframe的信息：${body}`)
          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
      }
    }
  })
  
  const onSend = useCallback(() => {
    iterationFrames(window.frames);
    function iterationFrames (frames, data) {
      if (frames) {
        for (let i = 0; i < frames.length; i++) {
          frames[i].postMessage({
            method: "senMsgToChild",
            body: value
          }, "*");
          if (frames[i].frames) {
            iterationFrames(frames[i].frames, data);
          }
        }
      }
    }
  }, [value])

  const onChange = useCallback((e) => {
    setValue(e.target.value)
  })

  return (
    <div style={{padding: "20px", height: "100%"}}>
      <p>
        <Input className="iframe-input" value={value} onChange={(e) => onChange(e)}/>
        <Button type="primary" onClick={(e) => onSend()}>向子窗口发送信息</Button>
      </p>
      <p className="iframe-tips">iframe子窗口</p>
      <AppIframe className='open-tab-in-iframe' {...props}/>
    </div>
  )
}


