// APP方法封装
import { localPath } from "../config/env";
import * as YdShare from "./share";
import Bridge from "./iosBridge";
import nativeJson from "./nativeInt";
const APP: { [funName: string]: any } = {
  middleFun(): any {
    // if (!window.tool.isYuedong()) {
    //     window.global.toast("请打开悦动圈app进行操作");
    //     return
    // }
    let ag: string[] = [].slice.apply(arguments);
    let funName = ag.shift() as string;
    return APP[funName](...ag);
  },
  /**
   * 在外部跳转app页面，参数需要encode。http://wiki.17yund.me/doku.php?id=ios_universallink
   * ios最好使用vc_name！
   * android使用native_int
   * @param {*} url 跳转到网页的链接
   * @param {*} from 来源
   * @param {*} action 调本地界面
   * @param {*} vc_name 界面类名
   * @param {*} vc_params 需要带给界面的参数（json字符串）
   * @param {*} vc_direct_url 这种模式可以直接找ios组员给参数值
   * @param {*} native_int 方式 数字
   * @param {*} native_params 方式 参数
   * @param {*} marketDetectUrl 下载监测链接
   * @param {*} downloadPage 下载页跳转。market：跳转到应用市场，home：跳转到官网首页。ios都是跳官网，因为同时弹出app store和app体验不好
   */
  jumpAppPage(urlObj: {
    url: any;
    from: any;
    action: any;
    vc_name: any;
    vc_params: any;
    vc_direct_url: any;
    native_int: any;
    native_params: any;
    marketDetectUrl: any;
    downloadPage?: string | undefined;
  }) {
    let {
      url,
      from,
      action,
      vc_name,
      vc_params,
      vc_direct_url,
      native_int,
      native_params,
      marketDetectUrl,
      downloadPage = "home",
    } = urlObj;
    if (window.tool.isIosWeb()) {
      // 使用 universal link打开app
      let jumpUrl = `https://uljump.51yund.com/openApp?downloadPage=${downloadPage}${
        url ? "&url_inside=" + encodeURIComponent(url) : ""
      }${from ? "&from=" + encodeURIComponent(from) : ""}${
        action ? "&action=" + encodeURIComponent(action) : ""
      }${action === "to_local_vc" ? "&vc_open_type=push" : ""}${
        vc_name ? "&vc_name=" + encodeURIComponent(vc_name) : ""
      }${
        vc_params
          ? "&vc_params=" + encodeURIComponent(JSON.stringify(vc_params))
          : ""
      }${
        vc_direct_url
          ? "&vc_direct_url=" + encodeURIComponent(vc_direct_url)
          : ""
      }${native_int ? "&native_int=" + encodeURIComponent(native_int) : ""}${
        native_params
          ? "&native_params=" +
            encodeURIComponent(JSON.stringify(native_params))
          : ""
      }${
        marketDetectUrl
          ? "&marketDetectUrl=" +
            encodeURIComponent(JSON.stringify(marketDetectUrl))
          : ""
      }`;
      window.location.href = jumpUrl;
    } else if (window.tool.isAndroidWeb()) {
      // 使用deeplink打开app
      window.location.href = `https://uljump.51yund.com/openApp?downloadPage=${downloadPage}${
        url ? "&open_url=" + encodeURIComponent(url) : ""
      }${from ? "&from=" + encodeURIComponent(from) : ""}${
        native_int ? "&native_int=" + encodeURIComponent(native_int) : ""
      }${
        native_params
          ? "&native_params=" +
            encodeURIComponent(JSON.stringify(native_params))
          : ""
      }${
        marketDetectUrl
          ? "&marketDetectUrl=" +
            encodeURIComponent(JSON.stringify(marketDetectUrl))
          : ""
      }`;
    } else {
      // pc端打开
      window.location.href = "https://www.51yund.com/?from=open_app";
    }
  },
  /******************************************************************************************
   * **********客户端交互url*********
   * 函数名使用"yd"开始跟其他功能函数区分
   * ******************************************************************************************/
  //打开nativeInt 对应的页面，通过名字打开的方式
  openNativeInt(name: string | number, parm: any = {}) {
    if (!window.tool.isYuedong())
      return window.global.toast("亲，请在app内打开哦~");
    let nativeObj = (nativeJson as any)[name];
    if (!nativeObj) {
      return window.global.toast("请检查传入的NativeInt名字");
    }
    let needArr = nativeObj.need;
    if (needArr && needArr.length > 0) {
      //需要传参数
      for (let m = 0; m < needArr.length; m++) {
        let values = parm[needArr[m].key]; //目标值
        if (needArr[m].require && !values) {
          //需要填而没有填
          return window.global.toast(needArr[m].key + "为必填项，请检查");
        }
        if (values && typeof values !== needArr[m].type) {
          //填了而类型不对
          return window.global.toast(
            needArr[m].key + "类型必须为" + needArr[m].type
          );
        }
      }
    }
    let paramStr = "";
    for (let i in parm) {
      paramStr += "&" + i + "=" + parm[i];
    }
    if (window.tool.isIosWeb()) {
      let code = nativeObj.code || nativeObj.ios;
      // 这里临时注释掉，ios新方法里没有注册这个
      // if(checkIosBridgeVailable()){
      //     iosBridgeCall('native_int_jump', Object.assign({native_int: code}, parm))
      //     return;
      // }
      let path =
        "/local_call?local_action=native_int_jump&native_int=" +
        code +
        paramStr;
      window.tool.iframeLocalCall(path);
      return;
    } else {
      let nativeInt = nativeObj.code || nativeObj.android;
      if (
        window.YDJSInterface &&
        "jumpLocalByActionInfo" in window.YDJSInterface
      ) {
        let parmObj: any = {
          native_int: nativeInt,
        };
        if (paramStr) {
          parmObj.params = paramStr.slice(1); //去掉第一位的&
        }
        window.YDJSInterface.jumpLocalByActionInfo(JSON.stringify(parmObj));
        return;
      }
    }
    window.global.toast("亲，请升级悦动圈app版本");
  },
  //打开nativeInt页面，通过接口返回code的方式打开
  openNativeIntByCode(obj: any = {}) {
    if (!window.tool.isYuedong())
      return window.global.toast("亲，请在app内打开哦~");
    if (window.tool.isIosWeb()) {
      let path =
        "/local_call?local_action=native_int_jump&native_int=" + obj.native_int;
      if (obj.params) path += "&" + obj.params;
      window.tool.iframeLocalCall(path);
      return;
    } else {
      if (
        window.YDJSInterface &&
        "jumpLocalByActionInfo" in window.YDJSInterface
      ) {
        window.YDJSInterface.jumpLocalByActionInfo(JSON.stringify(obj));
        return;
      }
    }
    window.global.toast("亲，请升级悦动圈app版本");
  },
  //app打开微信小程序
  openMiniApp(originId: any, path: any, type: string) {
    //type 0:正式，1:测试，2:预览
    if (
      window.tool.isAndroidWeb() &&
      "jumpWxMiniProgram" in window.YDJSInterface
    ) {
      window.YDJSInterface.jumpWxMiniProgram(
        String(originId),
        String(path),
        parseInt(type)
      );
      return;
    }
    if (window.tool.isIosWeb() && checkIosBridgeVailable()) {
      iosBridgeCall("open_wechat_mini_program", {
        user_name: originId,
        path: path,
        type: type,
      });
      return;
    }
    window.global.toast("亲，请升级悦动圈app版本");
  },
  goMyFitness() {
    if (window.tool.isYuedong()) {
      if (window.tool.isIosWeb()) {
        let path =
          "/local_call?local_action=to_local_vc&&arg0=YDFitUserPlanViewController&arg1=push";
        window.tool.iframeLocalCall(path);
      } else {
        window.YDJSInterface.jumpLocalByActionInfo("{native_int: 601}");
      }
    }
  },

  // 去资讯tab
  goInfoTab() {
    if (window.tool.isYuedong()) {
      if (window.tool.isIosWeb()) {
        window.tool.iframeLocalCall(
          `/local_call?local_action=to_local_vc&vc_direct_url=%2FYDBaseTabBarController%2FYDCTCircleRootViewController`
        );
        return;
      } else if (
        window.YDJSInterface &&
        "jumpLocalByActionInfo" in window.YDJSInterface
      ) {
        let obj = {
          native_int: 503,
        };
        window.YDJSInterface.jumpLocalByActionInfo(JSON.stringify(obj));
        return;
      }
      window.global.toast("亲，请升级悦动圈app版本");
    }
  },

  setTitle(title: string) {
    if (!window.tool.isIosWeb() || !window.tool.isYuedong()) return;
    let path = "/local_call?local_action=set_vc_title&arg0=" + title;
    window.tool.iframeLocalCall(path);
  },

  shareBitmap(obj: { data: any; callback: any }) {
    let shareObj = obj.data;
    let cabk = obj.callback;
    if (!shareObj.base64Img) {
      window.global.toast("分享图片暂未生成!");
      return;
    }
    if (window.tool.isAndroidWeb()) {
      var pic = shareObj.base64Img.replace(/^.*?,/, "");
      if (
        window.YDJSInterface &&
        "shareBase64ImgByPopupWindow" in window.YDJSInterface
      ) {
        window.YDJSInterface.shareBase64ImgByPopupWindow(
          pic,
          shareObj.shareTitle,
          shareObj.shareContent,
          shareObj.shareUrl
        );
      } else {
        window.global.toast("请升级悦动圈app分享!");
      }
      return;
    }
    shareObj.sharePicUrl = shareObj.base64Img;
    YdShare.setSimpleShare(shareObj, function () {
      if (cabk) {
        cabk();
      }
    });
    YdShare.onShare(this);
  },
  // 获取app定位
  ydGetPosition(cb: any) {
    if (window.tool.isYuedong()) {
      APP.ydGetPositionCb = cb;
      let version = window.tool.version;
      if (window.tool.isAndroidWeb()) {
        if (window.YDJSInterface && "requestLocation" in window.YDJSInterface) {
          window.YDJSInterface.requestLocation();
        }
      } else {
        if (checkIosBridgeVailable()) {
          let cbSuccAbj = { callback: "onLocationRes" };
          iosBridgeCall("request_location", cbSuccAbj);
          return;
        }
        let url =
          localPath +
          "/local_call?local_action=request_location&callback=onLocationRes";
        window.tool.iframeLocalCall(url);
      }
      let timer: any = setTimeout(() => {
        if (APP.ydGetPositionCb) {
          //客户端没有回调，可能是被禁止获取定位
          window.tool.getBrowserPosition(cb);
        }
        timer = null;
      }, 4000);
    } else {
      window.tool.getBrowserPosition(cb);
    }
  },
  // 打开新窗口
  openUrlByNewWindow: function (url: string) {
    if (!url) return;
    if (url.indexOf("http:") == -1 && url.indexOf("https:") == -1) {
      url = document.location.protocol + "//" + document.domain + url;
    }
    if (window.tool.isYuedong()) {
      if (window.YDJSInterface && "openWindow" in window.YDJSInterface) {
        window.YDJSInterface.openWindow(url);
        return;
      }
      if (window.tool.isIosWeb()) {
        if (checkIosBridgeVailable()) {
          iosBridgeCall("open_url_new_window", { arg0: url });
          return;
        }
        url = encodeURIComponent(url);
        let path = "/local_call?local_action=open_url_new_window&arg0=" + url;
        window.tool.iframeLocalCall(path);
        return;
      }
    }
    window.location.href = url;
  },
  ydVisitUserInfo(args: any) {
    if (!window.tool.isYuedong()) {
      window.global.toast("亲，请在app内打开哦~");
      return;
    }
    if (window.tool.isIosWeb() && checkIosBridgeVailable()) {
      iosBridgeCall("personinfo", args.data);
      return;
    }
    window.location.href =
      "/local_call?local_action=personinfo&arg0=" + args.data.arg0;
  },
  //跳转心肺复苏采集详情页
  ydHeartLung(nativeInt: any, enterpriseId: any) {
    if (window.tool.isIosWeb()) {
      let path = `/local_call?local_action=native_int_jump&native_int=${nativeInt}&enterprise_id=${enterpriseId}`;
      window.tool.iframeLocalCall(path);
      return;
    }
    if (
      window.YDJSInterface &&
      "openLocalPageAndEnterprise" in window.YDJSInterface
    ) {
      window.YDJSInterface.openLocalPageAndEnterprise(nativeInt, enterpriseId);
      return;
    }
    window.global.toast("亲，请升级悦动圈app版本");
  },
  //跳转课外体育首页
  ydHome() {
    if (window.tool.isIosWeb() && checkIosBridgeVailable()) {
      iosBridgeCall("jump2footprint", { arg0: 0 });
      return;
    }
    window.location.href = "/local_call?local_action=jumpToAppMain&arg0=0";
  },
  //开始走路
  ydStartWalk() {
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("jump2footprint", { arg0: 0 });
        return;
      }
    }
    window.location.href = "/local_call?local_action=jump2footprint&arg0=0";
  },
  //开始跑步-室外跑
  ydStartRun(fromVal: string) {
    if (window.tool.isAndroidWeb()) {
      fromVal = fromVal || "web";
      window.location.href =
        "/local_call?local_action=start_run&from=" + fromVal;
      return;
    }
    iosGoSport(0);
  },
  //开始跑步-室内跑
  ydStartRunInRoom(fromVal: string) {
    fromVal = fromVal || "web";
    if (window.tool.isAndroidWeb()) {
      if (window.YDJSInterface && "startRunInRoom" in window.YDJSInterface) {
        window.YDJSInterface.startRunInRoom(fromVal);
        return;
      }
    }
    if (
      window.tool.isIosWeb() &&
      window.tool.versionCompare(window.tool.version, "5.10.3") >= 0
    ) {
      APP.openNativeInt("StartRunInRoom");
      return;
    }
    window.global.toast(
      "您暂未更新APP，无法体验此功能。请下载最新版悦动圈APP后，重新尝试。"
    );
  },
  // 去徒步（android不能直接开始）
  ydStartHike(fromVal: string) {
    if (window.tool.isAndroidWeb()) {
      // android新版本直接开始
      if (window.tool.versionCompare(window.tool.version, "3.3.4.2.0") >= 0) {
        fromVal = fromVal || "web";
        window.location.href =
          "/local_call?local_action=start_hike&from=" + fromVal;
        return;
      }
      if (window.YDJSInterface && "startHikeSport" in window.YDJSInterface) {
        fromVal = fromVal || "web";
        window.YDJSInterface.startHikeSport(fromVal);
        return;
      }
    }
    iosGoSport(6);
  },
  // 去骑行
  ydStartRide(fromVal: string) {
    if (window.tool.isAndroidWeb()) {
      fromVal = fromVal || "web";
      window.location.href =
        "/local_call?local_action=sport_ride&from=" + fromVal;
      return;
    }
    iosGoSport(3);
  },
  // 跳转平板撑
  ydStartPlank(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 29,
        page_type: 0,
        move_type: 2,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.1",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // 跳转俯卧撑
  ydStartPushUps(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 33,
        page_type: 0,
        move_type: 2,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.1",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // 跳转开合跳
  ydStartOACJump(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 2,
        page_type: 0,
        move_type: 1,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.1",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // 跳转仰卧起坐
  ydStartSitUps(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 40,
        page_type: 0,
        move_type: 2,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.7",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // 跳转引体向上
  ydStartPullUps(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 44,
        page_type: 0,
        move_type: 1,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.7",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // 跳转跳绳
  ydStartJumpSkip(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 45,
        page_type: 0,
        move_type: 1,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.7",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // 跳转左体侧运动
  ydStartLeftSport(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 4,
        page_type: 0,
        move_type: 1,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.7",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // 跳转右体侧运动
  ydStartRightSport(params: any) {
    let _params = Object.assign(
      {},
      {
        video_id: 5,
        page_type: 0,
        move_type: 1,
        android_ver: "3.3.2.2.2",
        ios_ver: "5.1.7",
      },
      params
    );
    APP.ydStartAIMatch(_params);
  },
  // TODO 运动类型会越来越多，需要统一份配置，不做特殊函数处理
  // 跳转AI运动开始界面
  ydStartAIMatch(params: {
    video_id: any;
    page_type: any;
    match_id: any;
    mode: any;
    limit_times: any;
    complete_tip: any;
    move_type: any;
    android_ver: any;
    ios_ver: any;
    difficulty: any;
    groupRunId: any;
    group_id: any;
    more_params: any;
  }) {
    // videoId平板撑29 俯卧撑33,开合跳 2
    if (!window.tool.isYuedong())
      return window.global.toast(
        "本功能需要在悦动圈APP内使用。请下载最新版悦动圈APP后，重新尝试。"
      );
    let videoId = Number(params.video_id); // 视频ID
    let pageType = Number(params.page_type); // 非C端赛事类型 0，平板撑C端赛事类型 pageType=5，俯卧撑C端赛事类型pageType=6
    let matchId = params.match_id ? Number(params.match_id) : 0; // C端赛事活动ID 此处不传给iOS B端传0
    let mode = params.mode ? Number(params.mode) : 0; // AI运动模式 0 普通模式 2 限时模式
    let limitTimes =
      params.limit_times && mode ? Number(params.limit_times) : 0; // 多长时间自动结束
    let completeTip = params.complete_tip ? params.complete_tip : ""; // 结束后的提示
    let moveType = Number(params.move_type); // 健身动作：1-竖向；2-横向
    let androidVer = params.android_ver ? params.android_ver : "0"; // 所需Android版本
    let iosVer = params.ios_ver ? params.ios_ver : "0"; // 所需ios版本
    let difficulty = params.difficulty ? Number(params.difficulty) : 0; // 难易模式 0 普通 1 简单 (安卓新增)
    let groupRunId = params.groupRunId ? Number(params.groupRunId) : 0; // 广播体操id
    let group_id = params.group_id ? Number(params.group_id) : 0;
    let more_params = params.more_params
      ? JSON.stringify(params.more_params)
      : JSON.stringify({}); //其他参数的对象

    // 跳转安卓的新方法
    if (
      window.YDJSInterface &&
      "toAICoachSingleTrainActivity" in window.YDJSInterface &&
      window.tool.versionCompare(window.tool.version, androidVer) >= 0
    ) {
      if (window.tool.versionCompare(window.tool.version, "5.9.0.2.5") >= 0) {
        let _params = {
          video_id: videoId,
          match_id: matchId,
          page_type: pageType,
          limit_time: limitTimes,
          mode: mode,
          complete_tip: completeTip,
          move_type: moveType,
          more_params: more_params,
          difficulty: difficulty,
          group_id: group_id,
        };
        window.YDJSInterface.toAICoachSingleTraining(JSON.stringify(_params));
      } else if (
        window.tool.versionCompare(window.tool.version, "5.7.0.0.1") >= 0
      ) {
        window.YDJSInterface.toAICoachSingleTrainActivity(
          videoId,
          matchId,
          pageType,
          limitTimes,
          moveType,
          difficulty,
          mode,
          groupRunId,
          more_params
        );
      } else {
        window.YDJSInterface.toAICoachSingleTrainActivity(
          videoId,
          matchId,
          pageType,
          limitTimes,
          moveType,
          difficulty,
          mode,
          groupRunId
        );
      }
      return;
    }

    let _params = {
      video_id: videoId,
      limit_times: limitTimes,
      mode: mode,
      complete_tip: completeTip,
      move_type: moveType,
      more_params: more_params,
      video_group_id: group_id,
    };
    // 兼容iOS版本问题
    if (
      window.tool.isIosWeb() &&
      window.tool.versionCompare(window.tool.version, "5.8.5") == 0
    ) {
      APP.openNativeInt(
        "AIMatch",
        Object.assign({}, _params, { group_id: videoId })
      );
      return;
    }
    if (
      window.tool.isIosWeb() &&
      window.tool.versionCompare(window.tool.version, iosVer) >= 0
    ) {
      APP.openNativeInt("AIMatch", _params);
      return;
    }
    window.global.toast(
      "您暂未更新APP，无法体验此功能。请下载最新版悦动圈APP后，重新尝试。"
    );
  },
  /***
   * 跳转运动记录封装
   * name值有：
   * runSportRcord 跳转跑步运动记录
   * ridingSportRcord 跳转骑行运动记录
   * toreroSportRcord 跳转徒步运动记录
   * fitnessSportRcord 跳转健身运动记录
   * stepSportRcord 跳转计步运动记录
   */
  ydRecordMatch(name: any) {
    APP.openNativeInt(name);
  },
  ydAiRecord() {
    if (window.tool.isIosWeb()) {
      let path =
        "/local_call?local_action=to_local_vc&arg0=YDAICoachHistoryRootViewController";
      window.tool.iframeLocalCall(path);
      return;
    }
    if (
      window.YDJSInterface &&
      "toAiCoachHistoryList" in window.YDJSInterface
    ) {
      window.YDJSInterface.toAiCoachHistoryList();
      return;
    }
    window.global.toast("亲，请升级悦动圈app版本");
  },
  // 跳转AI运动动作列表（可用于开始AI运动）
  ydGotoAICoach() {
    if (window.tool.isIosWeb()) {
      let path = "/local_call?local_action=native_int_jump&native_int=691";
      window.tool.iframeLocalCall(path);
      return;
    }
    if (window.YDJSInterface && "toAICoach" in window.YDJSInterface) {
      window.YDJSInterface.toAICoach();
      return;
    }
    if (window.tool.isYuedong()) {
      window.global.toast("亲，请升级悦动圈app版本");
      return;
    }
    window.global.toast(
      "亲，本功能需要在悦动圈APP内使用。请下载最新版悦动圈APP后，重新尝试。"
    );
  },
  //打开话题落地页 例子：#零零落落#
  ydGoTheme(args: { data: { themeId: string; headerViewTitle: any } }) {
    let circleId: any = 0;
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "goToTopicListToEditor" in window.YDJSInterface
    ) {
      window.YDJSInterface.goToTopicListToEditor(
        parseInt(args.data.themeId),
        args.data.headerViewTitle,
        parseInt(circleId),
        true,
        true,
        true
      );
      return;
    }
    if (window.tool.isIosWeb()) {
      let themeObj = args.data;
      let topicIdObj: any = {
        showProgressForEditor: 1,
        confineTapForEditor: 1,
        aimCirclesForEditor: circleId,
      };
      Object.assign(topicIdObj, themeObj);
      topicIdObj = JSON.stringify(topicIdObj);
      topicIdObj = encodeURIComponent(topicIdObj);
      if (checkIosBridgeVailable()) {
        let params = {
          arg0: "YDTopicViewController",
          arg1: 1,
          arg2: topicIdObj,
        };
        iosBridgeCall("to_local_vc", params);
        return;
      }
      window.location.href =
        "/local_call?local_action=to_local_vc&arg0=YDTopicViewController&arg1=push&arg2=" +
        topicIdObj;
      return;
    }
    window.global.toast("亲，请升级悦动圈app版本");
  },
  //去发布动态 支持带图
  ydAddImgToClentTopic(args: { data: any }) {
    // argsObj = {
    //     circleId:1,//ios 话题发布到的圈子ID 带上id限制只能发到该圈子 不带可以选择用户加入的任何圈子
    //     //android则根据androidCanSelectCircle来判断是否可以选择圈子  androidCanSelectCircle=false的时候必须要带circleId 不然就不能发布成功啦 因为没有圈子可以选
    //     iosShowProgress:1,//是否显示发布动画
    //     base64Array:[],//base64图片数组
    //     urlArray:[],//url图片数组 安卓需要搭配androidPhotoIds一起使用才行
    //     androidPhotoIds:[],//安卓话题发布图片 urlArray数组 与photoId数组需一一对应
    //     androidShowProgress:true,//是否跳转进度页
    //     androidCanSelectTopic:true,//是否可以选择话题
    //     androidCanSelectCircle:true,//是否可以选择圈子
    //     aimTagItemObj:{themeId:"",themeTitle:""}//需要带话题发布的情况下 带上该对象
    // }
    let argsObj = args.data;
    let version = window.tool.version;
    if (window.YDJSInterface) {
      let formatBase64Arr: any = [];
      if (argsObj.base64Array.length > 0) {
        argsObj.base64Array.forEach(
          (element: string, index: string | number) => {
            formatBase64Arr[index] = element.replace(/^.*?,/, "");
          }
        );
      }
      let themeId = parseInt(argsObj.aimTagItemObj.sub_theme_id) || 0;
      let themeTitle = "#" + argsObj.aimTagItemObj.tag + "#" || "";
      if (
        formatBase64Arr.length > 0 ||
        (argsObj.urlArray.length > 0 && argsObj.androidPhotoIds.length > 0)
      ) {
        if ("publishPhotoDynamicToEditor" in window.YDJSInterface) {
          window.YDJSInterface.publishPhotoDynamicToEditor(
            themeId,
            themeTitle,
            parseInt(argsObj.circleId),
            argsObj.androidShowProgress,
            argsObj.androidCanSelectTopic,
            argsObj.androidCanSelectCircle,
            formatBase64Arr,
            argsObj.urlArray,
            argsObj.androidPhotoIds
          );
        }
        return;
      }
      if ("publishDynamicToEditor" in window.YDJSInterface) {
        window.YDJSInterface.publishDynamicToEditor(
          themeId,
          themeTitle,
          parseInt(argsObj.circleId),
          argsObj.androidShowProgress,
          argsObj.androidCanSelectTopic,
          argsObj.androidCanSelectCircle
        );
        return;
      }
    }
    if (
      window.tool.isIosWeb() &&
      window.tool.versionCompare(version, "4.6.6") >= 0
    ) {
      var imagesFromWeb = {
        imagesBase64Array: argsObj.base64Array,
        imagesURLArray: argsObj.urlArray,
      };
      let aimTagItemObj = JSON.stringify(argsObj.aimTagItemObj);
      if (argsObj.base64Array.length > 0 || argsObj.urlArray.length > 0) {
        aimTagItemObj = JSON.parse(aimTagItemObj);
      }
      var topicIdObj: any = {
        commingSourceType: 7,
        showProgressVCWhenUpload: argsObj.iosShowProgress,
        aimTagItem: aimTagItemObj,
        aimCircleIds: argsObj.circleId,
        imagesFromWeb: imagesFromWeb,
      };
      topicIdObj = JSON.stringify(topicIdObj);
      topicIdObj = encodeURIComponent(topicIdObj);
      if (checkIosBridgeVailable()) {
        let params = {
          arg0: "YDCircleEditorViewController",
          arg1: "push",
          arg2: topicIdObj,
        };
        iosBridgeCall("to_local_vc", params);
        return;
      }
      let path =
        "/local_call?local_action=to_local_vc&arg0=YDCircleEditorViewController&arg1=push&arg2=" +
        topicIdObj;
      window.tool.iframeLocalCall(path);
      return;
    }
    window.global.toast("亲，请升级悦动圈app版本");
  },
  // 客户端下载base64图片
  ydDownloadImgBase64(base64: string) {
    if (window.YDJSInterface && "saveBase64Image" in window.YDJSInterface) {
      window.YDJSInterface.saveBase64Image(base64);
      window.global.toast("图片下载中，请下拉系统菜单查看进度~");
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("download_img", { args0: base64 });
        return;
      }
      let path = "/local_call?local_action=download_img&args0=" + base64;
      window.tool.iframeLocalCall(path);
      return;
    }
    window.global.toast("请升级版本后重试");
  },
  //客户端下载图片链接
  ydDownloadImgSrc(picUrl: string) {
    // 下载图片后保存到相册
    if (
      window.YDJSInterface &&
      "downloadImageToAlbum" in window.YDJSInterface
    ) {
      window.YDJSInterface.downloadImageToAlbum(picUrl);
      return;
    }
    // 下载图片后，但是没有保存到相册
    if (window.YDJSInterface && "downloadBySystem" in window.YDJSInterface) {
      window.YDJSInterface.downloadBySystem(picUrl);
      window.global.toast("图片下载中，请下拉系统菜单查看进度~");
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("download_img", { args0: picUrl });
        return;
      }
      let path = "/local_call?local_action=download_img&args0=" + picUrl;
      window.tool.iframeLocalCall(path);
      return;
    }
    window.global.toast("请升级版本后重试");
  },
  //web跳转客户端账号绑定
  ydGoBind() {
    if (window.tool.isAndroidWeb()) {
      window.location.href = "/local_call?local_action=account_bind";
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("account_bind");
        return;
      }
      window.location.href = "/local_call?local_action=account_bind";
      return;
    }
    window.global.toast("当前软件版本不支持跳转，请升级最新版本");
  },
  //web跳转客户端邀请好友
  ydInviteNew(circleId: string) {
    if (window.tool.isAndroidWeb()) {
      window.location.href =
        "/local_call?local_action=invite_friend_circle&arg0=" + circleId;
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("invite_friend_circle", { args0: circleId });
        return;
      }
      window.location.href = "/local_call?local_action=invite_friend_circle";
      return;
    }
    window.global.toast("当前软件版本不支持跳转，请升级最新版本");
  },
  //获取设备信息
  ydGetDeviceInfo() {
    let deviceInfo = {};
    if (window.tool.isIosWeb()) {
      deviceInfo = {
        ver: window.tool.getCookieValue("ver"), //app版本号
        device_id: window.tool.getCookieValue("device_id"), //app版本号
        network_status: window.tool.getCookieValue("network_status"), //网络状况 //-1 未知   0 不可达没网络  1 在蜂窝网（2，3，4G等）  2 WiFi
        language: window.tool.getCookieValue("language"),
        timezone: window.tool.getCookieValue("timezone"),
        locale: window.tool.getCookieValue("locale"), //国家
        phone_type: window.tool.getCookieValue("phone_type"), //手机型号
        os_version: window.tool.getCookieValue("os_version"), //系统版本
        longitude: window.tool.getCookieValue("longitude"),
        latitude: window.tool.getCookieValue("latitude"),
        timestamp: window.tool.getCookieValue("timestamp"),
        scale: window.tool.getCookieValue("scale"), //屏幕倍率
        screen_width: window.tool.getCookieValue("screen_width"), //屏幕宽度 单位为屏幕点，实际像素为screen_width*scale
        screen_height: window.tool.getCookieValue("screen_height"), //屏幕高度 单位为屏幕点，实际像素为screen_height*scale
        channel: window.tool.getCookieValue("channel"), //渠道 appstore之类的
      };
    }
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "getDeviceInfo" in window.YDJSInterface
    ) {
      deviceInfo = JSON.parse(window.YDJSInterface.getDeviceInfo());
    }
    return deviceInfo;
  },
  // 获取ios APP信息
  getYodoIosInfo(cb: string) {
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("get_yodo_info", { callback: cb });
        return;
      }
      window.location.href =
        "/local_call?local_action=get_yodo_info&callback=" + cb;
      return;
    }
  },
  //关闭当前webView 退回客户端进web的页面
  ydBackWebEntry(hideTip: any) {
    if (
      window.tool.isAndroidWeb() &&
      "closeHeadlineRule" in window.YDJSInterface &&
      "closeWebBrowser" in window.YDJSInterface
    ) {
      window.YDJSInterface.closeWebBrowser();
      window.YDJSInterface.closeHeadlineRule();
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("close_window");
        return;
      }
      window.location.href = "/local_call?local_action=close_window";
      return;
    }
    if (!hideTip) {
      window.global.toast("亲，当前版本不支持，请更新版本");
    }
  },
  //页面显示 回调方法
  ydShowPage() {
    // operatePageCb('onShow');
  },
  ydHidePage() {
    // operatePageCb('onHide');
  },
  ydWillShowPage() {
    // operatePageCb('onWillShow');
  },
  ydWillHidePage() {
    // operatePageCb('onWillHide');
  },
  //打开勋章馆
  ydOpenModel() {
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        let params = {
          arg0: "YDAchievementRootViewController",
          arg1: "push",
          arg2: "",
        };
        iosBridgeCall("to_local_vc", params);
        return;
      }
      window.location.href =
        "/local_call?local_action=to_local_vc&arg0=YDAchievementRootViewController&arg1=push&arg2=";
      return;
    }
    if ("gotoAchievement" in window.YDJSInterface) {
      window.YDJSInterface.gotoAchievement();
      return;
    }
  },
  //客户端保存某个DOM 到相册
  ydDownloadImg(domObj: {
    getBoundingClientRect: () => {
      (): any;
      new (): any;
      top: any;
      left: any;
      width: any;
      height: any;
    };
  }) {
    // domObj dom节点 在vue中使用 this.$refs.XXX;
    // pointXRadio dom x轴原点  相对于屏幕宽的 比例 0～1
    // pointYRadio dom y轴原点 相对于屏幕高的 比例 0～1,
    // dowWidthRadio dom宽度 相对于屏幕宽的 比例 0～1,
    // dowHeightRadio dom高度 相对于屏幕高的 比例 0～1
    // 安卓的高是相对于clientHeight ios的高是相对于文档的高度 document.body.scrollHeight
    // 这四个值类型不要进行parsInt 或者 parseFloat
    //如需全屏截图 起点为0，0，1，1
    let clientHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    let clientWidth =
      document.documentElement.clientWidth || document.body.clientWidth;
    let offsetTop = domObj.getBoundingClientRect().top;
    let offsetleft = domObj.getBoundingClientRect().left;
    let domWidth = domObj.getBoundingClientRect().width;
    let domHeight = domObj.getBoundingClientRect().height;
    let pointXRadio = offsetleft / clientWidth;
    let pointYRadio = offsetTop / clientHeight;
    let dowWidthRadio = domWidth / clientWidth;
    let dowHeightRadio = domHeight / clientHeight;
    let version = window.tool.version;

    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "saveShareBitmap" in window.YDJSInterface
    ) {
      window.YDJSInterface.saveShareBitmap(
        pointXRadio,
        pointYRadio,
        dowWidthRadio,
        dowHeightRadio
      );
      return;
    }
    if (
      window.tool.isIosWeb() &&
      window.tool.versionCompare(version, "4.2.3") >= 0
    ) {
      pointYRadio = offsetTop / document.body.scrollHeight;
      dowHeightRadio = domHeight / document.body.scrollHeight;
      // window.location.href = "/local_call?local_action=download_img_base_64&arg0="+imgData;
      var topicIdObj =
        "{" +
        "{" +
        pointXRadio +
        "," +
        pointYRadio +
        "}" +
        "," +
        "{" +
        dowWidthRadio +
        "," +
        dowHeightRadio +
        "}" +
        "}";
      topicIdObj = JSON.stringify(topicIdObj);
      topicIdObj = encodeURIComponent(topicIdObj);
      if (checkIosBridgeVailable()) {
        let params = { arg0: topicIdObj };
        iosBridgeCall("download_img_get_web_image", params);
        return;
      }
      window.location.href =
        "/local_call?local_action=download_img_get_web_image&arg0=" +
        topicIdObj;
      return;
    }
    window.global.toast("亲，当前版本不支持，请更新版本");
  },
  // 跳转到客户端加入圈子页面
  ydGoCircle() {
    let userId = window.tool.getYdUserKey("user_id");
    let url =
      "https://circle.51yund.com/circleMain/searchCircle?user_id=" +
      userId +
      "&circle_id=8&tab=1";
    if (window.tool.isIosWeb() && window.tool.isYuedong()) {
      if (checkIosBridgeVailable()) {
        let params = { arg0: "YDCTFindMoreRootViewController" };
        iosBridgeCall("to_local_vc", params);
        return;
      }
      url =
        "/local_call?local_action=to_local_vc&arg0=YDCTFindMoreRootViewController";
      window.tool.iframeLocalCall(url);
      return;
    }
    window.location.href = url;
  },
  //使用外部浏览器打开链接
  ydOpenUrlByBrowser(url: string) {
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "openUrlByBrowser" in window.YDJSInterface
    ) {
      window.YDJSInterface.openUrlByBrowser(url);
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("open_url_by_safari", { arg0: url });
        return;
      }
      let path =
        "/local_call?local_action=open_url_by_safari&arg0=" +
        encodeURIComponent(url);
      window.tool.iframeLocalCall(path);
      return;
    }
    window.location.href = url;
  },
  //当前网络是否是wifi
  isWifi() {
    let isWifi = false;
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "isHasConnectedWifi" in window.YDJSInterface
    ) {
      isWifi = window.YDJSInterface.isHasConnectedWifi();
    }
    if (window.tool.isIosWeb()) {
      let networkStatue = window.tool.getCookieValue("network_status");
      if (networkStatue == 2) {
        isWifi = true;
      } else {
        isWifi = false;
      }
    }
    return isWifi;
  },
  //下拉刷新开关
  pullRefresh(flag: string) {
    //falg 1禁用下拉刷新，0 开启
    if (window.tool.isIosWeb()) {
      setTimeout(() => {
        if (checkIosBridgeVailable()) {
          iosBridgeCall("hide_pull_refresh", { arg0: flag });
          return;
        }
        let url = "/local_call?local_action=hide_pull_refresh&arg0=" + flag; //arg0=1禁用下拉刷新，0未默认开启
        window.tool.iframeLocalCall(url);
      }, 500);
      return;
    }
    if (window.YDJSInterface) {
      if ("setPageRefreshAble" in window.YDJSInterface) {
        window.YDJSInterface.setPageRefreshAble(!flag);
      } else if ("setPageRefresh" in window.YDJSInterface) {
        window.YDJSInterface.setPageRefresh(!flag);
      }
    }
  },
  //跳转到话题详情
  jumpTopicSubject(topicId: string, circle_id: string, videoFlag: string) {
    //videoFlag 0 普通话题（话题 视频）1 小视频 视频列表
    let url =
      "http://circle.51yund.com/circleDiscussion?topic_id=" +
      topicId +
      "&hide_circle=true&oper_type=false";
    if (window.tool.isYuedong()) {
      if (window.tool.isAndroidWeb()) {
        if ("jumpToArticleDetail" in window.YDJSInterface) {
          window.YDJSInterface.jumpToArticleDetail(
            parseInt(topicId),
            parseInt(videoFlag),
            parseInt(circle_id),
            false,
            "reloadFunc"
          );
          return;
        }
        if ("jumpTopicArticleDetail" in window.YDJSInterface) {
          window.YDJSInterface.jumpTopicArticleDetail(
            parseInt(topicId),
            parseInt(videoFlag)
          );
          return;
        }
      }
      if (window.tool.isIosWeb()) {
        let version = window.tool.version;
        if (window.tool.versionCompare(version, "3.6.9") >= 0) {
          let topicIdObj: any = {
            topicId: topicId,
            circleId: circle_id,
            accessToManage: false,
            sourceWebURL: window.location.href,
          };
          topicIdObj = JSON.stringify(topicIdObj);
          topicIdObj = encodeURIComponent(topicIdObj);
          if (checkIosBridgeVailable()) {
            let params = {
              arg0: "YDCircleDetailViewController",
              arg1: "push",
              arg2: topicIdObj,
            };
            iosBridgeCall("to_local_vc", params);
            return;
          }
          let path =
            "/local_call?local_action=to_local_vc&arg0=YDCircleDetailViewController&arg1=push&arg2=" +
            topicIdObj;
          window.tool.iframeLocalCall(path);
          return;
        }
      }
    }
    location.href = url;
  },
  //跳转到客户端视频播放列表
  jumpToVideoList(topicId: string, from: any) {
    let url =
      "https://sslwxsharecircle.51yund.com/topic/shareVideo?topic_id=" +
      topicId +
      "&is_share=true";
    if (window.tool.isYuedong()) {
      if (window.tool.isAndroidWeb()) {
        if ("openCircleVideo" in window.YDJSInterface) {
          window.YDJSInterface.openCircleVideo(topicId, 3, false);
          return;
        }
        if ("openCircleVideoList" in window.YDJSInterface) {
          window.YDJSInterface.openCircleVideoList(topicId, 3);
          return;
        }
      }
      let version = window.tool.version;
      if (window.tool.versionCompare(version, "4.0.9") >= 0) {
        var topicIdObj: any = { topicID: topicId, from: from };
        topicIdObj = JSON.stringify(topicIdObj);
        topicIdObj = encodeURIComponent(topicIdObj);
        if (checkIosBridgeVailable()) {
          let params = {
            arg0: "YDVideoPlayingListViewController",
            arg1: "push",
            arg2: topicIdObj,
          };
          iosBridgeCall("to_local_vc", params);
          return;
        }
        window.location.href =
          "/local_call?local_action=to_local_vc&arg0=YDVideoPlayingListViewController&arg1=push&arg2=" +
          topicIdObj;
        return;
      }
    }
    window.location.href = url;
  },
  //跳转到客户端健身计划页面
  jumpClientHealthVideo(args: {
    data: { planId: string; userPlanId: string };
  }) {
    //operType  默认“my”
    if (window.tool.isAndroidWeb()) {
      if ("gotoPrescriptionPlan" in window.YDJSInterface) {
        window.YDJSInterface.gotoPrescriptionPlan(
          parseInt(args.data.planId),
          parseInt(args.data.userPlanId),
          "my"
        );
        return;
      }
      if ("gotoFitnessPlan" in window.YDJSInterface) {
        window.YDJSInterface.gotoFitnessPlan(
          parseInt(args.data.planId),
          parseInt(args.data.userPlanId),
          "my"
        );
        return;
      }
    }
    if (window.tool.isIosWeb()) {
      var jumpClientObj: any = args.data;
      jumpClientObj = JSON.stringify(jumpClientObj);
      jumpClientObj = encodeURIComponent(jumpClientObj);
      if (checkIosBridgeVailable()) {
        let params = {
          arg0: "YDFitPlanDetailViewController",
          arg1: "push",
          arg2: jumpClientObj,
        };
        iosBridgeCall("to_local_vc", params);
        return;
      }
      let path =
        "/local_call?local_action=to_local_vc&arg0=YDFitPlanDetailViewController&arg1=push&arg2=" +
        jumpClientObj;
      window.tool.iframeLocalCall(path);
      return;
    }
    window.global.toast("亲，当前版本不支持，请更新版本");
  },
  //跳转到web健身计划页面
  jumpClientHealthVideoCourse(args: any) {
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "openCoursePlayer" in window.YDJSInterface
    ) {
      window.YDJSInterface.openCoursePlayer(513, args.data.course_id);
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        let params = { native_int: 513 };
        Object.assign(params, args.data);
        iosBridgeCall("native_int_jump", params);
        return;
      }
      let path =
        "/local_call?local_action=native_int_jump&native_int=513&course_id=" +
        args.data.course_id +
        "&plan_id=" +
        args.data.planId +
        "&is_user_plan=1&user_plan_id=" +
        args.data.userPlanId +
        "&day_time=" +
        args.data.day_time;
      window.tool.iframeLocalCall(path);
      return;
    }
    window.global.toast("亲，当前版本不支持，请更新版本");
  },
  //跳转到反馈页面
  gotofeed() {
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("to_feedback");
        return;
      }
      let url = "/local_call?local_action=to_feedback";
      return window.tool.iframeLocalCall(url);
    }
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "goToAliFeedBack" in window.YDJSInterface
    ) {
      return window.YDJSInterface.goToAliFeedBack();
    }
    window.global.toast("请打开悦动圈app进行反馈");
  },
  //扫描二维码
  openScanCode(args: { data: { succ: any } }) {
    APP.scanQrcodeCb = args.data.succ;
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "openQRCodeScan" in window.YDJSInterface
    ) {
      window.YDJSInterface.openQRCodeScan();
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        return iosBridgeCall("qr_code", { arg0: "greenroad" });
      }
      let url = "local_call?local_action=qr_code&arg0=greenroad";
      window.tool.iframeLocalCall(url);
      return;
    }
    window.global.toast("请升级最新版本使用该功能~");
  },
  //运动数据上报
  tryRunDataReport(args: any) {
    if (
      window.tool.isAndroidWeb() &&
      "tryRunDataReport" in window.YDJSInterface
    ) {
      APP.androidReportCb = args.data.succ;
      window.YDJSInterface.tryRunDataReport();
      return;
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        //ios localCall需要的回调方法的key 和名字
        let cbSuccAbj = { arg0: "pushSucc" };
        let cbFailAbj = { arg1: "pushFail" };
        let params = formatIosBridgeArgs(args.data, cbSuccAbj, cbFailAbj);
        //如果不需要回调 方法调用如下：formatIosBridgeArgs(args) 这时的args里也不存在succ 和 fail
        // let params = formatIosBridgeArgs(args)
        iosBridgeCall("push_pedometer", params);
      }
      APP.pushSucc = args.data.succ;
      APP.pushFail = args.data.fail;
      let url =
        "/local_call?local_action=push_pedometer&arg0=pushSucc&arg1=pushFail";
      window.tool.iframeLocalCall(url);
    }
  },
  //跳转到微信公众号
  gotoBindWeChat() {
    if (window.tool.isAndroidWeb()) {
      window.YDJSInterface.gotoWeChatOpenAccount();
    }
    if (window.tool.isIosWeb()) {
      if (checkIosBridgeVailable()) {
        iosBridgeCall("wechat_rank");
        return;
      }
      window.location.href = "/local_call?local_action=wechat_rank";
    }
  },
  viewAdVideo(args: { data: { finish: any; tip: string; entry: any } }) {
    let version = window.tool.version;
    APP.ydViewAdVideoCb = args.data.finish;
    let tip = args.data.tip || "亲，请升级悦动圈app版本";
    // 观看结束回调函数：window.onAdPlayFinish 参数值 1：观看完整 0: 未看完
    if (window.tool.isYuedong()) {
      if (window.tool.isAndroidWeb()) {
        if (window.tool.versionCompare(version, "3.2.8.2.1") >= 0) {
          APP.openNativeInt("viewAdVideo", {
            user_id: parseInt(window.tool.getYdUserKey("user_id")) || 0,
            entry: args.data.entry, // 可在cms配置 http://cms.51yund.com/sport/index.php?r=ydVidoeExcitationConfig/admin
          });
          return;
        } else {
          window.global.toast(tip);
        }
      }
      if (window.tool.isIosWeb()) {
        if (window.tool.versionCompare(version, "4.8.7") >= 0) {
          if (checkIosBridgeVailable()) {
            iosBridgeCall("play_reward_video", { entry: args.data.entry });
            return;
          }
          let path = `/local_call?local_action=play_reward_video&entry=${args.data.entry}`;
          window.tool.iframeLocalCall(path);
          return;
        } else {
          window.global.toast(tip);
        }
      }
    }
  },
  //显示分享按钮
  ydShowShareBtn(isFristPage: any) {
    if (!window.tool.isYuedong()) return;
    if (isFristPage) {
      let queryStr = location.search;
      if (queryStr) {
        if (queryStr.indexOf("ios_show_share=true") == -1) {
          queryStr += "&ios_show_share=true";
        }
        if (queryStr.indexOf("showTitle=true") == -1) {
          queryStr += "&showTitle=true";
        }
      } else {
        queryStr = "?showTitle=true&ios_show_share=true";
      }
      history.replaceState({}, "", queryStr);
    }
    if (window.tool.isAndroidWeb()) {
      if (window.YDJSInterface && "showShareBtn" in window.YDJSInterface) {
        window.YDJSInterface.showShareBtn();
      }
    } else {
      if (checkIosBridgeVailable()) {
        return iosBridgeCall("hide_share_bnt", { arg0: 1 });
      }
      let url = "/local_call?local_action=hide_share_bnt&arg0=1";
      window.tool.iframeLocalCall(url);
    }
  },
  //隐藏分享按钮
  ydHideShareBtn() {
    if (window.tool.isAndroidWeb()) {
      if (window.YDJSInterface && "hideShareBtn" in window.YDJSInterface) {
        window.YDJSInterface.hideShareBtn();
      }
    } else {
      if (checkIosBridgeVailable()) {
        return iosBridgeCall("hide_share_bnt", { arg0: 0 });
      }
      let url = "/local_call?local_action=hide_share_bnt&arg0=0";
      window.tool.iframeLocalCall(url);
    }
  },
  //跳转到小视频播放列表
  openShortVideoList(currentTopicId: any) {
    window.YDJSInterface.openShortVideoList(currentTopicId, 3);
  },
  //跳转到短视频播放列表
  openCircleVideoList(currentTopicId: any) {
    window.YDJSInterface.openCircleVideoList(currentTopicId, 3);
  },
  //跳转到文章详情
  jumpTopicArticleDetail(currentTopicId: any) {
    window.YDJSInterface.jumpTopicArticleDetail(currentTopicId, 0);
  },
  //发短信
  onSendSms(phone: any, msg: any) {
    if ("sendPhoneMessage" in window.YDJSInterface) {
      window.YDJSInterface.sendPhoneMessage(phone, msg);
      return;
    }
  },
  //用X5浏览器打开新链接
  loadURLByX5WebKit(url: string) {
    if (!url) {
      return;
    }
    if (window.YDJSInterface && "loadURLByX5WebKit" in window.YDJSInterface) {
      window.YDJSInterface.loadURLByX5WebKit(url);
    } else {
      window.location.href = url;
    }
  },
  //打开新的webView
  jumpToYDWebView(url: string) {
    if (window.YDJSInterface && "jumpToYDWebView" in window.YDJSInterface) {
      window.YDJSInterface.jumpToYDWebView(url);
      return;
    }
    window.location.href = url;
  },
  //在ios需要主动调web函数传递数据时 web需要注册客户端调的方法 即funName
  iosBridgeRegister(funName: any) {
    Bridge.registerhandler(
      funName,
      (data: any, responseCallback: (arg0: string) => void) => {
        let res = "";
        responseCallback(res); //告诉客户端我们接收到了数据
      }
    );
  },
  /**
   * 清除IOS的日历
   * @param {String} keyword 模糊匹配关键词，跟APP.setAppCalendar里面的content参数对应
   * @param {Number} start_ts 清除日历的开始时间
   * @param {Number} end_ts 清除日历的结束时间
   */
  // clearIosCalendar() {
  //   if (
  //     window.tool.isIosWeb() &&
  //     window.tool.versionCompare(window.tool.version, "5.0.8") >= 0
  //   ) {
  //     let url = `/local_call?local_action=yd_calendar_delete_remind&keyword=${keyword}&start_ts=${start_ts}&end_ts=${end_ts}`;
  //     window.tool.iframeLocalCall(url);
  //   }
  // },
  /**
   * 设置日历提醒
   * @param {Array} data.remind_ts
   * @param {String} data.title
   * @param {String} data.content//url备注
   */
  setAppCalendar(data: { title: any; remind_ts: any[]; content: any }) {
    // syncCalendarReminderV2去掉了科学运动计划的文案
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "syncCalendarReminderV2" in window.YDJSInterface
    ) {
      let planJsonStr = {
        title: data.title,
      };
      let dayDetailJsonStr = data.remind_ts.map((item: number) => {
        let obj = {
          day_time: item - 19 * 60 * 60, // 减去19h，因为跟科学运动计划的接口耦合了
        };
        return obj;
      });
      window.YDJSInterface.syncCalendarReminderV2(
        JSON.stringify(planJsonStr),
        JSON.stringify(dayDetailJsonStr)
      );
      return;
    }
    if (
      window.tool.isAndroidWeb() &&
      window.YDJSInterface &&
      "syncCalendarReminder" in window.YDJSInterface
    ) {
      let planJsonStr = {
        title: data.title,
      };
      let dayDetailJsonStr = data.remind_ts.map((item: number) => {
        let obj = {
          day_time: item - 19 * 60 * 60, // 减去19h，因为跟科学运动计划的接口耦合了
        };
        return obj;
      });
      window.YDJSInterface.syncCalendarReminder(
        JSON.stringify(planJsonStr),
        JSON.stringify(dayDetailJsonStr)
      );
      return;
    }
    if (
      window.tool.isIosWeb() &&
      window.tool.versionCompare(window.tool.version, "5.0.8") >= 0
    ) {
      let list = data.remind_ts.map((item: any) => {
        let obj = {
          title: data.title,
          content: data.content ? data.content : data.title,
          remind_ts: item,
        };
        return obj;
      });
      let url = `/local_call?local_action=yd_calendar_add_remind&arg0=${encodeURIComponent(
        JSON.stringify(list)
      )}`;
      window.tool.iframeLocalCall(url);
      return;
    }
  },
  /**
   * 设置ios的导航栏，安卓暂时不支持
   * @param {Number} bgType 导航栏背景色 0：主题色，1：白色，2：透明
   * @param {Number} hideRightBtn 是否隐藏右边按钮 1：是。 0：否
   */
  setNavBar(bgType: any, hideRightBtn: any) {
    if (
      window.tool.isIosWeb() &&
      window.tool.versionCompare(window.tool.version, "5.0.8") >= 0
    ) {
      if (checkIosBridgeVailable()) {
        return iosBridgeCall("set_nav_bar_style", {
          arg0: bgType,
          arg1: hideRightBtn,
        });
      }
      let url = `/local_call?local_action=set_nav_bar_style&arg0=${bgType}&arg1=${hideRightBtn}`;
      window.tool.iframeLocalCall(url);
    }
  },
};

export default () => {
  if (typeof window.APP == "undefined") {
    window.APP = APP;
  }
  APP.pullRefresh(1);
};
//ios跳转到运动模式
function iosGoSport(sportType: number) {
  //sportType 0去跑步 3去骑行
  let runObj: any = { sportType: sportType };
  runObj = JSON.stringify(runObj);
  runObj = encodeURIComponent(runObj);
  let params = { arg0: "YDRunningViewController", arg2: runObj };
  if (checkIosBridgeVailable()) {
    iosBridgeCall("to_local_vc", params);
    return;
  }
  window.location.href =
    "/local_call?local_action=to_local_vc&arg0=YDRunningViewController" +
    "&arg2=" +
    runObj;
}
function checkIosBridgeVailable() {
  let version = window.tool.version;
  if (window.tool.versionCompare(version, "5.2.0") >= 0) {
    return true;
  }
  return false;
}
//ios版本>=5.2.0  并且有bridge对象  第一个参数localaction的名字 第二个参数是json字符串（可以试试json对象行不），json的key和v
// 2020-11-18 ios 升级wk webview，支持版本为5.2.0，以下方法不用encode
// open_url_internal arg0
// open_url_new_window arg0
// open_url_by_safari  arg0
// rightTitleText  arg0  arg1
// show_right_img_btn  arg0
// alipay  reUrl
// pay  arg5

// 老版有decode 新版没有decode
// report_time_event_start  extra
// report_time_event_end extra
// report_event_um  attributes
// select_upload_pic  source
// photograph_upload_pic source
// fitness_watermark  suc_callback  pic_source
// ad_handle_url  arg0
function iosBridgeCall(funName: string, data = {}) {
  //如果有回调函数 例如这种类型的 ：window.location.href = "/local_call?local_action=push_pedometer&arg0=pushSucc&arg1=pushFail&id=1"
  //那么 funName = 'push_pedometer'
  //那么data应该是：data{'arg0':'pushSucc','arg1':'pushFail','id':1} 根据客户端的要求 看看要不要进行JSON.Stringfy(data)
  //pushFail 和 pushFail都应该是注入到window的方法名  详情看第app.js634行代码的例子 再执行相关逻辑
  Bridge.callhandler(funName, data, undefined);
}
function formatIosBridgeArgs(args: any = {}, cbSuccAbj = {}, cbFailAbj = {}) {
  //如果有回调函数 例如这种类型的 ：window.location.href = "/local_call?local_action=push_pedometer&arg0=pushSucc&arg1=pushFail"
  //那么 funName = 'push_pedometer'
  //那么data应该是：data{'arg0':'pushSucc','arg1':'pushFail'} 根据客户端的要求 看看要不要进行JSON.Stringfy(data)
  //pushFail 和 pushFail都应该是注入到window的方法名  详情看第app.js634行代码的例子 再执行相关逻辑

  let params = {};
  let cbSucc = null;
  let cbFail = null;
  if (args) {
    params = args.data ? args.data : {};
    cbSucc = args.succ ? args.succ : null;
    cbFail = args.fail ? args.fail : null;
  }
  APP[Object.values(cbSuccAbj)[0] as string] = cbSucc ? cbSucc : null;
  APP[Object.values(cbFailAbj)[0] as string] = cbFail ? cbFail : null;
  Object.assign(params, cbSuccAbj, cbFailAbj);
  return params;
}
function hexCharCodeToStr(hexCharCodeStr: string) {
  var trimedStr = hexCharCodeStr.trim();
  var rawStr =
    trimedStr.substr(0, 2).toLowerCase() === "0x"
      ? trimedStr.substr(2)
      : trimedStr;
  var len = rawStr.length;
  if (len % 2 !== 0) {
    return "";
  }
  var curCharCode;
  var resultStr = [];
  for (var i = 0; i < len; i = i + 2) {
    curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
    resultStr.push(String.fromCharCode(curCharCode));
  }
  return resultStr.join("");
}
//网络发生变化客户端调用
window.onNetworkStatusChange = function (netWorkStatus: any) {
  // APP.onNetworkStatusChange(netWorkStatus);
  console.log(
    "网络发生了变化 -1 未知   0 不可达没网络  1 在蜂窝网（2，3，4G等）  2 WiFi===========变化后的网络：",
    netWorkStatus
  ); //-1 未知   0 不可达没网络  1 在蜂窝网（2，3，4G等）  2 WiFi
};
//获取地理位置客户端回调
window.onLocationRes = function (arg: string) {
  if (typeof arg === "string") {
    arg = JSON.parse(arg);
  }
  APP.ydGetPositionCb(arg);
  APP.ydGetPositionCb = "";
};
//  扫描二维码
window.getScanResult = function (url: string) {
  if (window.tool.isAndroidWeb()) {
    url = window.atob(url);
  } else {
    url = hexCharCodeToStr(url);
  }
  APP.scanQrcodeCb(url);
  APP.scanQrcodeCb = () => {}; //清除本次回调方法执行逻辑 避免后续重复回调执行
};
//上传运动数据客户端回调
window.getPushStatus = function (flag: any) {
  APP.androidReportCb(flag); //flag = "0" 数据更新成功 否则数据同步失败
  APP.androidReportCb = () => {}; //清除本次回调方法执行逻辑 避免后续重复回调执行
};
// 观看广告视频的回调
window.onAdPlayFinish = (isFinish: any) => {
  // isFinish 1:完整观看 0：未观看完
  APP.ydViewAdVideoCb(isFinish);
  // 清空
  APP.ydViewAdVideoCb = () => {};
};
window.pushSucc = function () {
  APP.pushSucc();
  APP.pushSucc = () => {}; //清除本次回调方法执行逻辑 避免后续重复回调执行
};
window.pushFail = function () {
  APP.pushFail();
  APP.pushFail = () => {}; //清除本次回调方法执行逻辑 避免后续重复回调执行
};
window["viewDidAppear"] = () => {
  //页面出现时客户端调用
  // APP.ydShowPage()
};
window["viewDidDisappear"] = () => {
  //页面消失时客户端调用
  // APP.ydHidePage()
};
window["viewWillAppear"] = () => {
  //页面即将出现时客户端调用
  // APP.ydWillShowPage()
};
window["viewWillDisappear"] = () => {
  //页面即将消失时客户端调用
  // APP.ydWillHidePage()
};

//客户端页面显示或者消失时触发执行
function operatePageCb(action: any) {
  if (window.global.$route) {
    let path = window.global.$route.path;
    switch (path) {
      case "/app":
        window.global.$emit(action);
        //接收方 window.global.$on('onShowAPP', funtion（）)
        break;
    }
  }
}
