import { getCartCount } from "../api/home.api";
import store from "store";
import { SAVE_CART_COUNT } from "store/modules/shoppingCart/type.js";

const saveCartCount = count => {
  store.commit(SAVE_CART_COUNT, count);
};
// console.log("saveCartCount", saveCartCount);

export const getCartCountVal = async function() {
  const token = uni.getStorageSync("token") || "";
  if (!token) return;
  const [data] = await getCartCount();
  if (!data) return;
  saveCartCount(data.count);
  const count = data.count > 99 ? "99+" : data.count ? data.count : "";
  const params = {
    index: 1,
    text: `${count}`
  };
  count ? uni.setTabBarBadge(params) : uni.removeTabBarBadge({ index: 1 });
  return count;
};

export const jumpToUrl = function(url) {
  if (!url) return;
  url = url.toString();
  if (!url || url.indexOf("xyqb://") > -1) {
    uni.switchTab({
      url: "/pages/index/index"
    });
    return;
  }
  if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0) {
    uni.navigateTo({
      url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
    });
    return;
  }
  const tabUrl = ["/pages/index/index", "/pages/shopcart/index", "/pages/user/user"];
  const navigateType = tabUrl.indexOf(url) > -1 ? "switchTab" : "navigateTo";
  console.log(navigateType);
  console.log(url);
  uni[navigateType]({
    url
  });
};
