<template>
  <div id="bind">
    <el-dialog title="绑定微信" :visible.sync="dialog" width="40%" center :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <el-row>
        <slot></slot>
        <el-col :span="24" style="text-align:center">
          <qrcode :qrcode="qrcode" @toReturn="toReturn"></qrcode>
        </el-col>
        <slot name="footer"></slot>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
const jwt = require('jsonwebtoken');
import { mapActions, mapState, mapMutations } from 'vuex';
import qrcode from '@/components/qrcode.vue';
export default {
  name: 'bind',
  props: {
    display: { type: Boolean },
    mobile: null,
  },
  components: {
    qrcode,
  },
  data: () => ({
    dialog: false,
    qrcode: '',
  }),
  watch: {
    display: {
      handler(val) {
        this.$set(this, `dialog`, val);
      },
    },
  },
  created() {
    this.initQrcode();
  },
  mounted() {},
  computed: {
    ...mapState(['user']),
  },
  methods: {
    ...mapMutations(['setUser']),
    ...mapActions(['createConnection', 'getWxtoken', 'bindOperation', 'userOperation']),
    async initQrcode() {
      let result = await this.createConnection();
      this.$set(this, `qrcode`, result);
    },
    async toReturn(msg) {
      let result = await this.getWxtoken(this.qrcode);
      this.toBind(result);
    },
    async toBind(wxtoken) {
      let object = { corpid: this.user.corpid, wxtoken: wxtoken };
      if (!this.mobile) {
        //是默认绑定
        console.log('first login');
        object['mobile'] = this.user.sub;
      } else {
        //hr绑定
        console.log('hr');
        object['mobile'] = this.mobile;
      }
      let result = await this.bindOperation({ data: object });
      if (`${result.errcode}` === '0') {
        this.$message.success('操作成功');
        if (!this.mobile) this.wxLogin(wxtoken);
        else this.$emit(`close`, 'bind');
      } else {
        this.$message.error(result.errmsg);
      }
    },
    async wxLogin(wxtoken) {
      let result = await this.userOperation({ type: 'login', data: { loginType: '1', info: { wxtoken: wxtoken } } });
      if (`${result.errcode}` === '0') {
        let info = jwt.decode(result.data);
        sessionStorage.setItem('user', JSON.stringify(info));
        this.setUser(info);
        window.location.href = `${window.location.href}`;
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
