<template>
  <view class="container" :style="{ backgroundColor: backgroundColor }">
    <!-- 分享弹窗 -->

    <view class="navbox" style="z-index: 9999999999999999999999999999999">
      <view class="status_bar"></view>
      <uni-nav-bar
        :title="title"
        @clickLeft="goBack"
        @click-left="goBack"
        color="#8B2316"
        :border="false"
        backgroundColor="#eeeeee"
      >
        <template #left>
          <view class="back-hit" @click.stop="goBack">
            <uni-icons type="left" size="22" color="#8B2316"></uni-icons>
          </view>
        </template>
        <template #right>
          <view class="nav-actions">
            <view class="collect-img" @click="shareToggle" v-if="canShare">
              <image
                class="share-img-icon"
                :src="shareIcon"
                mode="aspectFill"
              />
            </view>
          </view>
        </template>
      </uni-nav-bar>
    </view>
  </view>
  <web-view
    v-if="safeUrl && !usePlusWebview"
    :src="safeUrl"
    :webview-styles="webviewStyles"
  ></web-view>
  <view class="bottom-box">
    <view class="bottom-cell">
      <image class="bottom-cell-img" :src="readImg" />
      <text class="bottom-cell-text">{{ fromatNumber(readnum) }}</text>
    </view>
    <view class="bottom-cell" @click="toggleAgree">
      <image
        class="bottom-cell-img"
        :src="isAgree == 1 ? likeImg : dislikeImg"
      />
      <text class="bottom-cell-text">{{ fromatNumber(agreenum) }}</text>
    </view>
    <view class="bottom-cell" @click="toggleCollect">
      <image
        class="bottom-cell-img"
        :src="isCollection == 1 ? collectImg : discollectImg"
      />
      <text class="bottom-cell-text">收藏</text>
    </view>
    <view class="bottom-cell" @click="shareToggle">
      <image class="bottom-cell-img" :src="shareImgBottom" />
      <text class="bottom-cell-text">分享</text>
    </view>
  </view>
  <uni-popup ref="shareRef" type="bottom" safeArea backgroundColor="#fff">
    <view class="share-popup">
      <view class="share-title">分享到</view>
      <view class="share-content">
        <view class="share-item" @click="shareToWechat">
          <view class="share-icon wechat-icon">
            <image class="share-img" :src="wxImg" mode="aspectFill" />
          </view>
          <text class="share-text">微信</text>
        </view>
        <view class="share-item" @click="shareToMoments">
          <view class="share-icon moments-icon">
            <image class="share-img" :src="friendImg" mode="aspectFill" />
          </view>
          <text class="share-text">朋友圈</text>
        </view>
        <view class="share-item" @click="shareToWeibo">
          <view class="share-icon weibo-icon">
            <image class="share-img" :src="sinaImg" mode="aspectFill" />
          </view>
          <text class="share-text">新浪微博</text>
        </view>
      </view>
      <view class="share-cancel" @click="closeShare">
        <text>取消</text>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onHide, onShow, onUnload } from "@dcloudio/uni-app";
import api from "@/api/api";
import navBar from "@/components/navBar/navBar.vue";
import shareIcon from "@/static/icon_share.png";
import sinaImg from "@/static/share_sina.png";
import wxImg from "@/static/share_weixin.png";
import friendImg from "@/static/share_wxc.png";
import logoImg from "@/static/weiboShare.png";
import collectImg from "@/static/icon_book_collect_sel.png";
import discollectImg from "@/static/icon_book_collect_nor.png";
import readImg from "@/static/reading.png";
import docUrl from "@/utils/docUrl";
import likeImg from "@/static/argee_sure.png";
import dislikeImg from "@/static/argee_no.png";
import shareImgBottom from "@/static/icon_share.png";
import paitientImg from "@/static/info_icon_1.png";
const selectedPatients = ref([]);
const title = ref("新闻详情");
const type = ref("");
const safeUrl = ref("");
const backgroundColor = ref("");
const hasBg = ref(false);
const canShare = ref(false);
const summary = ref("");
const shareLink = ref("");
const shareImg = ref("");
const shareTitle = ref("");
const uuid = ref("");
const isCollection = ref(0);
const imgpath = ref("");
const readnum = ref(0);
const agreenum = ref(0);
const isAgree = ref(0);
const user_uuid = ref("");
const NAV_BAR_HEIGHT_PX = 44;
const WEBVIEW_BOTTOM_PX = 55;
const webviewTopPx = ref(88);
const webviewBottomPx = ref(WEBVIEW_BOTTOM_PX);
const usePlusWebview = ref(false);
const appPlusWebview = ref(null);

const webviewStyles = ref({
  width: "100%",
  top: webviewTopPx.value,
  bottom: webviewBottomPx.value,
});
const applyWebviewLayout = () => {
  const resInfo = uni.getSystemInfoSync();
  const statusBarHeight = Number(resInfo.statusBarHeight || 0);
  const safeAreaBottom = Number(
    (resInfo.safeAreaInsets && resInfo.safeAreaInsets.bottom) || 0
  );
  webviewTopPx.value = Math.round(statusBarHeight + NAV_BAR_HEIGHT_PX);
  webviewBottomPx.value = Math.round(WEBVIEW_BOTTOM_PX + safeAreaBottom);
  webviewStyles.value = {
    width: "100%",
    top: webviewTopPx.value,
    bottom: webviewBottomPx.value,
  };
  // #ifdef APP-PLUS
  if (usePlusWebview.value && appPlusWebview.value) {
    appPlusWebview.value.setStyle({
      top: `${webviewTopPx.value}px`,
      bottom: `${webviewBottomPx.value}px`,
      scalable: true,
      videoFullscreen: "landscape",
      zIndex: -1,
    });
  }
  // #endif
};
const initWebviewLayout = () => {
  applyWebviewLayout();
};
const onWindowResize = () => {
  applyWebviewLayout();
};
const addpoint = () => {
  console.log("添加积分1");
  api
    .addBonusPointsN({
      score_type: 5,
    })
    .then((res) => {
      console.log("添加积分2");
      console.log(res);
      if (res.code == 200) {
        //uni.showToast({ title: "添加积分成功", icon: "none" });
      } else {
        //uni.showToast({ title: res.msg, icon: "none" });
      }
    })
    .catch((err) => {
      uni.showModal({
        title: "提示",
        content: res.message,
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            //uni.navigateBack();
          }
        },
      });
      //uni.showToast({ title: err.msg, icon: "none" });
    });
};
const getCollect = () => {
  api
    .getCollect({
      other_uuid: uuid.value,
      user_uuid: user_uuid.value,
      type: type.value == "huanjiao_news" ? 1 : 2,
      title: shareTitle.value,
      path: safeUrl.value.replace(docUrl, ""),
      readnum: readnum.value,
      imgpath:
        imgpath.value.indexOf("http") > -1
          ? imgpath.value
          : docUrl + imgpath.value,
      public_name: shareTitle.value,
    })
    .then((res) => {
      if (res.code == 200) {
        uni.showToast({
          title: "收藏成功",
          icon: "none",
        });
        if (type.value == "huanjiao_news") {
          getNewsDetail();
        } else {
          getKePuCollection();
        }
      }
    });
};
const getDiscollect = () => {
  api
    .getDiscollect({
      other_uuid: uuid.value,
      user_uuid: user_uuid.value,
      type: type.value == "huanjiao_news" ? 1 : 2,
    })
    .then((res) => {
      console.log(res);
      if (res.code == 200) {
        uni.showToast({
          title: "取消收藏成功",
          icon: "none",
        });
        if (type.value == "huanjiao_news") {
          getNewsDetail();
        } else {
          getKePuCollection();
        }
      }
    });
};
const toggleCollect = () => {
  console.log("收藏状态" + isCollection.value);
  if (isCollection.value == 0) {
    getCollect();
  } else {
    getDiscollect();
  }
};
const toggleAgree = () => {
  if (isAgree.value == 0) {
    getAgree();
  } else {
    getDisagree();
  }
};
const getAgree = () => {
  api
    .getAgree({
      news_article_uuid: uuid.value,
      user_uuid: user_uuid.value,
      type: type.value == "huanjiao_news" ? 1 : 2,
    })
    .then((res) => {
      if (type.value == "huanjiao_news") {
        getNewsDetail();
      } else {
        getKePuCollection();
      }
    });
};
const getDisagree = () => {
  api
    .getDisagree({
      news_article_uuid: uuid.value,
      user_uuid: user_uuid.value,
      type: type.value == "huanjiao_news" ? 1 : 2,
    })
    .then((res) => {
      console.log(res);
      if (type.value == "huanjiao_news") {
        getNewsDetail();
      } else {
        getKePuCollection();
      }
    });
};
const getOutRead = () => {
  api
    .getOutRead({
      uuid: uuid.value,
      type: type.value == "huanjiao_news" ? 1 : 2,
    })
    .then((res) => {
      console.log(res);
    });
};
const getNewsDetail = () => {
  api
    .getNewsDetail({
      uuid: uuid.value,
    })
    .then((res) => {
      console.log(res);
      if (res.code == 200) {
        isCollection.value = res.data.isCollection;
        readnum.value = res.data.readnum;
        agreenum.value = res.data.agreenum;
        isAgree.value = res.data.isAgree;
      }
    });
};
const fromatNumber = (number) => {
  if (number < 10000) {
    return number;
  } else {
    return (number / 10000).toFixed(1) + "w";
  }
};
const getKePuCollection = () => {
  api
    .getKePuCollection({
      uuid: uuid.value,
      user_uuid: user_uuid.value,
    })
    .then((res) => {
      console.log(res.data);
      if (res.code == 200) {
        isCollection.value = res.data.isCollection;
        readnum.value = res.data.readnum;
        agreenum.value = res.data.agreenum;
        isAgree.value = res.data.isAgree;
      }
    });
};
const goBack = () => {
  closeNativePopup();
  closeSelectNativePopup();
  uni.navigateBack({
    delta: 1,
    fail() {
      uni.redirectTo({
        url: "/pages/index/index",
      });
    },
  });
};
const webviewRef = ref(null);
const createAppPlusWebview = (url) => {
  // #ifdef APP-PLUS
  try {
    if (!url) return;
    const pages = getCurrentPages();
    const page = pages[pages.length - 1];
    const currentWebview =
      page && page.$getAppWebview ? page.$getAppWebview() : null;
    if (!currentWebview) return;
    if (appPlusWebview.value && appPlusWebview.value.close) {
      appPlusWebview.value.close();
      appPlusWebview.value = null;
    }
    const wv = plus.webview.create("", "webview-class-content", {
      top: `${webviewTopPx.value}px`,
      bottom: `${webviewBottomPx.value}px`,
      scalable: true,
      videoFullscreen: "landscape",
      zIndex: -1,
    });
    wv.loadURL(url);
    currentWebview.append(wv);
    appPlusWebview.value = wv;
  } catch (error) {
    console.log("createAppPlusWebview error:", error);
  }
  // #endif
};
const addGroupSendMsg4YunXin = async () => {
  const res = await api.addGroupSendMsg4YunXin({
    patient_user_uuid: selectedPatients.value
      .map((item) => item.uuid)
      .join(","),
    msg_content: uuid.value,
    msg_type: 3,
  });
  if (res.code == 200) {
    uni.showToast({ title: "推荐成功", icon: "none" });
  } else {
    uni.showToast({ title: res.msg, icon: "none" });
  }
};

onShow(() => {
  uni.$on("selectedChatPatientsSingle", (data) => {
    console.log("监听数据");
    console.log(data);
    selectedPatients.value = data.patients;
    if (type.value == "huanjiao") {
      addGroupSendMsg4YunXin();
    }
  });
  initWebviewLayout();
  setTimeout(() => {
    uni.hideLoading();
  }, 2000);
  // console.log('show');
  // plus.screen.lockOrientation('portrait-primary');
});
onUnload(() => {
  if (typeof uni.offWindowResize === "function") {
    uni.offWindowResize(onWindowResize);
  }
  // console.log('onUnload');
  // plus.screen.lockOrientation('portrait-primary');
});
onHide(() => {
  // console.log('onHide');
  // plus.screen.lockOrientation('landscape-primary');
});
onLoad((query) => {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  initWebviewLayout();
  // #ifdef APP-PLUS
  usePlusWebview.value = true;
  // #endif
  if (typeof uni.onWindowResize === "function") {
    uni.onWindowResize(onWindowResize);
  }
  const userInfo = uni.getStorageSync("userInfo");
  if (query.type) {
    type.value = query.type;
  }
  user_uuid.value = userInfo.uuid;
  if (query.title) {
    title.value = query.title;
  }
  if (query.uuid) {
    uuid.value = query.uuid;
  }
  if (query.share == 1) {
    canShare.value = true;
  }
  if (query.bg == 1) {
    hasBg.value = true;

    backgroundColor.value = "linear-gradient(to bottom,'#fff' , '#398775')";
  }
  if (type.value == "huanjiao_news") {
    getNewsDetail();
  } else {
    getKePuCollection();
  }
  getOutRead();

  const raw =
    query && (query.url || query.href || query.link || query.src || "");
  if (!raw) {
    uni.showToast({
      title: "未获取到网页链接",
      icon: "none",
    });
  }
  try {
    safeUrl.value = decodeURIComponent(raw);
    console.log(safeUrl.value);
    imgpath.value = decodeURIComponent(query.imgPath);
    // query.imgPath
    //   ? decodeURIComponent(query.imgPath)
    //   : "https://doc.igandan.com/app/html/img/2016/20160714132557.png";
    shareImg.value =
      "https://doc.igandan.com/app/html/img/2016/20160714132557.png";
    console.log(shareImg.value);

    if (query.type == "live_yugao") {
      shareTitle.value = query.sharetitle;
      summary.value = "分享一篇来自“肝胆相照”的会议预告：" + shareTitle.value;
    } else if (query.type == "live_old") {
      shareTitle.value = query.sharetitle;
      summary.value = "分享一篇来自“肝胆相照”的历史会议：" + shareTitle.value;
    } else if (query.type == "live") {
      shareTitle.value = "肝胆相照直播：" + query.sharetitle;
      summary.value = shareTitle.value;
    } else if (query.type == "news") {
      shareTitle.value = query.sharetitle;
      summary.value = "";
    } else if (query.type == "huanjiao" || query.type == "huanjiao_news") {
      console.log(query.sharetitle);
      console.log(query.summary);
      shareTitle.value = query.sharetitle;
      summary.value = query.summary;
    }
    // #ifdef APP-PLUS
    // let wv = plus.webview.create("", "custom-webview", {
    //   top: statusBarHeight + navHeight + "px",
    //   height: calcWebviewHeight(baseWindowHeight) + "px",
    //   bottom: fixedBottomHeight + "px",
    // });
    // webviewRef.value = wv;
    // wv.loadURL(safeUrl.value);

    // let pages = getCurrentPages();
    // let page = pages[pages.length - 1];

    // var currentWebview = page.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
    // currentWebview.append(wv);
    // const applyWebviewStyle = (windowH) => {
    //   wv.setStyle({
    //     top: statusBarHeight + navHeight + "px",
    //     height: calcWebviewHeight(windowH) + "px",
    //     bottom: fixedBottomHeight + "px",
    //     scalable: true,
    //     videoFullscreen: "landscape",
    //     zIndex: -1,
    //   });
    // };
    // setTimeout(function () {
    //   wv = currentWebview.children()[0];
    //   webviewRef.value = wv;
    //   applyWebviewStyle(baseWindowHeight);
    // }, 300); //如果是页面初始化调用时，需要延时一下
    // wv.onloaded = (e) => {
    //   wv.show();
    // };

    // uni.onWindowResize((res) => {
    //   const resizeH = Number((res && res.size && res.size.windowHeight) || baseWindowHeight);
    //   setTimeout(function () {
    //     applyWebviewStyle(resizeH);
    //   }, 0);
    // });
    // 创建并展示原生弹窗
    createNativePopup();
    createAppPlusWebview(safeUrl.value);

    // #endif
  } catch (e) {
    safeUrl.value = raw;
    createAppPlusWebview(safeUrl.value);
  }
});
const shareRef = ref(null);
shareRef.value?.open();
// 分享APP
const shareToggle = () => {
  showNativePopup();
  // console.log(shareRef.value);
  // shareRef.value?.open();
  //  uni.showActionSheet({
  //    title:"分享",
  //    itemList: ['分享到微信', '分享到朋友圈', '分享到微博'],
  //    success: function (res) {
  //    		if(res.tapIndex==0){
  // 			shareToWechat()
  // 		}else if(res.tapIndex==1){
  // 			shareToMoments()
  // 		}else{
  // 			shareToWeibo()
  // 		}
  //    	},
  //  })
};

// 关闭分享弹窗
const closeShare = () => {
  shareRef.value.close();
};

// ========= 原生弹窗（plus.nativeObj.view）============
const nativeMaskView = ref(null);
const nativePopupView = ref(null);
const popupShowing = ref(false);
const shareActionLocked = ref(false);
const nativeSelectMaskView = ref(null);
const nativeSelectPopupView = ref(null);
const selectPopupShowing = ref(false);
const selectActionLocked = ref(false);
const selectNavigateLocked = ref(false);
const lastSelectNavigateAt = ref(0);
const selectPopupInfo = ref({
  screenW: 0,
  screenH: 0,
  panelW: 0,
  panelH: 0,
  panelLeft: 0,
  panelTop: 0,
  titleH: 0,
  itemH: 0,
});
// 保存弹窗尺寸信息，供事件处理使用
const popupInfo = ref({
  screenW: 0,
  screenH: 0,
  panelH: 0,
  cancelH: 0,
  contentTop: 0,
  iconSize: 0,
  textSize: 0,
});

function createNativePopup() {
  // #ifdef APP-PLUS
  if (nativeMaskView.value || nativePopupView.value) return;
  const screenW = plus.screen.resolutionWidth;
  const screenH = plus.screen.resolutionHeight;
  const panelH = uni.upx2px(520); // 面板高度（含标题+内容+取消）
  const radius = uni.upx2px(20);

  // 保存尺寸信息
  const iconSize = 50; // 图标大小80px（与图标文件尺寸一致）
  const titleH = uni.upx2px(80);
  const cancelH = uni.upx2px(100);
  const contentTop = uni.upx2px(90) + titleH;
  const textSize = uni.upx2px(24);

  popupInfo.value = {
    screenW,
    screenH,
    panelH,
    cancelH,
    contentTop,
    iconSize,
    textSize,
  };
  // 遮罩
  nativeMaskView.value = new plus.nativeObj.View(
    "native-share-mask",
    {
      left: "0px",
      top: "0px",
      width: screenW + "px",
      height: screenH + "px",
      zindex: 99998,
      touchable: true,
      interceptTouchEvent: true,
    },
    [
      {
        tag: "rect",
        id: "mask",
        position: {
          left: "0px",
          top: "0px",
          width: screenW + "px",
          height: screenH + "px",
        },
        color: "rgba(0,0,0,0.5)",
      },
    ]
  );
  // 面板
  nativePopupView.value = new plus.nativeObj.View(
    "native-share-panel",
    {
      left: "0px",
      top: screenH - panelH + "px",
      width: screenW + "px",
      height: panelH + "px",
      zindex: 99999,
      touchable: true,
      interceptTouchEvent: true,
    },
    []
  );
  // 背景+圆角
  nativePopupView.value.drawRect(
    {
      color: "#FFFFFF",
      radius: radius,
      rectStyles: {},
    },
    {
      left: uni.upx2px(0) + "px",
      top: uni.upx2px(0) + "px",
      width: screenW + "px",
      height: panelH + "px",
    }
  );
  // 标题
  nativePopupView.value.drawText(
    "分享到",
    {
      left: "0px",
      top: uni.upx2px(20) + "px",
      width: screenW + "px",
      height: titleH + "px",
    },
    {
      size: uni.upx2px(32) + "px",
      color: "#333333",
      align: "center",
      verticalAlign: "middle",
      weight: "500",
    }
  );
  const showPatientShare = false;//type.value === "huanjiao";
  const items = showPatientShare
    ? [
        // { id: "it-patient", text: "患者" },
        { id: "it-wechat", text: "微信" },
        { id: "it-moments", text: "朋友圈" },
      ]
    : [
        { id: "it-wechat", text: "微信" },
        { id: "it-moments", text: "朋友圈" },
      ];
  // 三个分享项区域（使用图标）
  const itemW = screenW / items.length;
  const iconTop = contentTop;
  const textTop = iconTop + iconSize + uni.upx2px(16);

  console.log("图标布局信息:", {
    screenW,
    itemW,
    iconSize,
    iconTop,
    contentTop,
  });

  // 图标文件名映射（直接使用文件名，避免路径转换问题）
  const iconFiles = showPatientShare
    ? [
      // "info_icon_1.png", // 患者
        "share_weixin.png", // 微信
        "share_wxc.png", // 朋友圈
      ]
    : [
        "share_weixin.png", // 微信
        "share_wxc.png", // 朋友圈
      ];

  items.forEach((it, idx) => {
    const left = idx * itemW;
    // 计算图标居中位置（确保是整数像素）
    const iconLeft = Math.round(left + (itemW - iconSize) / 2);
    const iconLeftPx = iconLeft;
    // 确保所有图标使用相同的 top 值，保证在一行
    const iconTopPx = Math.round(iconTop);
    const iconSizePx = iconSize;

    console.log(
      `图标 ${idx} (${it.text}): left=${left}, itemW=${itemW.toFixed(
        2
      )}, iconLeft=${iconLeftPx}, iconTop=${iconTopPx}, iconSize=${iconSizePx}`
    );

    // 构建图标本地路径
    // 说明：
    //  - 在 Android 上使用 convertLocalFileSystemURL 可以得到 file:// 路径；
    //  - 但在 iOS 上，plus.nativeObj.View.drawBitmap 对 file:// 路径兼容性较差，
    //    更推荐直接使用 "_www" 相对路径。
    // 这里统一使用 "_www/static/xxx.png" 相对路径，兼容 Android 和 iOS。
    let iconPath = null;
    try {
      const iconFile = iconFiles[idx];
      // 使用 _www 相对路径，避免 iOS 下 file:// 路径导致图片不显示
      iconPath = "_www/static/" + iconFile;
      console.log(`图标 ${it.text} 路径: ${iconPath}`);
    } catch (e) {
      console.log("构建图标路径失败:", e);
      iconPath = null;
    }

    // 绘制图标
    if (iconPath) {
      try {
        console.log(
          `绘制图标 ${it.text}: 位置=(${iconLeftPx}, ${iconTopPx}), 大小=${iconSizePx}x${iconSizePx}`
        );
        // 使用 drawBitmap 绘制图标
        // 尝试不同的参数格式，确保图标不变形且正确显示
        // 格式1: drawBitmap(src, position, options)
        try {
          nativePopupView.value.drawBitmap(
            iconPath,
            {},
            {
              left: iconLeftPx + "px",
              top: iconTopPx + "px",
              width: iconSizePx + "px",
              height: iconSizePx + "px",
            }
          );
        } catch (e1) {
          // 如果格式1失败，尝试格式2: drawBitmap(src, position)
          try {
            nativePopupView.value.drawBitmap(iconPath, {
              left: iconLeftPx + "px",
              top: iconTopPx + "px",
              width: iconSizePx + "px",
              height: iconSizePx + "px",
            });
          } catch (e2) {
            console.log("drawBitmap 两种格式都失败:", e1, e2);
            throw e2;
          }
        }
      } catch (e) {
        console.log("绘制图标失败，使用圆形色块代替:", e);
        // 如果图标加载失败，使用圆形色块作为后备
        const bgColor = idx === 2 ? "#E6162D" : "#07C160";
        nativePopupView.value.drawRect(
          {
            color: bgColor,
            radius: Math.round(iconSize / 2),
          },
          {
            left: Math.round(iconLeft) + "px",
            top: Math.round(iconTop) + "px",
            width: Math.round(iconSize) + "px",
            height: Math.round(iconSize) + "px",
          }
        );
      }
    } else {
      // 如果没有图标路径，使用圆形色块
      const bgColor = idx === 2 ? "#E6162D" : "#07C160";
      nativePopupView.value.drawRect(
        {
          color: bgColor,
          radius: Math.round(iconSize / 2),
        },
        {
          left: Math.round(iconLeft) + "px",
          top: Math.round(iconTop) + "px",
          width: Math.round(iconSize) + "px",
          height: Math.round(iconSize) + "px",
        }
      );
    }

    // 绘制文字
    nativePopupView.value.drawText(
      it.text,
      {
        left: left + "px",
        top: textTop + "px",
        width: itemW + "px",
        height: textSize + uni.upx2px(20) + "px",
      },
      {
        size: textSize + "px",
        color: "#666666",
        align: "center",
        verticalAlign: "top",
      }
    );
  });
  // 取消按钮分割线
  const cancelTop = panelH - cancelH;
  nativePopupView.value.drawRect(
    { color: "#F0F0F0" },
    {
      left: "0px",
      top: cancelTop - 1 + "px",
      width: screenW + "px",
      height: "1px",
    }
  );
  nativePopupView.value.drawText(
    "取消",
    {
      left: "0px",
      top: cancelTop + "px",
      width: screenW + "px",
      height: cancelH + "px",
    },
    {
      size: uni.upx2px(32) + "px",
      color: "#333333",
      align: "center",
      verticalAlign: "middle",
    }
  );
  // 事件处理函数
  const lockShareAction = () => {
    if (shareActionLocked.value) return false;
    shareActionLocked.value = true;
    setTimeout(() => {
      shareActionLocked.value = false;
    }, 300);
    return true;
  };
  const handleMaskClick = () => {
    if (!lockShareAction()) return;
    console.log("遮罩被点击");
    closeNativePopup();
  };

  const handlePanelClick = (e) => {
    if (!lockShareAction()) return;
    console.log("面板被点击", e);
    const info = popupInfo.value;

    // 获取点击坐标
    let x = 0;
    let y = 0;

    // 尝试多种方式获取坐标
    if (e.clientX !== undefined && e.clientY !== undefined) {
      x = e.clientX;
      y = e.clientY;
    } else if (e.pageX !== undefined && e.pageY !== undefined) {
      x = e.pageX;
      y = e.pageY;
    } else if (e.touches && e.touches.length > 0) {
      x = e.touches[0].clientX || e.touches[0].pageX || 0;
      y = e.touches[0].clientY || e.touches[0].pageY || 0;
    } else if (e.changedTouches && e.changedTouches.length > 0) {
      x = e.changedTouches[0].clientX || e.changedTouches[0].pageX || 0;
      y = e.changedTouches[0].clientY || e.changedTouches[0].pageY || 0;
    }

    console.log("原始坐标:", x, y);
    console.log("屏幕信息:", info);

    if (!x || !y) {
      console.log("坐标无效");
      return;
    }

    // 判断坐标是相对于屏幕还是相对于视图
    // 如果 y 小于 panelH，说明是相对于视图的坐标
    // 如果 y 大于等于 screenH - panelH，说明是相对于屏幕的坐标
    let relativeY = y;
    let relativeX = x;

    if (y < info.panelH) {
      // 相对于视图的坐标，直接使用
      relativeY = y;
      relativeX = x;
      console.log("使用相对于视图的坐标:", relativeX, relativeY);
    } else if (y >= info.screenH - info.panelH) {
      // 相对于屏幕的坐标，转换为相对于视图的坐标
      relativeY = y - (info.screenH - info.panelH);
      relativeX = x;
      console.log(
        "使用相对于屏幕的坐标，转换为相对视图:",
        relativeX,
        relativeY
      );
    } else {
      // 可能是其他情况，尝试直接使用
      console.log("坐标类型不确定，尝试直接使用");
    }

    // 取消区域（底部取消按钮）- 相对于视图
    const cancelTop = info.panelH - info.cancelH;
    console.log(
      "取消区域判断: relativeY =",
      relativeY,
      ", cancelTop =",
      cancelTop
    );
    if (relativeY >= cancelTop) {
      console.log("点击了取消按钮");
      closeNativePopup();
      return;
    }

    // 分享项区域（图标+文字区域）- 相对于视图
    const shareAreaTop = info.contentTop;
    const shareAreaBottom =
      shareAreaTop + info.iconSize + info.textSize + uni.upx2px(20);

    console.log(
      "分享区域: relativeY =",
      relativeY,
      ", 范围 =",
      shareAreaTop,
      "到",
      shareAreaBottom
    );

    if (relativeY >= shareAreaTop && relativeY <= shareAreaBottom) {
      // 计算点击的是第几个分享项
      const itemWidth = info.screenW / items.length;
      const idx = Math.min(
        items.length - 1,
        Math.max(0, Math.floor(relativeX / itemWidth))
      );

      console.log(
        "点击了分享项:",
        idx,
        ", x =",
        relativeX,
        ", itemWidth =",
        itemWidth
      );

      if (showPatientShare) {
        if (idx === 0) {
          console.log("执行患者选择");
          closeNativePopup();
          showSelectNativePopup();
        } else if (idx === 1) {
          console.log("执行微信分享");
          shareToWechat();
          closeNativePopup();
        } else if (idx === 2) {
          console.log("执行朋友圈分享");
          shareToMoments();
          closeNativePopup();
        }
      } else {
        if (idx === 0) {
          console.log("执行微信分享");
          shareToWechat();
          closeNativePopup();
        } else if (idx === 1) {
          console.log("执行朋友圈分享");
          shareToMoments();
          closeNativePopup();
        }
      }
    } else {
      console.log(
        "点击位置不在分享区域内, relativeY =",
        relativeY,
        ", 需要范围:",
        shareAreaTop,
        "到",
        shareAreaBottom
      );
    }
  };

  // 仅监听 touchend，避免 click/touchstart/touchend 重复触发
  nativeMaskView.value.addEventListener("touchend", handleMaskClick, false);
  nativePopupView.value.addEventListener("touchend", handlePanelClick, false);
  // #endif
}

function showNativePopup() {
  // #ifdef APP-PLUS
  if (popupShowing.value) return;
  if (!nativeMaskView.value || !nativePopupView.value) {
    createNativePopup();
  }
  nativeMaskView.value && nativeMaskView.value.show();
  nativePopupView.value && nativePopupView.value.show();
  popupShowing.value = true;
  // #endif
}

function closeNativePopup() {
  // #ifdef APP-PLUS
  if (!popupShowing.value) return;
  nativeMaskView.value && nativeMaskView.value.hide();
  nativePopupView.value && nativePopupView.value.hide();
  popupShowing.value = false;
  // #endif
}
function createSelectNativePopup() {
  // #ifdef APP-PLUS
  if (nativeSelectMaskView.value || nativeSelectPopupView.value) return;
  const screenW = plus.screen.resolutionWidth;
  const screenH = plus.screen.resolutionHeight;
  const panelW = Math.round(uni.upx2px(650));
  const titleH = Math.round(uni.upx2px(96));
  const itemH = Math.round(uni.upx2px(110));
  const panelH = titleH + itemH * 2 + 2;
  const panelLeft = Math.round((screenW - panelW) / 2);
  const panelTop = Math.round((screenH - panelH) / 2);

  selectPopupInfo.value = {
    screenW,
    screenH,
    panelW,
    panelH,
    panelLeft,
    panelTop,
    titleH,
    itemH,
  };

  nativeSelectMaskView.value = new plus.nativeObj.View(
    "native-select-mask",
    {
      left: "0px",
      top: "0px",
      width: `${screenW}px`,
      height: `${screenH}px`,
      zindex: 99998,
      touchable: true,
      interceptTouchEvent: true,
    },
    [
      {
        tag: "rect",
        id: "mask",
        position: {
          left: "0px",
          top: "0px",
          width: `${screenW}px`,
          height: `${screenH}px`,
        },
        color: "rgba(0,0,0,0.6)",
      },
    ]
  );

  nativeSelectPopupView.value = new plus.nativeObj.View(
    "native-select-panel",
    {
      left: `${panelLeft}px`,
      top: `${panelTop}px`,
      width: `${panelW}px`,
      height: `${panelH}px`,
      zindex: 99999,
      touchable: true,
      interceptTouchEvent: true,
    },
    []
  );

  const radius = Math.round(uni.upx2px(16));
  nativeSelectPopupView.value.drawRect(
    { color: "#FFFFFF", radius, rectStyles: {} },
    { left: "0px", top: "0px", width: `${panelW}px`, height: `${panelH}px` }
  );
  nativeSelectPopupView.value.drawText(
    "温馨提示",
    { left: "0px", top: "0px", width: `${panelW}px`, height: `${titleH}px` },
    {
      size: `${Math.round(uni.upx2px(34))}px`,
      color: "#8B2316",
      align: "center",
      verticalAlign: "middle",
      weight: "500",
    }
  );
  nativeSelectPopupView.value.drawRect(
    { color: "#EEEEEE" },
    { left: "0px", top: `${titleH}px`, width: `${panelW}px`, height: "1px" }
  );
  nativeSelectPopupView.value.drawText(
    "单独选择",
    {
      left: "0px",
      top: `${titleH}px`,
      width: `${panelW}px`,
      height: `${itemH}px`,
    },
    {
      size: `${Math.round(uni.upx2px(30))}px`,
      color: "#333333",
      align: "center",
      verticalAlign: "middle",
    }
  );
  nativeSelectPopupView.value.drawRect(
    { color: "#EEEEEE" },
    {
      left: "0px",
      top: `${titleH + itemH}px`,
      width: `${panelW}px`,
      height: "1px",
    }
  );
  nativeSelectPopupView.value.drawText(
    "分组选择",
    {
      left: "0px",
      top: `${titleH + itemH}px`,
      width: `${panelW}px`,
      height: `${itemH}px`,
    },
    {
      size: `${Math.round(uni.upx2px(30))}px`,
      color: "#333333",
      align: "center",
      verticalAlign: "middle",
    }
  );

  const navigateFromSelectPopup = (url) => {
    const now = Date.now();
    if (selectNavigateLocked.value) return;
    if (now - Number(lastSelectNavigateAt.value || 0) < 800) return;
    selectNavigateLocked.value = true;
    lastSelectNavigateAt.value = now;
    if(url.includes('selectPatient')){
      uni.sendNativeEvent(
        "goSelectPatientPage",
        {
          msg: "goSelectPatientPage",
        },
        (ret) => {
          console.log(ret);
          setTimeout(() => {
            selectNavigateLocked.value = false;
          }, 500);
        }
      );
    }else{
        uni.navigateTo({
      url,
      complete: () => {
        setTimeout(() => {
          selectNavigateLocked.value = false;
        }, 500);
      },
    });
    }
    
    
  };
  const lockSelectAction = () => {
    if (selectActionLocked.value) return false;
    selectActionLocked.value = true;
    setTimeout(() => {
      selectActionLocked.value = false;
    }, 300);
    return true;
  };
  const handleMaskClick = () => {
    if (!lockSelectAction()) return;
    closeSelectNativePopup();
  };
  const handlePanelClick = (e) => {
    if (!lockSelectAction()) return;
    const info = selectPopupInfo.value;
    let x = 0;
    let y = 0;
    if (e.clientX !== undefined && e.clientY !== undefined) {
      x = e.clientX;
      y = e.clientY;
    } else if (e.pageX !== undefined && e.pageY !== undefined) {
      x = e.pageX;
      y = e.pageY;
    } else if (e.touches && e.touches.length > 0) {
      x = e.touches[0].clientX || e.touches[0].pageX || 0;
      y = e.touches[0].clientY || e.touches[0].pageY || 0;
    } else if (e.changedTouches && e.changedTouches.length > 0) {
      x = e.changedTouches[0].clientX || e.changedTouches[0].pageX || 0;
      y = e.changedTouches[0].clientY || e.changedTouches[0].pageY || 0;
    }
    if (!x || !y) return;
    const relativeY = y > info.panelH ? y - info.panelTop : y;
    if (relativeY >= info.titleH && relativeY < info.titleH + info.itemH) {
      closeSelectNativePopup();
      navigateFromSelectPopup(
        "/pages_app/selectPatient/selectPatient?from=patientVideo"
      );
      return;
    }
    if (
      relativeY >= info.titleH + info.itemH &&
      relativeY < info.titleH + info.itemH * 2
    ) {
      closeSelectNativePopup();
      navigateFromSelectPopup(
        "/pages_chat/patientGroup/patientGroup?from=patientVideo"
      );
    }
  };

  nativeSelectMaskView.value.addEventListener(
    "touchend",
    handleMaskClick,
    false
  );
  nativeSelectPopupView.value.addEventListener(
    "touchend",
    handlePanelClick,
    false
  );
  // #endif
}
function showSelectNativePopup() {
  // #ifdef APP-PLUS
  if (selectPopupShowing.value) return;
  if (!nativeSelectMaskView.value || !nativeSelectPopupView.value) {
    createSelectNativePopup();
  }
  nativeSelectMaskView.value && nativeSelectMaskView.value.show();
  nativeSelectPopupView.value && nativeSelectPopupView.value.show();
  selectPopupShowing.value = true;
  // #endif
}
function closeSelectNativePopup() {
  // #ifdef APP-PLUS
  if (!selectPopupShowing.value) return;
  nativeSelectMaskView.value && nativeSelectMaskView.value.hide();
  nativeSelectPopupView.value && nativeSelectPopupView.value.hide();
  selectPopupShowing.value = false;
  // #endif
}

// 分享到微信
const shareToWechat = () => {
  addpoint();
  // #ifdef APP-PLUS
  // 使用系统分享
  uni.downloadFile({
    url: shareImg.value,
    success: function (res) {
      uni.compressImage({
        src: res.tempFilePath,
        quality: 60,
        success: function (res2) {
          uni.share({
            provider: "weixin",
            scene: "WXSceneSession",
            type: 0,
            title: shareTitle.value,
            summary: summary.value,
            href: safeUrl.value,
            imageUrl: res2.tempFilePath,
            success: function (res) {
              console.log("分享微信成功");
              console.log("success:" + JSON.stringify(res));
            },
            fail: function (err) {
              console.log("fail:" + JSON.stringify(err));
            },
          });
        },
      });
    },
  });

  // #endif

  // #ifdef H5
  // H5环境下的分享
  if (navigator.share) {
    navigator
      .share({
        title: "肝胆相照APP",
        text: "专业的医疗健康平台，快来下载体验吧！",
        url: shareLink.value,
      })
      .then(() => {
        uni.showToast({
          title: "分享成功",
          icon: "success",
        });
      })
      .catch(() => {
        uni.showToast({
          title: "分享失败",
          icon: "none",
        });
      });
  } else {
    // 复制到剪贴板
    uni.setClipboardData({
      data:
        "肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：" +
        shareLink.value,
      success: () => {
        uni.showToast({
          title: "已复制到剪贴板",
          icon: "success",
        });
      },
    });
  }
  // #endif

  // #ifdef MP-WEIXIN
  // 微信小程序分享
  uni.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage", "shareTimeline"],
  });
  // #endif

  closeShare();
};

// 页面隐藏/销毁时清理原生弹窗
onHide(() => {
  // #ifdef APP-PLUS
  closeNativePopup();
  closeSelectNativePopup();
  // #endif
});
onUnload(() => {
  // #ifdef APP-PLUS
  try {
    appPlusWebview.value &&
      appPlusWebview.value.close &&
      appPlusWebview.value.close();
    nativeMaskView.value &&
      nativeMaskView.value.close &&
      nativeMaskView.value.close();
    nativePopupView.value &&
      nativePopupView.value.close &&
      nativePopupView.value.close();
    nativeSelectMaskView.value &&
      nativeSelectMaskView.value.close &&
      nativeSelectMaskView.value.close();
    nativeSelectPopupView.value &&
      nativeSelectPopupView.value.close &&
      nativeSelectPopupView.value.close();
  } catch (e) {}
  nativeMaskView.value = null;
  nativePopupView.value = null;
  nativeSelectMaskView.value = null;
  nativeSelectPopupView.value = null;
  appPlusWebview.value = null;
  popupShowing.value = false;
  selectPopupShowing.value = false;
  // #endif
});
// 分享到朋友圈
const shareToMoments = () => {
  addpoint();
  // #ifdef APP-PLUS
  uni.downloadFile({
    url: shareImg.value,
    success: function (res) {
      uni.compressImage({
        src: res.tempFilePath,
        quality: 60,
        success: function (res2) {
          uni.share({
            provider: "weixin",
            scene: "WXSceneTimeline",
            type: 0,
            title: shareTitle.value,
            summary: summary.value,
            href: safeUrl.value,
            imageUrl: res2.tempFilePath,
            success: function (res) {
              console.log("success:" + JSON.stringify(res));
              //addpoint();
            },
            fail: function (err) {
              console.log("fail:" + JSON.stringify(err));
            },
          });
        },
        fail: function (err) {
          console.log("fail:" + JSON.stringify(err));
        },
      });
    },
  });

  // #endif

  // #ifdef H5
  // 复制到剪贴板
  uni.setClipboardData({
    data: "肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com",
    success: () => {
      uni.showToast({
        title: "已复制到剪贴板，可分享到朋友圈",
        icon: "success",
      });
    },
  });
  // #endif

  // #ifdef MP-WEIXIN
  uni.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage", "shareTimeline"],
  });
  // #endif

  closeShare();
};

// 分享到新浪微博
const shareToWeibo = () => {
  // #ifdef APP-PLUS
  uni.share({
    provider: "sinaweibo",
    type: 0,
    title: shareTitle.value,
    summary: summary.value,
    href: safeUrl.value,
    imageUrl: logoImg,
    success: function (res) {
      console.log("分享成功");
    },
    fail: function (err) {
      console.log("fail:" + JSON.stringify(err));
    },
  });
  // plus.share.sendWithSystem({
  // 	type: 'text',
  // 	content: '肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com'
  // }, () => {
  // 	uni.showToast({
  // 		title: '分享成功',
  // 		icon: 'success'
  // 	})
  // }, (err) => {
  // 	console.log('分享失败：', err)
  // 	uni.showToast({
  // 		title: '分享失败',
  // 		icon: 'none'
  // 	})
  // })
  // #endif

  // #ifdef H5
  // 复制到剪贴板
  uni.setClipboardData({
    data: "肝胆相照APP - 专业的医疗健康平台，快来下载体验吧！\n下载链接：https://www.igandan.com",
    success: () => {
      uni.showToast({
        title: "已复制到剪贴板，可分享到微博",
        icon: "success",
      });
    },
  });
  // #endif

  closeShare();
};
</script>

<style>
.bottom-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 55px;
  display: flex;
  align-items: center;
  z-index: 9999999999999999999999999999999999999999999999999999999999999999;
  background-color: #fff;
}
.bottom-cell {
  flex: 1;
  height: 100%;
  border-right: 2rpx solid #ccc;
  border-top: 2rpx solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
}
.bottom-cell:last-child {
  border-right: none;
}
.bottom-cell-img {
  width: 40rpx;
  height: 40rpx;
}
.bottom-cell-text {
  margin-left: 8rpx;
  font-size: 28rpx;
  color: #666;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10000000;
}
/* 分享弹窗样式 */
.share-popup {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx 0 0;
}
.share-img {
  width: 100rpx;
  height: 100rpx;
}
.share-title {
  text-align: center;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 40rpx;
  font-weight: 500;
}

.share-content {
  display: flex;
  justify-content: space-around;
  padding: 0 40rpx 40rpx;
}

.share-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.share-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}

.wechat-icon {
  background-color: #07c160;
}

.moments-icon {
  background-color: #07c160;
}

.weibo-icon {
  background-color: #e6162d;
}

.qq-icon {
  background-color: #12b7f5;
}

.share-icon-text {
  font-size: 50rpx;
  color: #fff;
  font-weight: bold;
}

.share-text {
  font-size: 24rpx;
  color: #666;
}

.share-cancel {
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1rpx solid #f0f0f0;
  font-size: 32rpx;
  color: #333;
}

.share-cancel:active {
  background-color: #f5f5f5;
}
.nav-actions .share-img-icon {
  width: 40rpx;
  height: 40rpx;
}
.nav-actions .collect-img-icon {
  width: 40rpx;
  height: 40rpx;
}
.nav-actions {
  display: flex;
  align-items: center;
}
.back-hit {
  height: 44px;
  padding: 0 12px;
  display: flex;
  align-items: center;
}

.container {
  height: 100vh;
  position: relative;
  z-index: 0;
  overflow: scroll;
}
.tip {
  padding: 24rpx;
  color: #666;
  font-size: 28rpx;
}
</style>
