<template>
  <el-dialog
    :title="'绑定公众号'"
    :visible.sync="visible"
    width="400px"
    center
    class="chooseDialog"
    :before-close="close"
  >
    <div
      v-loading="loading"
      class="qrcode"
    >
      <el-image
        style="width: 200px; height: 200px"
        :src="url"
      />
      <p>请使用微信扫码进行绑定</p>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('ec.table.cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { bindWechat, createWechatQrcode } from 'ecip-web/api/vue/user/sysrUserApi'
import { guid } from 'ecip-web/utils/tableUtil'

let qrocodeValid
let userId
export default {
  name: 'WechatCode',
  data() {
    return {
      visible: false,
      loading: false,
      saveLoading: false,
      url: '',
      wechatAuthId: '',
    }
  },
  methods: {
    init(id) {
      userId = id
      this.url = ''
      this.visible = true
      this.$nextTick(async() => {
        this.loading = true
        this.wechatAuthId = guid()
        if (qrocodeValid) {
          clearInterval(qrocodeValid)
        }
        const { data } = await createWechatQrcode({ authId: this.wechatAuthId })
        this.url = data.qrcode
        this.validate(this.wechatAuthId)
        this.loading = false
      })
    },
    validate(authId) {
      // validateAuthId(authId);
      qrocodeValid = setInterval(() => {
        if (!this.visible) {
          this.close()
        }
        this.validateAuthId(authId)
      }, 3000)
    },
    async validateAuthId(authId) {
      const res = await bindWechat({ authId, userId })
      if (!res.success) {
        console.log(res)
        return
      }
      if (res.data === '0') {
        return
      }
      if (res.data === '1') {
        this.$notify.success('绑定成功')
      } else {
        this.$notify.success('该微信已经绑定了账号：' + res.data)
      }
      clearInterval(qrocodeValid)
      this.$emit('close')
      this.visible = false
    },
    close() {
      if (qrocodeValid) {
        clearInterval(qrocodeValid)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.qrcode {
  text-align: center;
  &.el-image {
    width: 200px;
    height: 200px;
   }
}
</style>
