import { setLotteryAddress } from '@/api/modules/records'

export default {
  data() {
    return {
      connection: null,
      timer: null
    }
  },
  computed: {
    isInIframe() {
      return process.client ? window.self !== window.top : false
    }
  },
  mounted() {
    this.connectionInit()
  },
  methods: {
    connectionInit() {
      if (process.client && this.isInIframe && !this.connection) {
        const { ClientConnection } = require('@easy-messenger/client-connection/dist/clientConnection.cjs.js')
        this.connection = new ClientConnection()
        let counter = 0
        this.timer = setInterval(() => {
          this.connection.init()
          counter++
          if (this.connection.connected || counter > 60) {
            clearInterval(this.timer)
            this.connectionListener()
          }
        }, 1000)
      }
    },
    connectionListener() {
      this.connection.on('onSaveLotteryAddress', addressInfo => {
        const params = {
          id: this.winInfo.id,
          tempId: this.winInfo?.tempId || '',
          uin: this.$route?.query?.uin || '',
          address: `${addressInfo?.province || ''}-${addressInfo?.city || ''}-${addressInfo?.area || ''}-${
            addressInfo?.detail
          }`,
          contactPhone: addressInfo?.mobile || '',
          name: addressInfo?.name || ''
        }
        setLotteryAddress(params).then(res => {
          const { code, errorCode, errorMessage } = res
          if (code === 200 && errorCode === 0) {
            this.$toast({
              message: '保存成功，具体详情请前往个人中心查看',
              duration: 3000,
              onClose: () => {
                this.connection.emit('onClose', { type: 'lottery' })
              }
            })
          } else {
            this.$toast(errorMessage)
          }
        })
      })
    },
    connectionEmit(type, data){
      this.connection.emit(type, data)
    }
  }
}
