<template>
  <div class="record record--sign"></div>
</template>

<script>
import { Yun } from "./namespace";
import { getYun, newLogin, newRegister } from "../api";
import { setKeyByWay, getKeyByWay } from "../util/index";
import getFingerPrintFunc from "../util/fingerprint";

import Vue from "vue";
export default {
  name: Yun.name,
  data() {
    return {};
  },
  async created() {
    if (this.$route.params.id) {
      //存入send_order_id,并且获取token;
      setKeyByWay("send_order_id", this.$route.params.id);
      let token = getKeyByWay("token");
      //如果不存在token
      if (!token) {
        //生成指纹
        let fingerprint = await getFingerPrintFunc();
        const params = {
          send_order_id: this.$route.params.id,
          fingerprint
        };
        //尝试注册新用户
        const data = await newRegister(params);
        //判断是否老用户老用户直接去看书
        if (data && data.old_user == 1) {
          setKeyByWay("token", data.token);
          setKeyByWay("hashuser", data.hashuser);
          this.getYun();
        } else {
          //不是老用户还要登录
          const loginParams = Object.assign(params, {
            hashuser: data.hashuser
          });
          const { token, hashuser } = await newLogin(loginParams);
          setKeyByWay("token", token);
          setKeyByWay("hashuser", hashuser);
          this.getYun();
        }
      } else {
        this.getYun();
      }
    } else {
      this.$router.replace("/");
    }
  },
  methods: {
    getYun() {
      getYun(this.$route.params.id).then(res => {
        const { bid, cid } = res;
        if (bid === 0) {
          this.$router.replace("/");
        } else {
          this.$router.replace(
            `/reader?yun=1&bid=${bid}&cid=${cid}&send_order_id=${this.$route
              .params.id || 0}`
          );
        }
      });
    }
  }
};
</script>
