import { makeAutoObservable } from "mobx";
import API from "../api/index";
import { showShareGuide } from "@spark/share";
import store from "./store";
import { isIos, isWeChat, onUpdateShare } from "@/utils/share.ts";
import { GetCurrSkinId, getCustomShareId, getUrlParam, isMiniprogram, windowJumpUrl } from "@/utils/utils";
// import modalStore from "./modal";
import { Toast } from "@grace/ui";
function isEnterpriseWeChat() {
  //企业微信
  const userAgent = navigator.userAgent.toLowerCase();
  return /wxwork/.test(userAgent); // 检查是否包含 "wxwork"
}
const shareStore = makeAutoObservable({
  // 初始化分享
  initShare(){
    console.info('time-initShare',new Date().getTime())
    const skinId = GetCurrSkinId() || getCustomShareId() || 'index';
    console.log("分享默认渠道===", CFG.defaultChannel);
    const shareInfo = JSON.parse(store.frontVariable.shareInfo);
    if (skinId == 'index') { // 首页
      let shareUrl = `${CFG.domain}${CFG.shareUrl}`;
      shareUrl += `&ykCode=${CFG.workerCode || CFG.agentCode || ""}`
      shareUrl += `&channel=${CFG.defaultChannel}&agentCode=${CFG.agentCode || ""}&actPlatforms=${CFG.actPlatforms || ""}&actId=${CFG.actId || ""}`
      onUpdateShare({
        title: shareInfo?.title,
        content: shareInfo?.content,
        thumbnail: shareInfo?.thumbnail,
        url: `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(shareUrl)}`
      });
    } else {
      const inviteCode = getUrlParam("inviteCode");
      let shareUrl = `${CFG.domain}${CFG.shareUrl}${getUrlParam("inviteCode") ? '&inviteCode=' + getUrlParam("inviteCode") : ""}`;
      shareUrl += `&ykCode=${CFG.workerCode || CFG.agentCode || ""}`
      if (CFG.channel) shareUrl += `&channel=${CFG.defaultChannel}&agentCode=${CFG.agentCode || ""}&actPlatforms=${CFG.actPlatforms || ""}&actId=${CFG.actId || ""}`
      onUpdateShare({
        title: inviteCode && inviteCode != '' ? shareInfo?.titleInvite : shareInfo?.title,
        content: inviteCode && inviteCode != '' ? shareInfo?.contentInvite : shareInfo?.content,
        thumbnail: shareInfo?.thumbnail,
        url: `${CFG.domain}${CFG.indexLogin}${encodeURIComponent(shareUrl)}`
      });
    }
  },
  /** 普通分享 */
  async doShare() {
    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()) {
        //微通 （企业微信）
        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 {
        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.shareInfo);
    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?.titleInvite,
          });
          // 小程序
          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?.titleInvite}&desc=${shareInfo?.contentInvite}&imgUrl=${shareInfo?.imgUrl}`;
        } else {
          showShareGuide();
          onUpdateShare({
            title: shareInfo?.titleInvite,
            content: shareInfo?.contentInvite,
            thumbnail: shareInfo?.thumbnail,
            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?.titleInvite,
          description: shareInfo?.contentInvite || "",
          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;
    const { success, code, data, message } = await API.doAssist({ inviteCode: CFG.inviteCode });
    if (success) {
      Toast.show("助力成功～")
    } 
    sessionStorage.setItem("inviteCode", CFG.inviteCode);
    // history.replaceState({}, "", location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ""));
  },

  /** 奖品页唤端 */
  goAppPrize() {
    // windowJumpUrl(CFG.toAppPrizeUrl);
    //CFG.projectId三元判断为真，前面的是正式，需要修改的地方为中间页链接，可咨询东哥链接(奖品页唤端)  ios需要多encode一次
    const testCustomId = "Did1NjEwNzk"; //奖品-测试中间页
    const prodCustomId = "Did1NjExMjc"; //奖品-正式中间页
    //pd3ee4a37 为正式项目 需替换为正式项目ID
    // TODO
    windowJumpUrl(
      CFG.projectId == "pd3ee4a37"
        ? "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=613402&redirect_type=0&redirect_uri=${isIos()
            ? encodeURIComponent(
              encodeURIComponent(
                `${location.origin}/customShare/share?id=${prodCustomId}` +
                `&channel=${CFG.defaultChannel}&agentCode=${CFG.workerCode || CFG.agentCode}&actPlatforms=${CFG.actPlatforms
                }&actId=${CFG.actId}`
              )
            )
            : encodeURIComponent(
              `${location.origin}/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=613402&redirect_type=0&redirect_uri=${isIos()
            ? encodeURIComponent(
              encodeURIComponent(
                `${location.origin}/customShare/share?id=${testCustomId}` +
                `&channel=${CFG.defaultChannel}&agentCode=${CFG.workerCode || CFG.agentCode}&actPlatforms=${CFG.actPlatforms
                }&actId=${CFG.actId}`
              )
            )
            : encodeURIComponent(
              `${location.origin}/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;
