import { computed, ref } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter, LocationQuery } from "vue-router";
import { Howl } from "howler";
import * as API from "@/api";
import store from "@/store";

/** 用户通过微信code登陆 */
export const useLogin = async (query: LocationQuery) => {
  //登陆
  const res = await API.login(query.code);
  store.commit("setToken", res.data.token);
  store.commit("setUserData", res.data.wxUserInfo);
  //获取用户信息
  const userDataRes = await API.userInfo();
  store.commit("setUserData", {
    ...store.getters.getUserData,
    expireTime: userDataRes.data.data.expireTime,
  });
};

/**
 * 获取用户会员到期时间
 */
export const useExpireTime = () => {
  const store = useStore();
  const expireTime = computed(() => store.getters.getUserData.expireTime);
  return {
    expireTime,
  };
};

/** 判断是不是zhangbing的openapi */
export const useOpenIdIsZhangbing = () => {
  const store = useStore();
  const openid = computed(() => store.getters.getUserData.openid);
  const userOpenidArr = [
    "ovKTX50v7OAEPI_ERofpUvrNQCJU",
    "ovKTX5-FKLF6_sgTtCIXpG_lz3PY",
    "ovKTX5zYvp9OXE43ADwLa1RHna0g",
  ];
  const isZhangbing = userOpenidArr.includes(openid.value);
  return {
    isZhangbing,
  };
};

export const useSound = (videoSrc: string) => {
  const sound = new Howl({
    autoplay: true,
    src: videoSrc,
  });

  return sound.unload;
};

/**
 * 路由转发汇总class模式书写,需要注意this指向
 * @returns
 */
export class RouterBus {
  router;
  route;
  constructor() {
    this.router = useRouter();
    this.route = useRoute();
  }
  /**
   * 会员购买页
   */
  goBuyVip = () => {
    this.router.push("/buyVip");
  };
  /**
   * 分成提现页
   */
  goCashOut = () => {
    this.router.push("/cashOut");
  };
  /**
   * 我的下级页
   */
  goMyBranch = () => {
    this.router.push("/myBranch");
  };
  /**
   * 模拟考试页
   */
  goMockTest = () => {
    this.router.push({ path: "/mockTest", query: this.route.query });
  };
  /** 错题重阅 */
  goWrongReview = (ids: number | number[]) => {
    this.router.push({
      path: "/wrongReview",
      query: { ...this.route.query, wrongIds: ids },
    });
  };
}
