<template>
  <div id="share">
    <van-button type="info" @click="toShare">分享</van-button>
  </div>
</template>

<script>
let wx = require('weixin-js-sdk');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: weixin } = createNamespacedHelpers('weixin');
export default {
  name: 'share',
  props: {},
  components: {},
  data: function() {
    return {
      wx: {},
    };
  },
  created() {
    this.init();
  },
  methods: {
    ...weixin(['jsAuth']),
    async init() {
      console.log(this.$router);
      const { path, query } = this.$route;
      const { openid, ...others } = query;
      let uri = `${path}`;
      const keys = Object.keys(others);
      if (keys.length > 0) {
        const arr = keys.map(key => `${key}=${query[key]}`);
        uri = `${uri}?${arr.join('&')}`;
      }
      const url = `${this.host}${process.env.VUE_APP_ROUTER}${uri}`;
      const res = await this.jsAuth({ url });
      if (this.$checkRes(res)) {
        const { data } = res;
        wx.config({
          debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: data.appid, // 必填，公众号的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的时间戳
          nonceStr: data.noncestr, // 必填，生成签名的随机串
          signature: data.sign, // 必填，签名
          jsApiList: [
            'updateAppMessageShareData', //朋友及QQ
            'updateTimelineShareData', // 朋友圈及QQ空间
          ],
        });
        wx.ready(() => {
          console.log('in ready');
          this.$set(this, 'wx', wx);
        });
        wx.error(res => {
          console.log(res);
        });
      }
    },
    toShare() {
      this.wx.updateAppMessageShareData({
        title: '测试分享',
        desc: '测试',
        // imgUrl:''
        link: 'http://free.waityou24.cn/',
        success: res => {
          console.log('in function:share success');
          console.log(res);
        },
        error: err => {
          alert('share is fail');
          alert(JSON.stringify(err));
        },
      });
    },
  },
  computed: {
    ...mapState(['user', 'menuParams']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
    host() {
      return 'http://broadcast.waityou24.cn';
    },
    authUrl() {
      return `${host}/api/article/auth`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

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