import store from "../store/store";
import wx from "weixin-js-sdk";
import apis1 from "./apis1.js";
// import sharebg from '../assets/images/share.png'
// let weynum =

let {
  signature
} = apis1;

// 此方法重复
const getUrlQueryValueByKey = (keyName, url) => {
  /*获取url地址栏中参数值，url为可选，默认为当前页面url*/
  if (!url) {
    url = location.href;
  }
  var reg = new RegExp("(^|[&?])" + keyName + "=([^&]*)(&|$)");
  var r = url.match(reg); //search,查询？后面的参数，并匹配正则
  if (r != null) return unescape(r[2]);
  return "";
};

const reportClick = (eventId, shopId, skuId, shareUuid) => {
  // eslint-disable-next-line no-undef
  let click = new MPing.inputs.Click(eventId);

  click.shopid = shopId || "";
  click.userpin = store.state.secretPin;
  click.activityid = store.state.jdActivityId;
  click.skuid = skuId || "";
  click.shareuserid = shareUuid || "";

  switch (store.state.clientType) {
    case "APP":
      click.channel = "app";
      break;
    case "WeChat":
      click.channel = "wx";
      break;
    case "QQ":
      click.channel = "qq";
      break;
    default:
      click.channel = "other";
  }

  if (store.state.isMiniProgram) {
    click.channel = "gouwu_applet";
  }

  click.updateEventSeries(); //更新时间串
  // eslint-disable-next-line no-undef
  let mping = new MPing();
  mping.send(click);
};

const reportPV = () => {
  // eslint-disable-next-line no-undef
  let pv = new MPing.inputs.PV();
  pv.shopid = store.state.shopId;
  pv.userpin = store.state.secretPin;
  pv.activityid = store.state.jdActivityId;

  let shareUserId = getUrlQueryValueByKey("shareuserid4minipg");
  if (shareUserId) {
    shareUserId = decodeURIComponent(shareUserId);
    pv.shareuserid = shareUserId;
  }
  switch (store.state.clientType) {
    case "APP":
      pv.channel = "app";
      break;
    case "WeChat":
      pv.channel = "wx";
      break;
    case "QQ":
      pv.channel = "qq";
      break;
    default:
      pv.channel = "other";
  }

  if (store.state.isMiniProgram) {
    pv.channel = "gouwu_applet";
  }
  // eslint-disable-next-line no-undef
  let mping = new MPing();
  mping.send(pv);
};

const closeWechatShareMask = () => {
  const popup = document.querySelector("#weChatShareMask");

  if (popup) {
    popup.style.display = "none";
  }
};

const showWechatShareMask = () => {
  const popup = document.querySelector("#weChatShareMask");

  if (!popup) {
    let mask = document.createElement("div");
    let icon = document.createElement("span");

    mask.setAttribute("id", "weChatShareMask");
    mask.style.cssText =
      "width:100vw;height:100vh;position:fixed;top:0;left:0;background:rgba(0,0,0,0.8);z-index: 99999;";
    icon.style.cssText =
      "width:7.50rem;height:4.22rem;background-image:url(https://img10.360buyimg.com/imgzone/jfs/t1/133722/2/12955/277061/5f8d64ffEcc18cac1/70b479225aa60a57.png);background-size:100% 100%;position:absolute;top:0.42rem;right:0rem;";
    // https://img10.360buyimg.com/imgzone/jfs/t1/18504/29/8138/79587/5c738423Ea807d3d1/ae0311769b1abbf7.png
    document.querySelector("body").appendChild(mask);
    mask.appendChild(icon);

    document.querySelector("#weChatShareMask").onclick = closeWechatShareMask;
  } else {
    popup.style.display = "block";
  }
};

// 微信分享方法
const callShare4WeChat = (title, content, url, logo, isHeader, callback) => {
  let shareUrl;

  if (url) {
    shareUrl = url;
  } else {
    shareUrl = location.href || "https://www.jd.com";
  }

  if (store.state.clientType == "APP") {
    if (isHeader) {
      // eslint-disable-next-line no-undef
      JSSDK.WebView.callHeaderSharePanel({
        title: title || "分享活动",
        content: content || "分享活动内容",
        shareUrl: shareUrl,
        channel: "",
        iconUrl: logo,
        callfunc: callback
      });
    } else {
      // eslint-disable-next-line no-undef
      JSSDK.WebView.callSharePanel({
        title: title || "分享活动",
        content: content || "分享活动内容",
        shareUrl: shareUrl,
        channel: "",
        iconUrl: logo,
        callfunc: callback
      });
    }
  } else {
    if (!isHeader) {
      showWechatShareMask();
    }
    signature(data => {
      wx.config({
        debug: false,
        appId: data.data.appid,
        timestamp: data.data.timestamp,
        nonceStr: data.data.nonceStr,
        signature: data.data.signature,
        jsApiList: [
          "onMenuShareWeibo",
          "onMenuShareTimeline",
          "onMenuShareAppMessage",
          "onMenuShareQQ",
          "onMenuShareQZone",
          "showAllNonBaseMenuItem"
        ]
      });
      wx.ready(function() {
        wx.checkJsApi({
          jsApiList: [
            "onMenuShareTimeline",
            "onMenuShareQQ",
            "onMenuShareWeibo"
          ]
        });
        wx.onMenuShareTimeline({
          title: title || "分享活动", // 分享标题
          link: shareUrl, // 分享链接，该链接域名必须与当前企业的可信域名一致
          imgUrl: logo || "", // 分享图标
          success: function() {
            closeWechatShareMask();
            // 用户确认分享后执行的回调函数
            const retData = {
              shareResult: 0
            };
            callback && callback(retData);
          },
          cancel: function() {
            closeWechatShareMask();
          },
          fail: function(res) {
            closeWechatShareMask();
            alert("wx.onMenuShareTimeline:fail: " + JSON.stringify(res));
          }
        });
        wx.onMenuShareAppMessage({
          title: title || "分享活动", // 分享标题
          desc: content || "分享活动内容", // 分享描述
          link: shareUrl, // 分享链接
          imgUrl: logo || "", // 分享图标
          success: function() {
            closeWechatShareMask();
            // 用户确认分享后执行的回调函数
            const retData = {
              shareResult: 0
            };
            callback && callback(retData);
          },
          cancel: function() {
            closeWechatShareMask();
            // 用户取消分享后执行的回调函数
          }
        });
        wx.onMenuShareQQ({
          title: title || "分享活动", // 分享标题
          desc: content || "分享活动内容", // 分享描述
          link: shareUrl, // 分享链接
          imgUrl: logo || "", // 分享图标
          success: function() {
            closeWechatShareMask();
            // 用户确认分享后执行的回调函数
            const retData = {
              shareResult: 0
            };
            callback && callback(retData);
          },
          cancel: function() {
            closeWechatShareMask();
            // 用户取消分享后执行的回调函数
          }
        });
        wx.onMenuShareWeibo({
          title: title || "分享活动", // 分享标题
          desc: content || "分享活动内容", // 分享描述
          link: shareUrl, // 分享链接
          imgUrl: logo || "", // 分享图标
          success: function() {
            closeWechatShareMask();
            // 用户确认分享后执行的回调函数
            const retData = {
              shareResult: 0
            };
            callback && callback(retData);
          },
          cancel: function() {
            closeWechatShareMask();
            // 用户取消分享后执行的回调函数
          }
        });
      });
    });
  }
};

// 小程序分享方法
const callShare4MiniProgram = (title, content, url, logoUrl, callback, isHeader, mpIconUrl, shopid, userpin,
  jdactivityid) => {
  //TODO 调用接口判断分享方式 0为京口令，1为H5，2为小程序 京口令跳转中转页面不进行任何操作，h5 直接在微信打开h5页面，小程序 直接弹出打开小程序弹框
  let weynum = sessionStorage.getItem('weynum')

  console.log('小程序分享方法')

  console.log(title, 'title')
  console.log(content, 'content')
  console.log(url, 'url')
  console.log(logoUrl, 'logoUrl')
  console.log(callback, 'callback')
  console.log(isHeader, 'isHeader')
  console.log(mpIconUrl, 'mpIconUrl')
  console.log(shopid, 'shopid')
  console.log(userpin, 'userpin')
  console.log(jdactivityid, 'jdactivityid')

  var shareUrl;
  if (url) {
    shareUrl = url;
  } else {
    shareUrl = location.href || "https://www.jd.com";
  }
  // console.log(shareUrl.indexOf("shareuserid4minipg"), 'indexOf')

  if (shareUrl.indexOf("shareuserid4minipg") < 0) {
    // console.log(shareUrl.indexOf("?"), 'indexOf1111')
    if (shareUrl.indexOf("?") > 0) {
      shareUrl = shareUrl + "&shareuserid4minipg=" + encodeURIComponent(userpin)
    } else {
      shareUrl = shareUrl + "?shareuserid4minipg=" + encodeURIComponent(userpin)
    }
  }
  // console.log(shareUrl, 'shareUrl')
  // if (!isHeader) {
  //上报子午线分享点击埋点
  // reportShareEvent(shopid, userpin, jdactivityid)
  // reportClick("share", shopid, userpin, jdactivityid);
  // }

  // var imgurl = 'https://lz-lkyl.oss-cn-zhangjiakou.aliyuncs.com/sub-system/active/share/c822cd70-8d54-409c-877a-7ae837e16c18/500-400%20(2).png' //encodeURI(mpIconUrl);
  var imgurl = mpIconUrl; //"https://img10.360buyimg.com/imgzone/jfs/t1/151712/34/15817/45445/600bae4bE4163dad8/c182821a5670cc0d.png";

  // console.log(imgurl, 'imgurl')
  // console.log(mpIconUrl, 'mpIconUrl11111')
  // 小程序分享页面氛围图片尺寸：670*470
  var atmosimgurl = mpIconUrl.replace("/jfs/", "/s670x470_jfs/") + "!cc_670x470";
  console.log(atmosimgurl, 'atmosimgurl')
  // 小程序分享出去的围图片尺寸：500*400
  var shareimgurl = mpIconUrl.replace("/jfs/", "/s500x400_jfs/") + "!cc_500x400";
  console.log(shareimgurl, 'shareimgurl')
  // 海报图片尺寸：550*500
  var posterimgurl = mpIconUrl.replace("/jfs/", "/s550x500_jfs/") + "!cc_550x500";
  console.log(posterimgurl, 'posterimgurl')

  var endTime = new Date().getTime() + 30 * 60 * 60 * 24 * 1000;
  console.log(store.state.clientType, '运行平台')
  // console.log(SYS_FROMTYPE, 'SYS_FROMTYPE')

  if (store.state.clientType == "01") {
    //APP
    shareUrl = shareUrl + "&shopid=" + shopid;
    if (weynum == 0) {
      shareUrl = encodeURIComponent(shareUrl);
      var parameters = {
        "title": title,
        "content": content,
        "url": shareUrl, //shareUrl https://m.jd.com,
        "img": logoUrl,
        "channel": "Wxfriends", //
        "callback": callback,
        "clickcallback": null,
        "qrparam": null,
        "timeline_title": "",
        "mpId": "gh_45b306365c3d", //gh_45b306365c3d gh_3f27179ed84f
        "mpIconUrl": shareimgurl,
        "mpPath": "pages/h5/index?encode_url=" + shareUrl,
        "mpType": "0", //0 正式 1 开发 2 体验
        "appCode": "jApp",
        "keyparam": {
          "url": decodeURIComponent(shareUrl),
          "keyEndTime": JSON.stringify(endTime),
          "keyChannel": "Wxfriends,QQfriends,Wxmoments,QQzone,Sinaweibo",
          "sourceCode": "isv",
          "keyImg": imgurl,
          "keyId": decodeURIComponent(shareUrl).split('?')[0] + '/' + jdactivityid,
          "keyTitle": title,
          "keyContent": content,
          "keyOpenapp": "openapp.jdmobile://virtual?params={\"category\":\"jump\",\"des\":\"jdreactcommon\",\"modulename\":\"JDReactCollectJDBeans\",\"appname\":\"JDReactCollectJDBeans\",\"param\":{\"page\":\"collectJDBeansHomePage\",\"transparentenable\":true}}"
        }
      }
      console.log(parameters,'京口令分享')
    } else if (weynum == 1) {
      var parameters = {
        "title": title,
        "content": content,
        "url": shareUrl,
        "img": logoUrl,
        "channel": "Wxfriends",
        "callback": callback,
        "clickcallback": null,
        "qrparam": null,
        "timeline_title": "",
      }
      console.log(parameters,'H5分享')
    } else if (weynum == 2) {
      shareUrl = encodeURIComponent(shareUrl);
      var parameters = {
        "title": title,
        "content": content,
        "url": shareUrl,
        "img": logoUrl,
        "channel": "Wxfriends",
        "callback": callback,
        "clickcallback": null,
        "qrparam": null,
        "timeline_title": "",
        "mpId": "gh_45b306365c3d",
        "mpIconUrl": shareimgurl,
        "mpPath": "pages/h5_wv/sns/index?encode_url=" + shareUrl,
        "mpType": "0",
      }
      console.log(parameters,'小程序分享')
    }

    console.log(parameters, 'parameters')
    if (isHeader && !window.XView) {
      jdshare.setShareInfo(parameters);
    } else {
      jdshare.callSharePane(parameters);

    }

  } else {
    if (store.state.clientType == "02") {
      //微信小程序
      console.log(wx, '微信小程序')
      if (!isHeader) {
        //子午线埋点：上报分享按钮点击事件（小程序专用）
        // reportClick("share",shopid,userpin,jdactivityid)
        callback()
        wx.miniProgram.navigateTo({
          url: '/pages/h5share/index/index?atmosimgurl=' + encodeURIComponent(atmosimgurl) +
            '&sharetitle=' + encodeURIComponent(title) +
            '&shareurl=' + encodeURIComponent(shareUrl) +
            '&shareimgurl=' + encodeURIComponent(shareimgurl) +
            '&isautoback=1' +
            '&noneBtnBg=0'
          // +'&shareposter=1'
          // +'&postertitle='+ encodeURIComponent(title)
          // +'&posterdesc='+ encodeURIComponent(content)
          // +'&posterimgurl='+ encodeURIComponent(mpIconUrl)

        });

      }

    } else {
      // if (isHeader) {
      //     busiSetHeadShare(replaceTitle, content, shareUrl, logoUrl, callback);
      // } else {
      //     if (store.state.clientType == "02") {
      //         showWechatShareMask();
      //     }
      //     buyersShareCallback(replaceTitle, content, -1, shareUrl, logoUrl, callback);
      // }
    }
  }
}

// const callShare = (title,enterTheType, content, url, logo, logoMini, isHeader, callback) => {
//   var enterTheType = '0'//0 客端 1 主端
//   if (process.env.NODE_ENV == "development") {
//     if (!isHeader) {
//       showWechatShareMask();
//     }
//   } else {
//     if (store.state.miniProApp) {
//       console.log('设置小程序分享');
//       callShare4MiniProgram(
//         title,
//         content,
//         url,
//         logo,
//         logoMini,
//         isHeader,
//         enterTheType,
//         callback
//       );
//     } else {
//       // console.log('设置微信分享');
//       callShare4WeChat(title, content, url, logo, isHeader, callback);
//     }
//   }
// };

export {
  callShare4MiniProgram
};
