import request from "../request";
import * as API from "@/api";
import store from "@/store";
import { Toast } from "vant";
import router from "@/route";

declare let WeixinJSBridge: any;

interface PayConfig {
  appId: string;
  timeStamp: string;
  nonceStr: string;
  package: string;
  signType: string;
  paySign: string;
}

function onBridgeReady(payConfig: PayConfig) {
  WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    payConfig,
    async function (res: any) {
      if (res.err_msg == "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        let userDataRes = await API.userInfo();
        store.commit("setUserData", {
          ...store.getters.getUserData,
          expireTime: userDataRes.data.data.expireTime,
        });
        Toast.success("支付成功");
        router.push("/home/test");
      }
    }
  );
}

/**
 * 获取支付配置，并调起微信支付
 */
export async function prepareOrder(dictCode: number) {
  let res = await request({
    url: "/student/wx/prepareOrder",
    method: "post",
    data: {
      dictCode,
    },
  });

  if (res.data.code === 200) {
    if (typeof WeixinJSBridge !== "undefined") {
      onBridgeReady(res.data.data);
    }
  }
}

/**
 * 循环支付，并调起微信支付
 */
export async function loopPrepareOrder() {
  let res = await request({
    url: "/student/wx/prepareOrder-test",
    method: "post",
  });

  if (res.data.code === 200) {
    if (typeof WeixinJSBridge !== "undefined") {
      onBridgeReady(res.data.data);
    }
  }
}

/**
 * 获取vip价格字典
 * @returns
 */
export async function getVipPrice() {
  const res = await request({
    url: `/system/dict/data/type/vip_type_price`,
  });

  return res.data;
}
