import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import I18nBehavior from "../../../../i18n/behavior";
import TickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";

// module/health/pages/scheme/scheme.ts
import { healthSchemeMethod } from "../../request";

import { toReportPage } from "../../router";
Component({
  behaviors: [I18nBehavior, PageContainerBehavior, TickleBehavior],
  lifetimes: {
    attached() {
      this.getHealthScheme(this.data.id);
    },
  },
  properties: {
    id: { type: String, value: "" },
  },
  data: {
    i18n: {
      report: { title: '报告' },
      scheme: { title: '方案', date: '' },
      orderText:{goPay:'去确认'}
    },
    dataset: null,
    schemeId: "",
    healthIndex: { data: [], loading: false, message: "" },
    showQrCodePopup: false,
    qrCodeImageUrl: "",
  },
  observers: {},
  methods: {
    async getHealthScheme(id: string) {
      wx.showLoading({ title: "加载中" });
      try {
        const dataset = await healthSchemeMethod(id);

        this.setData({ dataset });
      } catch (error) {
        console.log(error);

        getTickleContext
          .call(this)
          .showErrorMessage(error.errMsg || error.message, 0);
      }
      wx.hideLoading();
    },
    toReportPage() {
      toReportPage(this.data.id);
    },
    // 跳转到商品选择页面
    goToProductPage() {
      wx.setStorageSync('healthAnalysisReportId', this.data.id);
      if (this.data.id) {
        wx.redirectTo({
          url: `/module/order/pages/select-goods/select-goods?healthAnalysisReportId=${this.data.id}`,
          fail: (err) => {
            getTickleContext.call(this).showWarnMessage(err.errMsg || "跳转失败");
          },
        });
      } else {
        wx.showToast({
          title: "健康评估报告ID不能为空",
          icon: "none",
        });
      }
    },
    // 去购买
    goBuy(this: any, e: any) {
      const item = e.currentTarget.dataset.item || {};
      const type: string = (item.buyType || "").toLowerCase();
      const url: string = item.buyUrl || "";
      const shortImageUrl: string = item.shortImageUrl || "";
      console.log(item, "item", type, url);
      //  跳转小程序
      if (type === "miniprogram") {
        // 如果没有跳转链接，直接显示小程序码或提示错误
        if (!url) {
          if (shortImageUrl) {
            this.setData({
              showQrCodePopup: true,
              qrCodeImageUrl: shortImageUrl,
            });
          } else {
            getTickleContext.call(this).showWarnMessage("缺少小程序跳转参数");
          }
          return;
        }

        // 解析 miniprogram:// 格式的 URL
        let parsedAppId = "";
        let parsedPath = "";
        const isMiniprogramUrl = url.startsWith("miniprogram://");

        if (isMiniprogramUrl) {
          // 解析 miniprogram://?appid=xxx&path=xxx 格式
          try {
            // 提取查询参数字符串（去掉 miniprogram://? 前缀）
            const queryString = url.replace(/^miniprogram:\/\/(\?)?/, "");
            // 解析查询参数
            const params: Record<string, string> = {};
            queryString.split("&").forEach((param) => {
              const [key, value] = param.split("=");
              if (key && value) {
                params[key] = decodeURIComponent(value);
              }
            });
            parsedAppId = params.appid || "";
            parsedPath = params.path || "";
          } catch (error) {
            console.error("解析 miniprogram:// URL 失败:", error);
          }
        }

        // 统一的错误处理函数：显示小程序码或错误提示
        const showErrorOrQrCode = (errMsg?: string) => {
          if (shortImageUrl) {
            this.setData({
              showQrCodePopup: true,
              qrCodeImageUrl: shortImageUrl,
            });
          } else {
            getTickleContext
              .call(this)
              .showWarnMessage(errMsg || "跳转小程序失败");
          }
        };

        // 统一的跳转函数：使用 appId + path 方式跳转
        const navigateWithAppIdAndPath = (appId: string, path: string) => {
          wx.navigateToMiniProgram({
            appId: appId,
            path: path,
            envVersion: "release",
            fail: (pathErr) => {
              if (
                pathErr.errMsg.includes("navigateToMiniProgram:fail cancel")
              ) {
                console.log("用户取消appid小程序跳转");
              } else {
                showErrorOrQrCode(pathErr.errMsg);
              }
            },
          });
        };

        // 如果是 miniprogram:// 格式，直接使用 appId + path 方式跳转
        if (isMiniprogramUrl) {
          if (parsedAppId && parsedPath) {
            navigateWithAppIdAndPath(parsedAppId, parsedPath);
          }
        } else {
          // 短链接格式，优先使用短链接方式跳转
          wx.navigateToMiniProgram({
            shortLink: url,
            envVersion: "release",
            fail: (err) => {
              if (err.errMsg.includes("navigateToMiniProgram:fail cancel")) {
                console.log("用户取消短链跳转");
              } else {
                // 短链接失败，尝试使用 appId + path 方式跳转
                if (parsedAppId && parsedPath) {
                  navigateWithAppIdAndPath(parsedAppId, parsedPath);
                } else {
                  // 没有 appId 和 path，直接显示弹窗或错误提示
                  showErrorOrQrCode(err.errMsg || "跳转小程序失败");
                }
              }
            },
          });
        }
      } else if (type === "url") {
        // h5链接
        if (!url) {
          getTickleContext.call(this).showWarnMessage("无有效链接");
          return;
        }
        wx.navigateTo({
          url: "/module/article/pages/science-info/science-info",
          success: (res) => {
            res.eventChannel?.emit?.("load", {
              title: item.title || "详情",
              url,
            });
          },
          fail: (err) => {
            getTickleContext
              .call(this)
              .showWarnMessage(err.errMsg || "打开页面失败");
          },
        });
        return;
      } else {
        // 无法识别
        getTickleContext.call(this).showWarnMessage("未识别的跳转类型");
      }
    },
    // 关闭小程序码弹窗
    closeQrCodePopup(e?: any) {
      // 如果 visible-change 事件触发且 visible 为 false，才关闭
      if (e === undefined || !e.detail?.visible) {
        this.setData({
          showQrCodePopup: false,
          qrCodeImageUrl: "",
        });
      }
    },
  },
});
