import axios from "axios";

declare const wx: any;

const ua = navigator.userAgent.toLowerCase();

function isWeixinBrowser() {
  return /micromessenger/.test(ua) ? true : false;
}

function isIos() {
  if (/(iphone|ipad|ipod|ios)/i.test(ua)) {
    return true;
  } else {
    return false;
  }
}

// function isAndroid() {
//   if (/(android)/i.test(ua)) {
//     return true;
//   } else {
//     return false;
//   }
// }

export class wxController {
  signSuccess = false;
  requestUrl = ""; //获取signature地址

  configData = {
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: "", // 必填，公众号的唯一标识
    timestamp: 0, // 必填，生成签名的时间戳
    nonceStr: "", // 必填，生成签名的随机串
    signature: "", // 必填，签名
    jsApiList: [
      "updateAppMessageShareData",
      "updateTimelineShareData",
      "previewImage",
    ], // 必填，需要使用的JS接口列表
  };

  //默认分享设置
  shareData = {
    title: "",
    link: location.href,
    imgUrl: "",
    desc: "",
  };

  constructor(options: { url: string }) {
    this.requestUrl = options.url;
  }

  setup(signUrl: string) {
    if (isWeixinBrowser()) {
      if (isIos()) {
        signUrl = signUrl.split("#")[0];
      }
      this.signSuccess = false;
      this.sign(signUrl);
    } else {
      console.error("非微信浏览器");
    }
  }

  sign(url: string) {
    const _this = this;

    if (!url) url = window.location.href;

    //签名接口
    axios(this.requestUrl, {
      method: "get",
      params: { url },
    })
      .then(function (response) {
        const data = response.data.result;
        _this.setConfig(data);
        wx.config(_this.configData);
        wx.ready(function () {
          _this.signSuccess = true;
          _this.setShare();
        });
        wx.error(function (res: any) {
          _this.signSuccess = false;
          console.error("error: ", res);
        });
      })
      .catch(function (error) {
        console.error(error);
      });
  }

  setShareData(shareData: {
    title: string;
    link: string;
    imgUrl: string;
    desc: string;
  }) {
    shareData = Object.assign({}, this.shareData, shareData);
    this.shareData = shareData;
  }

  setConfig(options: any) {
    const { app_id, nonce_str, signature, timestamp } = options;
    this.configData = Object.assign(this.configData, {
      appId: app_id,
      timestamp: timestamp,
      nonceStr: nonce_str,
      signature: signature,
    });
  }

  setShare(options?: {
    link: string;
    title: string;
    desc: string;
    imgUrl: string;
  }) {
    options = Object.assign({}, this.shareData, options);

    if (!this.signSuccess || !options.title) return;

    wx.updateAppMessageShareData({
      title: options.title, // 分享标题
      desc: options.desc, // 分享描述
      link: options.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: options.imgUrl, // 分享图标
      success: function () {
        console.log("设置成功");
      },
      fail: function (msg: any) {
        console.error("设置失败：" + JSON.stringify(msg));
      },
    });

    wx.updateTimelineShareData({
      title: options.title, // 分享标题
      link: options.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: options.imgUrl, // 分享图标
      success: function () {
        console.log("设置成功");
      },
      fail: function (msg: any) {
        console.error("设置失败：" + JSON.stringify(msg));
      },
    });
  }

  setPreviewData(url: string, urls: string[]) {
    if (!this.signSuccess) return;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: urls, // 需要预览的图片http链接列表
    });
  }
}
