<template>
  <div>
    <!-- 微信页面授权回调:用户首次进入时判断当前用户所在环境：微信公众号和微信小程序 -->
    微信页面授权回调:用户首次进入时判断当前用户所在环境：微信公众号和微信小程序
  </div>
</template>
<script>
import { getUrlParams } from '@/utils/index';
import { WxJsOpenId } from '@/utils/login';

export default {
  created() {
    console.log(12121212);
    this.getCode();
  },
  mounted() {
    console.log(17171717171717);
  },
  methods: {
    getCode() {
      const code = getUrlParams()?.code; // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      console.log(17);
      const local = window.location.href;
      if (code == null || code === '') {
        console.log(120);
        window.location.href =
          'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
          //   window.APPID +
          `wx907c27f16841a919` +
          '&redirect_uri=' +
          encodeURIComponent(local) +
          '&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
      } else {
        this.getOpenId(code); //把code传给后台获取用户信息
      }
    },
    async getOpenId(code) {
      // 通过code获取 openId等用户信息，/api/user/wechat/login 为后台接口
      let _this = this;

      // ?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
      const res = await WxJsOpenId({
        appid: 'wx907c27f16841a919',
        secret: 'd9c81d6c47f7de322a2ff85847de6728',
        code,
        grant_type: 'authorization_code',
      });
      console.log(4848484848, res);
      //   this.$http
      //     .post('/api/user/wechat/login', { code: code })
      //     .then((res) => {
      //       let datas = res.data;
      //       if (datas.code === 0) {
      //         console.log('成功');
      //       }
      //     })
      //     .catch((error) => {
      //       console.log(error);
      //     });
    },
  },
};
</script>
