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

export default {
  async onLaunch(options) {
    console.log('options: ', options);
    /* #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 || !options.query.u) {
        // 参数里没有u (userId)提示
        this.$t.ui.showToast('缺少用户信息参数');
      } else {
        await this.getToken(options.query.u);
      }
    }
    // FIXME: 这里重复书写的
    this.initSocket();
    /* #endif */
  },
  onShow: function () {
    console.log('App Show');
  },
  onHide: function () {
    console.log('App Hide');
  },

  computed: mapState('user', ['token']),

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

    async signin() {
      try {
        const data = await this.$u.api.signin();
        if (data && data.token) {
          this.setUser(data);
          this.setToken(data.token);
        } else {
          throw '登录失败';
        }
      } catch (error) {
        console.error('error: ', error);
        this.$t.ui.showToast(error || '登录失败');
      }
    },
  },
};
</script>

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