<template>
  <div
    id="wxqrcode"
    ref="wxqrcode"
    class="es-wx-qrcode"
    :style="{ width: mwidth, height: mheight }"
  >
    <iframe
      v-if="src && mwidth && mheight"
      frameborder="0"
      allowTransparency="true"
      scrolling="no"
      :width="mwidth"
      :height="mheight"
      :src="src"
    ></iframe>
  </div>
</template>
<script>
import util from 'eoss-ui/src/utils/util.js';
import qs from 'qs';
export default {
  name: 'EsWxlogin',
  inheritAttrs: false,
  inject: {},
  props: {
    self_redirect: {
      type: Boolean,
      default: false
    },
    appid: {
      //required: true,
      type: String
    },
    scope: {
      default: 'snsapi_login',
      type: [String, Array]
    },
    redirect_uri: {
      //required: true,
      type: String
    },
    state: String,
    color: {
      type: String,
      validator: (value) => {
        return ['black', 'white'].includes(value);
      }
    },
    href: String,
    lang: {
      type: String,
      validator: (value) => {
        return ['en', 'cn'].includes(value);
      }
    },
    width: {
      type: String,
      default: '300px'
    },
    height: {
      type: String,
      default: '300px'
    },
    auto: Boolean,
    param: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      src: '',
      mwidth: 0,
      mheight: 0
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    if (this.auto) {
      let parent = this.$refs.wxqrcode.parentNode;
      let h =
        parent.offsetHeight -
        parseInt(util.getStyle(parent, 'padding-top'), 10) -
        parseInt(util.getStyle(parent, 'padding-bottom'), 10);
      if (h > 0) {
        this.mwidth = h + 'px';
        this.mheight = h + 'px';
      }
    } else {
      this.mwidth = this.width;
      this.mheight = this.height;
    }
    this.wxLogin();
  },
  methods: {
    wxLogin() {
      let option = util.extend(
        {},
        {
          styletype: '',
          sizetype: '',
          bgcolor: '',
          rst: ''
        },
        this.param,
        {
          self_redirect: this.self_redirect,
          appid: this.appid,
          scope: this.scope,
          redirect_uri: encodeURI(this.redirect_uri),
          state: this.state,
          style: this.color,
          href: this.href,
          lang: this.lang
        }
      );
      this.src =
        'https://open.weixin.qq.com/connect/qrconnect?login_type=jssdk&' +
        qs.stringify(option, { skipNulls: true });
    }
  }
};
</script>
