<template>
  <div></div>
</template>

<script>
import { CheckBookPreviewIdentityCode } from '@/api/app';
import { setToken, setLocalStore } from '@/utils/auth';
import { updateBaseURL } from '@/utils/http';

export default {
  name: 'EnterPage',
  data() {
    return {
      identityCode: this.$route.query.identity_code || '',
      data: {
        book_id: null,
        access_token: null,
        gcls_sys_session_info: null,
      },
    };
  },
  created() {
    if (process.env.NODE_ENV === 'production') {
      let serverAddress = `${window.location.origin}/`;
      setLocalStore('server_address', serverAddress);
      updateBaseURL(serverAddress);
    }
    this.checkIdentityCode();
  },
  methods: {
    checkIdentityCode() {
      if (!this.identityCode) {
        this.$message.error('缺少身份码参数');
        return;
      }
      CheckBookPreviewIdentityCode({ identity_code: this.identityCode })
        .then((response) => {
          this.data = response;
          setToken(response);
          setLocalStore('book_id', this.data.book_id);
          if (this.isMobile()) {
            this.$router.replace({ name: 'MobileBookPreview' });
          } else {
            if (this.data.preview_type === 1) {
              setLocalStore('task_id', this.data.task_id); // 课程预览需要 task_id
              setLocalStore('courseware_id', this.data.courseware_id);
              this.$router.replace({ name: 'CoursewarePreview' });
              return;
            }
            this.$router.replace({ name: 'BookPreview' });
          }
        })
        .catch(() => {});
    },
    // 判断当前是web端还是手机端
    isMobile() {
      const userAgent = navigator.userAgent || navigator.vendor || window.opera;
      return /android|iphone|ipad|ipod/i.test(userAgent);
    },
  },
};
</script>
