import { loginByPhone } from "@/api/user";
import { isWeixinBrower } from "@/service/validation";
import { mapState, mapActions } from "vuex";
import localStorage from "@/service/localStorage";

export default {
  computed: {
    ...mapState(["isShowLogin"])
  },
  watch: {
    isShowLogin(val) {
      if (!val && localStorage.get("mongoToken")) {
        this.nextStep();
      }
    }
  },
  methods: {
    ...mapActions(["setIsShowLogin"]),
    ...mapActions("user", ["setUserInfo"]),
    showLoginPopup() {
      if (localStorage.get("mongoToken")) {
        this.setUserInfo();
        this.nextStep();
      } else {
        this.setIsShowLogin(true);
      }
    },
    async login(phoneNo, verifyCode) {
      if (localStorage.get("mongoToken")) {
        return new Promise(resolve => {
          resolve();
        });
      }
      let formData = {
        loginChannel: isWeixinBrower ? 1 : 2,
        openId: localStorage.get("openId") || null,
        phoneNo,
        verifyCode
      };
      const res = await loginByPhone(formData);
      if (res) {
        this.setUserInfo();
        this.$notify({ type: "success", message: "登录成功" });
        localStorage.set("mongoToken", res.token);
        // TODO 开发目前使用这个token
        // localStorage.set("mongoToken", "6ae7da7dd4c543f1a36c702c6f419f12");
      }
      return new Promise(resolve => {
        resolve();
      });
    }
  }
};
