<template>
  <div id="XReportView">
    <a-spin tip="Loading..." :spinning="!(configName || localConfig)">
      <XReport
        v-if="configName || localConfig"
        :config-name="configName"
        :config-data="configData"
        :localConfig="localConfig"
        @saveConfig="saveConfig"/>
    </a-spin>
  </div>
</template>

<script>
import XReport from '@vue2-client/base-client/components/common/XReport'

export default {
  name: 'XReportView',
  components: {
    XReport
  },
  data () {
    return {
      localConfig: undefined,
      configName: '',
      configData: {}
    }
  },
  // 作为 iframe 嵌入时 初始化时 监听 iframe 事件
  created () {
    // 增加监听
    window.addEventListener('message', this.receiveMessage, false)
    // 向上级发送事件
    window.parent.postMessage('calParentSend', '*')
  },
  methods: {
    saveConfig (config) {
      window.parent.postMessage({
        type: 'saveConfig',
        config
      }, '*')
    },
    // 接收 iframe 传递的数据
    receiveMessage (event) {
      try {
        if (event.data && typeof event.data === 'object' && event.data.type === 'setConfig') {
          this.localConfig = event.data.localConfig
          this.configName = event.data.configName
          this.configData = event.data.configData
        }
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>
<style scoped>
#XReportView {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
