<template>
  <div id="recall">
    <!-- 点击下载提示 -->
    <DownLoadInfo @onShowControl="onShowControl"></DownLoadInfo>

    <!-- safari添加到桌面提示 -->
    <SafariTips v-if="showSafariTips" @onShowControl="onShowControl" />

    <!-- 退出页面提示 -->
    <ExitGame></ExitGame>

    <!-- 页面悬浮球 -->
    <Float @openInnerBox="openInnerBox"></Float>

    <!-- 游戏iframe -->
    <GameIframe></GameIframe>

    <!-- 已登录 -->
    <InnerBox v-show="isLogin && showInnerBox"></InnerBox>

    <!-- 未 显示登录框 -->
    <UdbBox v-if="!isLogin"></UdbBox>
  </div>
</template>

<script>
import { recallConfig } from "../../config";
import { mapState, mapActions } from "vuex";
import DownLoadInfo from "@/components/Inner/DownLoadInfo"; // 点击下载到桌面提示
import ExitGame from "@/components/Inner/ExitGame.vue"; // 退出页面提示
import Float from "@/components/Inner/Float"; // 页面悬浮球
import GameIframe from "@/components/Inner/GameIframe"; // 游戏iframe
import InnerBox from "@/components/Inner/InnerBox"; // 已登录显示的内容
import UdbBox from "@/components/UDB/UdbBox"; // 登录框
import SafariTips from "@/components/Inner/SafariTips"; // safari添加到桌面提示
export default {
  name: "Recall",
  components: {
    DownLoadInfo,
    ExitGame,
    Float,
    GameIframe,
    InnerBox,
    UdbBox,
    SafariTips,
  },
  data() {
    return {
      queryTimeout: null, // 订单查询 定时器
      wechatAppid: "wx2c4f9f89c572aeb5", // 公众号appid
      showSafariTips: false, // 显示safari组件
    };
  },
  provide() {
    return {
      // 校验返回值
      checkCode: this.checkCode,
      // 支付校验返回值
      checkCodeHandler: this.checkCodeHandler,
      // 刷新登录态
      refresh: this.refresh,
      // 获取用户信息
      getUserInfo: this.getUserInfo,
      // 获取鸿币余额
      getFinance: this.getFinance,
      // 支付
      payHandler: this.payHandler,
      // 订单查询
      queryOrder: this.queryOrder,
      // 微信内支付
      wechatPay: this.wechatPay,
      // 获取微信code
      getWechatCode: this.getWechatCode,
    };
  },
  computed: {
    ...mapState(["CONFIG", "isLogin", "showInnerBox", "isPay", "query","appid"]),
    userInfo() {
      return this.$store.state.userInfo;
    },
  },
  watch: {
    // ios url带token 直接登录进去
    userInfo: {
      handler(newValue) {
        if (newValue) {
          const token = this.$utils.getQueryString("token");
          if (token) {
            window.location.href = this.$utils.delQueStr(
              window.location.href,
              "token"
            );
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // 携带token 直接登录
    const token = this.$utils.getQueryString("token");
    if (token) {
      localStorage.setItem("x-token", token);
    }
  },
  mounted() {
    clearTimeout(this.queryTimeout);

    // 设置页面基础配置信息
    this.setConfigAction(recallConfig);

    // 初始化页面信息
    this.init();
  },
  methods: {
    ...mapActions([
      "setConfigAction",
      "showInnerAction",
      "userInfoAction",
      "isLoginAction",
      "financeAction",
      "isPayAction",
      "tokenAction",
      "isShowExitGameAction",
      "isWeChatAction",
    ]),

    onShowControl(showSafariTips) {
      this.showSafariTips = showSafariTips;
    },

    // 初始化页面信息
    async init() {
      // 微信内
      const _this = this;
      document.addEventListener(
        "WeixinJSBridgeReady",
        function onBridgeReady() {
          _this.isWeChatAction(true);
          // const wechat_open_id = localStorage.getItem("wechat_open_id");
          const wechat_open_id = _this.$utils.getCookie("wechat_open_id");
          const wechat_code = _this.$utils.getQueryString("code");
          if (!wechat_open_id && !wechat_code) {
            _this.$toast.text("授权过期，请重新授权");
            _this.getWechatCode();
            return;
          }

          // 有code, 没有openid 用code换openid
          if (!wechat_open_id && wechat_code) {
            _this.wechatOpenId();
          }
        },
        false
      );

      // userInfo
      //   const userInfo = localStorage.getItem("userInfo");
      //   if (!userInfo) {
      //     this.isLoginAction(false);
      //     return;
      //   }

      // 校验登录态
      await this.refresh();
      // 获取用户信息
      await this.getUserInfo();
      // 获取鸿币余额
      await this.getFinance();
      // 订单查询
      await this.queryOrder();
    },

    // 换openid
    wechatOpenId() {
      const wechat_code = this.$utils.getQueryString("code");
      const pay_type = this.$utils.payType("WECHATPAY").h5;
      this.$api
        .wechatOpenId({
          wechat_code,
          pay_type,
        })
        .then((res) => {
          this.checkCode(res);
          const { data, code, msg } = res.data;
          // 错误
          if (code) {
            return;
          }
          // 成功
          this.$utils.setCookie("wechat_open_id", data.openId, 30);
        });
    },

    // 获取用户信息
    getUserInfo() {
      this.$api
        .info()
        .then((res) => {
          this.checkCode(res);
          const { data, code, msg } = res.data;
          // 错误
          if (code) {
            return;
          }
          // 成功
          this.isLoginAction(true);
          localStorage.setItem("userInfo", JSON.stringify(data));
          this.userInfoAction(data);
          const token = localStorage.getItem("token");
          this.tokenAction(token);
        })
        .then(() => {
          // 携带token 直接登录
          const token = this.$utils.getQueryString("token");
          if (token) {
            // window.location.href = this.$utils.delQueStr(
            //   window.location.href,
            //   "token"
            // );
            return;
          }
        });
    },

    // 查询鸿币余额
    getFinance() {
      this.$api.finance().then((res) => {
        this.checkCode(res);
        const { data, code, msg } = res.data;
        // 错误
        if (code) {
          return;
        }
        // 成功
        this.financeAction(data.hb / 100);
      });
    },

    // 微信获取微信code
    getWechatCode() {
      const { wechatAppid } = this;
      let redirect_uri = "";
      redirect_uri = escape(window.location.href);
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wechatAppid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
    },

    /**
     * 支付宝 微信支付
     * @param {Object} payInfo 支付信息
     */
    payHandler(payInfo) {
      const {
        server_id,
        server_name,
        cp_order_id,
        role_name,
        role_id,
        goods_id,
        goods_name,
        amount,
        pay_type,
        pay_platform,
        extra,
      } = payInfo;
      const { appid } = this;
      return this.$api
        .order({
          server_id,
          server_name,
          cp_order_id,
          app_id: appid,
          role_name,
          role_id,
          goods_id,
          goods_name,
          amount,
          pay_type,
          pay_platform,
          return_url: window.location.href,
          extra,
        })
        .then((res) => {
          this.checkCodeHandler(res);
          const { data, code, msg } = res.data;
          // 错误
          if (code) {
            return;
          }
          // 成功
          this.isPayAction(true);

          // 鸿币支付不需要回调
          if (pay_platform === "HB") {
            return;
          }

          const time = new Date().getTime();
          const orderItem = {
            order_id: data.order_id,
            time,
          };
          let orderList = JSON.parse(localStorage.getItem("orderList")) || [];
          orderList.push(orderItem);
          localStorage.setItem("orderList", JSON.stringify(orderList));

          // 微信内支付
          const { isWeChat } = this;
          if (isWeChat) {
            this.wechatPay(data);
            return;
          }
          window.location.href = data.url;
        });
    },

    // 微信内支付
    wechatPay(res) {
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            this.onBridgeReady(res),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady(res));
          document.attachEvent(
            "onWeixinJSBridgeReady",
            this.onBridgeReady(res)
          );
        }
      } else {
        this.onBridgeReady(res);
      }
    },

    // 微信内支付
    onBridgeReady(res) {
      const { appId, timeStamp, nonceStr, signType, paySign, openId } = res;
      //   localStorage.setItem("wechat_open_id", openId);
      this.$utils.setCookie("wechat_open_id", openId, 30);
      const _this = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId, //公众号ID，由商户传入
          timeStamp, //时间戳，自1970年以来的秒数
          nonceStr, //随机串
          package: res.package,
          signType, //微信签名方式：
          paySign, //微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            _this.$toast.text("支付成功");
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            return;
          }
          if (res.err_msg == "get_brand_wcpay_request:cancel") {
            _this.$toast.text("取消支付");
            return;
          }
          _this.$toast.text("支付失败");
        }
      );
    },

    // 订单查询
    queryOrder() {
      //  延迟执行定义定时器
      this.queryTimeout = setTimeout(() => {
        let orderList = JSON.parse(localStorage.getItem("orderList")) || [];
        if (orderList.length == 0) {
          clearTimeout(this.queryTimeout);
          return;
        }
        const maxTime = 10000;
        const nowTime = new Date().getTime();
        let _orderList = JSON.parse(JSON.stringify(orderList));
        orderList.map((ele, index) => {
          const flag = nowTime - ele.time > maxTime;
          if (!flag) {
            return;
          }
          // 大于10s 订单查询
          this.$api
            .query({
              order_id: ele.order_id,
            })
            .then((res) => {
              _orderList.splice(index, 1);
              localStorage.setItem("orderList", JSON.stringify(_orderList));
            });
        });
        this.queryOrder();
      }, 5000);
    },

    // 显示innerBox
    openInnerBox() {
      this.showInnerAction(true);
    },

    // 校验返回值
    checkCode(res) {
      // 请求超时
      if (!res) {
        this.$toast.text("当前网络拥堵, 请重试");
        return;
      }
      this.checkCodeHandler(res);
    },

    // 刷新登录态
    refresh() {
      return this.$api.refresh().then((res) => {
        this.checkCode(res);
        const { data, code, msg } = res.data;
        // 错误
        if (code) {
          this.isLoginAction(false);
          this.showInnerAction(false);
          localStorage.removeItem("userInfo");
          return;
        }

        const userInfo = localStorage.getItem("userInfo");
        this.isLoginAction(true);
        this.userInfoAction(JSON.parse(userInfo));
      });
    },

    // 校验返回值====all
    checkCodeHandler(res) {
      const { code, msg } = res.data;
      if (!code) {
        return;
      }
      switch (code) {
        // 2 未登录
        case 2:
          localStorage.removeItem("userInfo");
          this.showInnerAction(false);
          this.isLoginAction(false);
          this.userInfoAction({});
          this.$toast.text(msg);
          break;
        // 7 微信支付code 过期
        case 7:
          this.getWechatCode();
          this.$toast.text(msg);
          break;
        default:
          this.$toast.text(msg);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.focusState {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
</style>
