<template>
  <div id="app">
    <MenuService v-if="showServiceInline" />
    <router-view />
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import MenuService from "@/components/Menu/MenuService"; // 联系客服
export default {
  name: "App",
  // 向子组件提供变量/方法, 子组件通过inject 注入变量
  provide() {
    return {
      // 校验返回值
      checkCode: this.checkCode,
      // 支付校验返回值
      checkCodeHandler: this.checkCodeHandler,
      // 刷新登录态
      refresh: this.refresh,
      // 获取用户信息
      getUserInfo: this.getUserInfo,
      // 获取鸿币余额
      getFinance: this.getFinance,
      // 支付
      payHandler: this.payHandler,
      // 订单查询
      queryOrder: this.queryOrder,
      // 路由跳转(携带路由参数)
      routeLink: this.routeLink,
      // 鸿币充值
      onRecharge: this.onRecharge,
    };
  },
  components: {
    MenuService,
  },
  data() {
    return {
      wechatAppid: "wx2c4f9f89c572aeb5", // 公众号appid
    };
  },
  computed: {
    ...mapState(["query", "appid", "CONFIG", "userInfo", "showServiceInline"]),
  },
  watch: {
    // 监听路由变化 初始化路由
    $route(to, from) {
      this.initUrl();
    },
  },
  created() {
    this.initUrl();
  },
  mounted() {
    // 设置页面基础配置信息
    this.setConfigAction(this.$CONFIG);
  },
  methods: {
    ...mapActions([
      "queryAction",
      "userInfoAction",
      "financeAction",
      "appidAction",
      "setConfigAction",
      "platformAction",
    ]),

    /**
     * 初始化路由地址
     */
    initUrl() {
      // 获取url 参数
      const query = this.$utils.getAllQueryString();
      this.queryAction({ ...query });

      // 获取appid
      const _appid = this.$utils.getQueryString("appid");
      const appid = _appid || this.CONFIG.appid;
      this.appidAction(appid);

      // 获取当前是哪个(针对特殊处理的包, 比如忘川伏魔录)
      const platform = this.$utils.getQueryString("platform");
      this.platformAction(platform);

      // 获取userInfo
      let userInfo = this.$utils.readStorage("", "userInfo");
      userInfo = userInfo && JSON.parse(userInfo);
      this.userInfoAction(userInfo);
    },

    // 获取用户信息
    getUserInfo() {
      this.$api.info().then((res) => {
        this.checkCode(res);
        const { data, code } = res.data;
        // 错误
        if (code) {
          return;
        }
        // 成功
        // localStorage.setItem("userInfo", JSON.stringify(data));
        this.$utils.writeStorage("", "userInfo", JSON.stringify(data));
        this.userInfoAction(data);
      });
    },

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

    /**
     * 支付宝 微信支付
     * @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;
      const returnUrlLeft =
        window.location.origin + window.location.pathname + "#/counter?";
      const allQuery = this.$utils.getAllQueryString();
      // 2. 将需要的参数拼接
      const queryString = this.$utils.queryStringUtil({
        amount,
        pay_platform,
        pay: "game",
      });
      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: returnUrlLeft + queryString,
          extra,
        })
        .then((res) => {
          this.checkCodeHandler(res);
          const { data, code, msg } = res.data;
          // 错误
          if (code) {
            return;
          }

          // 鸿币支付不需要跳转页面
          if (pay_platform === "HB") {
            return;
          }

          let payUrl = data.url;
          if (pay_platform === "WECHATPAY") {
            payUrl = `${payUrl}&redirect_url=${encodeURIComponent(
              returnUrlLeft + queryString
            )}`;
          }
          this.onPayUtil(payUrl);
        });
    },

    /**
     * 鸿币充值
     */
    onRecharge(payInfo) {
      const { pay_platform, amount, goods_name, pay_type, extra } = payInfo;
      const { appid } = this;
      const returnUrlLeft =
        window.location.origin + window.location.pathname + "#/counter?";

      // 2. 将需要的参数拼接
      const queryString = this.$utils.queryStringUtil({
        amount,
        pay_platform,
        pay: "game",
      });

      return this.$api
        .recharge({
          amount,
          goods_name,
          app_id: appid,
          pay_type,
          pay_platform,
          return_url: returnUrlLeft + queryString,
          extra,
        })
        .then((res) => {
          this.checkCodeHandler(res);
          const { data, code } = res.data;
          // 错误
          if (code) {
            return res;
          }

          let payUrl = data.url;
          if (pay_platform === "WECHATPAY") {
            payUrl = `${payUrl}&redirect_url=${encodeURIComponent(
              returnUrlLeft + queryString
            )}`;
          }
          this.onPayUtil(payUrl);
          return res;
        });
    },

    // 支付工具函数
    onPayUtil(payUrl) {
      const _payUrl = `${this.$CONFIG.redirectUrl}${encodeURIComponent(
        payUrl
      )}`;
      const savedata = decodeURIComponent(this.$utils.getQueryString("data"));
      window.location.href = `${
        this.$CONFIG.wcfmlPayUrl
      }?data=${savedata}&jump=${encodeURIComponent(_payUrl)}`;
    },

    // 订单查询
    queryOrder(order_id) {
      this.$api.query({
        order_id,
      });
    },

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

    // 刷新登录态
    refresh() {
      return this.$api.refresh().then((res) => {
        this.checkCode(res);
        const { code } = res.data;
        // 错误
        if (code) {
          this.$utils.deleteStorage("", "userInfo");
          return;
        }

        const userInfo = this.$utils.readStorage("", "userInfo");
        this.userInfoAction(JSON.parse(userInfo));
      });
    },

    // 校验返回值====all
    checkCodeHandler(res) {
      const { code, msg } = res.data;
      if (!code) {
        return;
      }
      switch (code) {
        // 2 未登录
        case 2:
          this.$utils.deleteStorage("", "userInfo");
          this.userInfoAction({});
          // 跳转登录
          this.routeLink("Login");
          break;
        // 7 微信支付code 过期
        case 7:
          this.$toast.text(msg);
          break;
        default:
          this.$toast.text(msg);
      }
    },

    // 跳转页面
    routeLink(routeName, params) {
      const query = this.$utils.getAllQueryString();
      this.queryAction({ ...query });
      this.$utils.routeLink(routeName, query, params);
    },
  },
};
</script>

<style lang="less">
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  //   color: #eee;
  color: #555555;
  font-size: 28 / @rem;
}
/**横屏 */
@media screen and (orientation: landscape),
  only screen and (min-device-width: 768px) and (min-device-height: 768px) and (orientation: portrait) {
  #app {
    font-size: 16 / @rem;
  }
}
</style>
