import api from "@/api";
import { hex_sha1 } from "@/utils/sha1";
export class PageUtils {
  // 获取当前路由
  static getCurPage(): object {
    let pages = getCurrentPages();
    let curPage = pages[pages.length - 1];
    return curPage;
  }

  static getCurQuery(): object {
    // @ts-ignore
    return PageUtils.getCurPage().$page.options;
  }

  // 微信不需要标题,因为会出现双标题问题，而且我觉得标题上移会简洁一点
  // force强制获取
  static getTitle(force?: boolean): string {
    // @ts-ignore
    if (force) return PageUtils.getCurPage().$page.meta.navigationBar.titleText
    // @ts-ignore
    return uni.getStorageSync('isWX')?'':PageUtils.getCurPage().$page.meta.navigationBar.titleText
  }

  static object2Query(obj: any): string {
    let queryList: Array<string> = [];
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        queryList.push(
          encodeURIComponent(key) + "=" + encodeURIComponent(obj[key])
        );
      }
    }
    return queryList.join("&");
  }

  static goBack(url?: string) {
    if (getCurrentPages().length == 1) {
      uni.navigateTo({ url: url || "/" });
    } else {
      uni.navigateBack({
        delta: 1,
      });
    }
  }
}

declare interface EnumName {
  name: 'delivery' | 'userSex';
}
export class Enum {
  static delivery = {
    0: "现货",
    1: "15天",
    2: "30天",
    3: "45天",
    4: "45天以上",
  };
  static userSex = {
    null: "未填写",
    0: "女",
    1: "男"
  };
  static get(name: EnumName['name'], value: any) {
    if (!Enum.hasOwnProperty(name)) {
      console.error('Enum中没有该参数，请在Utils.ts中设置')
      return undefined
    }
    // @ts-ignore
    return Enum[name][value];
  }
}

export class WXUtils {
  static isWeiXin() {
    if (/micromessenger/.test(window.navigator.userAgent.toLowerCase())) {
      return true;
    } else {
      return false;
    }
  }
  static initWXConfig(test?: boolean) {
    return new Promise((resolve, reject) => {
      const wx = window._wx;
      api
        .getJsApiTicket()
        .then((ticket: any) => {
          const nonceStr = DataUtils.getRandString(16);
          const timestamp = Math.trunc(new Date().getTime() / 1000);
          const url = window.location.href;
          const signature = hex_sha1(
            `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`
          );
          const wxConfig = {
            debug: !!test, // 上生产，时设置成false
            appId: "wx6165c6cc754deeba",
            timestamp,
            nonceStr,
            signature,
            jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"],
          };
          wx.config(wxConfig);
          wx.ready(function () {
            resolve({
              status: true,
              message: "初始化成功",
              data: wxConfig,
            });
          });
          wx.error(function (data: any) {
            reject({
              status: false,
              message: "初始化失败:微信配置异常",
              data,
            });
          });
        })
        .catch((data: any) => {
          reject({
            status: false,
            message: "初始化失败:后台异常",
            data,
          });
        });
    });
  }
}

export class DataUtils {
  static getRandString(len: number) {
    const chars =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var str = "";
    for (var i = 0; i < len; i++) {
      str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
  }
}
