<script>
import { mapActions, mapMutations, mapState, mapGetters } from 'vuex';

export default {
  async onLaunch(options) {
    this.checkNetwork(); // 监听网络状态

    /* #ifdef MP-WEIXIN */
    await this.signin();
    this.initSocket();
    /* #endif */

    /* #ifdef H5 */
    options.query.url && (this.$t.domain = options.query.url);
    if (!this.token) {
      // 不论有没有token都直接从userId获取token
      // token有过期时间 从本地获取可能是过期 干脆直接从userId获取
      if (!options.query.share) {
        if (!options.query || !options.query.u) {
          // 参数里没有u (userId)提示
          this.$t.ui.showToast('缺少用户信息参数');
        } else {
          const data = await this.getToken(options.query.u);
          this.noPhone(data.phone);
        }
      }
    }
    // FIXME: 这里重复书写的
    this.initSocket();
    /* #endif */
  },

  computed: {
    ...mapGetters(['useStorage']),
    ...mapState('user', ['token']),
  },

  methods: {
    ...mapActions('user', ['getToken']),
    ...mapActions('socket', ['initSocket']),
    ...mapMutations(['setNetworkConnected']),
    ...mapMutations('user', ['setToken', 'setUser']),

    // 检查网络状态 设置store里的网络状态变量
    // 网络连接 且 不是2g 不是3g 才算是网络连接; 否则不是 将启用本地存储
    checkNetwork() {
      uni.getNetworkType({
        success: ({ networkType }) => {
          this.setNetworkConnected(!(networkType === 'none' || networkType === '2g' || networkType === '3g'));
        },
      });
      // 监听网络状态的变化
      uni.onNetworkStatusChange(({ isConnected, networkType }) => {
        this.setNetworkConnected(isConnected && !(networkType === '2g' || networkType === '3g'));
      });
    },

    // 登录
    async signin() {
      try {
        const data = await this.$u.api.signin();
        if (data && data.token) {
          this.setUser(data);
          this.setToken(data.token);
          this.noPhone(data.phone);
        } else {
          this.$t.ui.showToast('返回数据异常');
        }
      } catch (error) {
        console.error('error: ', error);
        this.$t.ui.showToast(error || '登录失败');
      }
    },

    /**
     * 没有手机号 跳转绑定手机号的界面
     * @param {string} phone
     */
    async noPhone(phone) {
      if (!phone) {
        this.$u.route('/pages/phone-bind/phone-bind');
      }
    },
  },
};
</script>

<style lang="scss">
@import './common/styles/iconfont.scss';
@import 'uview-ui/index.scss';
@import './common/styles/app.scss';
</style>
