import { makeAutoObservable } from "mobx";
import API from "../api/index";
import { showShareGuide } from "@spark/share";
import store from ".";
import { isWeChat, onUpdateShare } from "@src/utils/share";
import { Toast } from "@spark/ui";
import { assistTip } from "@src/utils/constants";
import { isMiniprogram, windowJumpUrl } from "@src/utils/utils";
import modalStore from "./modal";
import { isIOS } from "@spark/utils";
function isEnterpriseWeChat() {
  //企业微信
  const userAgent = navigator.userAgent.toLowerCase();
  return /wxwork/.test(userAgent); // 检查是否包含 "wxwork"
}
const shareStore = makeAutoObservable({
  /** 普通分享 */
  async doShare(showGuide = true) {
    const shareInfo = JSON.parse(store.frontVariable.shareInfo);
    if (isWeChat()) {
      // 微信环境分享
      const _url = `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(
        `${CFG.domain}${CFG.shareUrl}&ykCode=${CFG.workerCode || CFG.agentCode || ""
        }&channel=${CFG.defaultChannel}&agentCode=${CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId
        }`
      )}`;
      console.info("分享链接", _url);

      if (isMiniprogram()) {
        const query = JSON.stringify({
          imgUrl: shareInfo?.imgUrl,
          isYKShare: "1",
          link: _url,
          title: shareInfo?.title,
        });
        // 小程序
        wx.miniProgram.navigateTo({
          url: `/subpackages/h5/miniProgramWebShare/index?YKMiniprogramShare=${encodeURIComponent(query)}`,
        });
      } else if (isEnterpriseWeChat()) {
        //微通 （企业微信）
        if(location.href.indexOf("test") > -1) {
          location.href = `https://mtest.picclife.cn/refactor-web/index.html?v=${Date.now()}#/duibaSharePage?link=${encodeURIComponent(
            _url
          )}&title=${shareInfo?.title}&desc=${shareInfo?.content}&imgUrl=${shareInfo?.imgUrl}`;
        } else {
          location.href = `https://m.picclife.cn/refactor-web/index.html?v=${Date.now()}#/duibaSharePage?link=${encodeURIComponent(
            _url
          )}&title=${shareInfo?.title}&desc=${shareInfo?.content}&imgUrl=${shareInfo?.imgUrl}`;
        }
      } else {
        showGuide && showShareGuide();
        //H5
        onUpdateShare({
          ...shareInfo,
          url: _url, // 带授权链接的活动链接
        });
      }
    } else {
      // app分享
      // app参数
      const _url = `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(
        `${CFG.domain}${CFG.shareUrl}&ykCode=${CFG.workerCode || CFG.agentCode || ""}&channel=${CFG.defaultChannel}&agentCode=${CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId}`
      )}`;
      console.info("分享链接", _url);
      if (CFG.channel == "1") {
        //管家
        const params = {
          title: shareInfo.title,
          description: shareInfo.content || "",
          shareUrl: _url,
          thumbUrl: shareInfo.thumbnail,
          shareType: "0", // 1分享网页 2分享图片 3分享视频4分享音乐 5分享文本
        };
        window.PICCLifeJsBrage.callNative({
          module: "Share",
          method: "options",
          params: JSON.stringify(params),
          callback: "",
        });
      }
      if (CFG.channel == "6") {
        //e通
        const params = {
          title: shareInfo.title,
          description: shareInfo.content || "",
          url: _url,
          thumbImage: shareInfo.thumbnail,
        };
        window.inAppShare({
          type: "shareLink",
          activity: "richMan",
          params: JSON.stringify(params),
        });
      }
    }
  },

  /** 邀请好友 */
  async doInvite() {
    const shareInfo = JSON.parse(store.frontVariable.shareInfoInvite);
    const { success, data } = await API.getInviteCode();
    const _url = `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(
      `${CFG.domain}${CFG.shareUrl}${CFG.workerCode ? `&ykCode=${CFG.workerCode}` : ""}&channel=${CFG.defaultChannel}`
      + (data?.inviteCode ? `&inviteCode=${data.inviteCode}` : "")
      + `&agentCode=${CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId}`
    )}`;
    console.info("邀请链接>>>", _url);
    // const { success:success2, data:data2 } = await API.getLongLinkQrcode({
    //   width: 220,
    //   height: 220,
    //   content: encodeURIComponent(_url),
    // });
    // return data2;
    if (success) {
      if (isWeChat()) {
        // 微信环境分享
        const _url = `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(
          `${CFG.domain}${CFG.shareUrl}${CFG.workerCode ? `&ykCode=${CFG.workerCode}` : ""}&channel=${CFG.defaultChannel}`
          + (data?.inviteCode ? `&inviteCode=${data.inviteCode}` : "")
          + `&agentCode=${CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId}`
        )}`;
        console.info("邀请链接>>>", _url);
        if (isMiniprogram()) {
          const query = JSON.stringify({
            imgUrl: shareInfo?.imgUrl,
            isYKShare: "1",
            link: _url,
            title: shareInfo?.title,
          });
          // 小程序
          wx.miniProgram.navigateTo({
            url: `/subpackages/h5/miniProgramWebShare/index?YKMiniprogramShare=${encodeURIComponent(query)}`,
          });
        } else if (isEnterpriseWeChat()) {
          location.href = `https://m.picclife.cn/refactor-web/index.html?v=${Date.now()}#/duibaSharePage?link=${encodeURIComponent(
            _url
          )}&title=${shareInfo?.title}&desc=${shareInfo?.content}&imgUrl=${shareInfo?.imgUrl}`;
        } else {
          // showShareGuide('点击右上角...分享', 0.7, 0, () => {
          //   const _url1 = `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(
          //     `${CFG.domain}${CFG.shareUrl}${CFG.workerCode ? `&ykCode=${CFG.workerCode}` : ""
          //     }${`&channel=${CFG.defaultChannel}`}` +
          //     `&agentCode=${CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId}`
          //   )}`;
          //   onUpdateShare({
          //     ...shareInfo,
          //     url: _url1, // 带授权链接的活动链接
          //   });
          // });
          showShareGuide();
          onUpdateShare({
            ...shareInfo,
            url: _url, // 带授权链接的活动链接
          });
        }
      } else {
        // app分享
        const _url = `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(
          `${CFG.domain}${CFG.shareUrl}${CFG.workerCode ? `&ykCode=${CFG.workerCode}` : ""}&channel=${CFG.defaultChannel}`
          + (data?.inviteCode ? `&inviteCode=${data.inviteCode}` : "")
          + `&agentCode=${CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId}`
        )}`;
        console.info("分享链接>>>", _url);
        // app参数
        const params = {
          title: shareInfo.title,
          description: shareInfo.content || "",
          shareUrl: _url,
          thumbUrl: shareInfo.thumbnail,
          shareType: "0", // 1分享网页 2分享图片 3分享视频4分享音乐 5分享文本
        };
        window.PICCLifeJsBrage.callNative({
          module: "Share",
          method: "options",
          params: JSON.stringify(params),
          callback: "",
        });
      }
    }
  },

  /** 助力 */
  async doAssist() {
    if (!CFG.inviteCode) return false;
    console.info("进入助力！！！");
    if (sessionStorage.getItem("inviteCode")) return false;
    console.info("111111进入助力！！！");
    const { success, code, message } = await API.doAssist({ inviteCode: CFG.inviteCode });
    console.info(success, message, code, "111111进入助力！！！");
    if (success) {
      modalStore.pushPop("AssistSucPanel");
      // Toast("助力成功～")
    } else {
      modalStore.pushPop("AssistFailPanel", {
        message, code
      });
    }
    sessionStorage.setItem("inviteCode", CFG.inviteCode);
    history.replaceState({}, "", location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ""));
  },

  /** 奖品页唤端 */
  goAppPrize() {
    // windowJumpUrl(CFG.toAppPrizeUrl);
    //CFG.projectId三元判断为真，前面的是正式，需要修改的地方为中间页链接，可咨询东哥链接(奖品页唤端)  ios需要多encode一次
    const testCustomId = "Did1NjAyNDc";
    const prodCustomId = "Did1NjA0NTU";

    const isProd = store.homeInfo?.prod !== null ? (store.homeInfo?.prod || false) : true
    windowJumpUrl(
      // CFG.projectId == "p50735695"
      isProd
        ? "https://lifeapp.picclife.cn/portal/app_manager/downloadapps.html?operate_link=" +
        encodeURIComponent(
          `https://lifeapp-api.picclife.cn/lifeapi/lifeapp-svc-gw/api/auth_code/authorize/v1?activity_code=613102&redirect_type=0&redirect_uri=${isIOS
            ? encodeURIComponent(
              encodeURIComponent(
                `https://96094-activity.dexfu.cn/customShare/share?id=${prodCustomId}` +
                `&channel=${CFG.defaultChannel}&agentCode=${CFG.workerCode || CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId}`
              )
            )
            : encodeURIComponent(
              `https://96094-activity.dexfu.cn/customShare/share?id=${prodCustomId}` +
              `&channel=${CFG.defaultChannel}&agentCode=${CFG.workerCode || CFG.agentCode}&actPlatforms=${CFG.actPlatforms}&actId=${CFG.actId}`
            )
          }`
        ) + "&isBindManager=1&isNeedAuth=1&operate_type=3"
        : "https://lifeapp-test.picclife.cn/portal-web/app_manager/downloadapps.html?operate_link=" +
        encodeURIComponent(
          `https://lifeapp-api-test.picclife.cn/lifeapi/lifeapp-svc-rel-gw/api/auth_code/authorize/v1?activity_code=613102&redirect_type=0&redirect_uri=${isIOS
            ? encodeURIComponent(
              encodeURIComponent(
                `https://96094-activity.dexfu.cn/customShare/share?id=${testCustomId}` +
                `&channel=${CFG.defaultChannel}&agentCode=${CFG.workerCode || CFG.agentCode}&actPlatforms=${CFG.actPlatforms
                }&actId=${CFG.actId}`
              )
            )
            : encodeURIComponent(
              `https://96094-activity.dexfu.cn/customShare/share?id=${testCustomId}` +
              `&channel=${CFG.defaultChannel}&agentCode=${CFG.workerCode || CFG.agentCode}&actPlatforms=${CFG.actPlatforms
              }&actId=${CFG.actId}`
            )
          }`
        ) + "&isBindManager=1&isNeedAuth=1&operate_type=3"
    );
  },

});
export default shareStore;
