import React, { useCallback, useState, useEffect } from 'react'
import { Button, Input, message } from 'antd'
import "./style.less"

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

  const [value, setValue] = useState('')

  const onOpen = useCallback(() => {
    window.top.postMessage({
			method: "openNewTab",
			name: "打开我",
			iframeUrl: "https://es6.ruanyifeng.com"
		}, "*")
  }, [])

  const onClose = useCallback(() => {
    window.top.postMessage({
			method: "closeCurrentTab",
			name: "打开我",
			iframeUrl: "https://es6.ruanyifeng.com"
		}, "*")
  }, [])

  const onSend = useCallback(() => {
    window.top.postMessage({
      method: "senMsgToTop",
      body: value
		}, "*")
  }, [value])

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

  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 'senMsgToChild':
          message.info(`收到来自父级窗口信息：${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
      }
    }
  })

  return (
    <div style={{padding: "20px"}}>
      <p><Button type="primary" onClick={() => onOpen()}>点我打开新窗口</Button></p>
      <p><Button type="primary" onClick={() => onClose()}>点我关闭新窗口</Button></p>
      <p>
        <Input className="iframe-input" value={value} onChange={(e) => onChange(e)}/>
        <Button type="primary" onClick={() => onSend()}>向父窗口发送信息</Button>
      </p>
    </div>
  )
}


 