<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
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: {},
  data() {
    return {
      wechatAppid: "wx2c4f9f89c572aeb5", // 公众号appid
    };
  },
  computed: {
    ...mapState(["query", "appid", "CONFIG"]),
  },
  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);

      // 获取当前android是哪个(针对特殊处理的包, 比如仙界情缘)
      const platform = this.$utils.getQueryString("platform");
      this.platformAction(platform);
    },

    // 获取用户信息
    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 returnUrlQuery = `pay=game&appid=${appid}&server_id=${server_id}&server_name=${server_name}&cp_order_id=${cp_order_id}&role_name=${role_name}&role_id=${role_id}&goods_id=${goods_id}&goods_name=${goods_name}&amount=${amount}&pay_type=${pay_type}&pay_platform=${pay_platform}`;
      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 + returnUrlQuery,
          extra,
        })
        .then((res) => {
          this.checkCodeHandler(res);
          const { data, code, msg } = res.data;
          // 错误
          if (code) {
            return;
          }

          // 鸿币支付不需要跳转页面
          if (pay_platform === "HB") {
            return;
          }
          window.location.href = data.url;
        });
    },

    /**
     * 鸿币充值
     */
    onRecharge(payInfo) {
      const { pay_platform, amount, goods_name, pay_type, extra } = payInfo;
      const { appid } = this;
      const returnUrlLeft =
        window.location.origin + window.location.pathname + "#/counter?";
      const returnUrlQuery = `pay=hb&appid=${appid}&amount=${amount}&goods_name=${goods_name}&pay_type=${pay_type}&pay_platform=${pay_platform}`;
      return this.$api
        .recharge({
          amount,
          goods_name,
          app_id: appid,
          pay_type,
          pay_platform,
          return_url: returnUrlLeft + returnUrlQuery,
          extra,
        })
        .then((res) => {
          this.checkCodeHandler(res);
          const { data, code } = res.data;
          // 错误
          if (code) {
            return res;
          }

          // 成功
          const time = new Date().getTime();
          const orderItem = {
            order_id: data.order_id,
            time,
            server_id: "",
            server_name: "",
            cp_order_id: "",
            app_id: appid,
            role_name: "",
            role_id: "",
            goods_id: "",
            goods_name,
            amount,
            pay_type,
          };
          //   let orderList = JSON.parse(localStorage.getItem("orderList")) || [];
          let orderList = this.$utils.readStorage("", "orderList");
          orderList = JSON.parse(orderList) || [];
          orderList.push(orderItem);

          //   localStorage.setItem("orderList", JSON.stringify(orderList));
          this.$utils.writeStorage("", "orderList", JSON.stringify(orderList));

          window.location.href = data.url;
          return res;
        });
    },

    // 订单查询
    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) {
          // localStorage.removeItem("userInfo");
          this.$utils.deleteStorage("", "userInfo");
          return;
        }

        // const userInfo = localStorage.getItem("userInfo");
        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:
          //   localStorage.removeItem("userInfo");
          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>
