<template>
  <view>
    <view v-if="token">
      <slot></slot>
    </view>
    <view v-else>
      <button
        :open-type="type || 'getPhoneNumber'"
        @getphonenumber="getPhoneNumber"
        @click="navLogin"
        plain
      >
        <view class="stop-event"></view>
        <slot></slot>
      </button>
    </view>
  </view>
</template>
<script>
import { saveUserInfo } from "../../commom/apis.js";
import {
  getUserToken,
  navLoginH5,
  openPhoneLogin,
  loopCacheInvitationCode,
  profile,
} from "../../js/request.js";

/**
 * 推荐设置成全局组件
 * 1.已经登陆只显示插槽内容
 * 2.未登陆先获取手机号登陆，登陆完成全局刷新组件
 * 3.检测登陆用token方式
 * 4.仅支持一健登陆
 * 5.H5环境按照跳转h5页面登陆
 * 6.强制绑定小程序openId
 */
export default {
  data() {
    return {};
  },
  props: {
    type: String,
    code: String,
  },
  computed: {
    invitationCode() {
      if (this.code) return this.code;
      return loopCacheInvitationCode();
    },
    token: {
      get() {
        return this.$store.state.userToken || getUserToken();
      },
      set(val) {
        this.$store.state.userToken = val;
      },
    },
  },
  methods: {
    async getPhoneNumber(e) {
      const msg = e.detail.errMsg;
      if (msg === "getPhoneNumber:ok") {
        const data = e.detail;
        const invitationCode = this.invitationCode;
        const token = await openPhoneLogin(data, {
          invitationCode,
        });
        // 更新用户登陆状态
        this.token = token;
        this.$api.msg("登录成功");
        this.$emit("success", token);
        await this.cacheUserInfo();
      } else {
        this.$api.msg(`获取手机号失败:${msg}`);
      }
    },
    async cacheUserInfo() {
      const info = await profile();
      saveUserInfo(info);
    },
    navLogin() {
      this.$emit("login-click");
      // #ifdef H5
      navLoginH5();
      // #endif
    },
  },
};
</script>

<style lang="scss" scoped>
button {
  background: transparent;
  height: auto;
  line-height: inherit;
  width: auto;
  margin: 0;
  padding: 0;
  text-align: left;
  border: 0;
}

button::after {
  border: 0;
}

.stop-event {
  position: absolute;
  top: 0;
  height: 100%;
  width: 100%;
  left: 0;
  z-index: 9999;
}
</style>
