// @ts-nocheck
import { Component } from "react";
import { View, Text, Image } from "@tarojs/components";
import "./index.scss";
import { AtButton, AtInput, AtTabBar } from "taro-ui";
import React, { useCallback, useEffect, useState, useRef } from "react";
import { AtGrid } from "taro-ui";
import { Swiper, SwiperItem } from "@tarojs/components";
import { AtCard } from "taro-ui";
import { AtImagePicker } from "taro-ui";
import Taro from "@tarojs/taro";
import { AtAvatar } from "taro-ui";
import { AtTag } from "taro-ui";
import { AtList, AtListItem } from "taro-ui";
import { AtForm, AtMessage, AtDrawer, AtIcon } from "taro-ui";
import { marked } from "marked";
import infoText from "./info.md";
import bookText from "./book.md";
// import youtubeIco from "../../images/youtube.ico";

marked.setOptions({
  breaks: true, // 是否回车换行
  gfm: true, //使用经批准的 GitHub Flavored Markdown (GFM) 规范
  // pedantic: true, //严格模式
  // highlight(code:any, lang:any) {
  //   //  语法高亮
  //   let val = code;
  //   if (lang) {
  //     val = hljs.highlight(lang, code).value;
  //   } else {
  //     val = hljs.highlightAuto(code).value;
  //   }
  //   return val;
  // },
});

// const renderer = new marked.Renderer();
// // 使用拓展
// marked.use({ renderer });

// export default class Index extends Component {
const Book = () => {
  const [book, setbook] = useState(window.localStorage.getItem("book"));
  const [markText, setmarkText] = useState(book == 1 ? bookText : infoText);
  const [isWeChat, setisWeChat] = useState(false);
  const [show, setshow] = useState(false);

  const [headers, setHeaders] = useState([]); // 存储所有 <h1> 的内容
  const contentRef = useRef(null); // 用于获取渲染后的 DOM

  useEffect(() => {
    //  window.localStorage.removeItem("book");
    isWeChatFun();
  }, []);

  useEffect(() => {
    if (contentRef.current) {
      const h1Elements = contentRef.current.querySelectorAll("h1");
      const h2Elements = contentRef.current.querySelectorAll("h2");

      const h1Texts = Array.from(h1Elements).map((el) => el.textContent);
      const h2Texts = Array.from(h2Elements).map((el) => el.textContent);

      setHeaders(h1Texts);
      // console.log("获取到的 H1 标题:"); // 控制台查看
      console.log("获取到的 H1 标题:", h1Texts); // 控制台查看
      console.log("获取到的 H2 标题:", h2Texts); // 控制台查看
    }
  }, [markText]); // 监听 HTML 内容变化

  const handleJump = (text) => {
    const h1Elements = contentRef.current.querySelectorAll("h1");
    for (let h1 of h1Elements) {
      if (h1.textContent.trim() === text.trim()) {
        // if (h1.textContent === text) {
        h1.scrollIntoView({ behavior: "smooth" });
        break;
      }
    }
  };

  // const handleClick = (value) => {
  //   // 跳转到目的页面，在当前页面打开
  //   Taro.navigateTo({
  //     url: "/pages/index/index",
  //   });
  // };

  // 是否在微信客户端
  const isWeChatFun = () => {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf("micromessenger") != -1) {
      setisWeChat(true);
      return true;
    } else {
      setisWeChat(false);
      return false;
    }
  };

  const payh5 = (type, total_fee = 1000) => {
    // console.log("111");
    Taro.request({
      method: "POST",
      url: `${process.env.TARO_API_API}/payh5`, //仅为示例，并非真实的接口地址
      // url: "https://pay.hackrobot.cn${process.env.TARO_API_API}/payh5", //仅为示例，并非真实的接口地址

      data: {
        callback_url: window.location.href,
        openid: window.localStorage.getItem("openid"),
        total_fee: total_fee, // 金额,单位:分
        type: type, //订单类型 book/meetup/video/vip
      },
      header: {
        "content-type": "application/json", // 默认值
      },
      success: function (res) {
        console.log(res.data);
        // window.alert(res.data.jsapi);
        WeixinJSBridge.invoke(
          "getBrandWCPayRequest",
          {
            // 以下6个支付参数通过payjs的jsapi接口获取
            // appId: "wxc5205a653b0259bf",
            // timeStamp: "1701401644",
            // nonceStr: "KhOYB0wFV6j9qyQK",
            // package: "prepay_id=wx01113404850024729b35f4d69b73500000",
            // signType: "MD5",
            // paySign: "2A823C8D47CCF871C6C65A56DC228CF8",
            ...(res?.data?.jsapi ?? {}),
          },
          function (res) {
            // 支付成功
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              window.localStorage.setItem(type, 1); //订单类型 book/meetup/video/vip
              WeixinJSBridge.call("closeWindow");
            }
          }
        );
      },
    });
  };

  return (
    <>
      <View className="book_header_div"></View>
      <View className="book_header">
        <View
          className="book_header_left"
          onClick={() => {
            Taro.redirectTo({
              url: `/`,
            });
            // Taro.navigateBack({
            //   delta: 1, // 表示返回的页面数，默认是 1，表示返回上一页
            // });
          }}
        >
          <AtIcon value="chevron-left"></AtIcon>
        </View>
        <View className="book_header_middle">{`云手机`}</View>
        <View
          className="book_header_right"
          onClick={() => {
            setshow(!show);
          }}
        >
          <AtIcon value="bullet-list"></AtIcon>
        </View>
      </View>
      <View className="Book">
        <View
          ref={contentRef}
          className="markdown-body" // 添加 GitHub Markdown 主题类
          dangerouslySetInnerHTML={{
            // __html: marked(markText),
            __html: marked(book == 1 ? bookText : infoText),
          }}
        ></View>

        <AtDrawer
          className="book_AtDrawer"
          show={show}
          mask
          items={headers}
          onItemClick={(index) => {
            handleJump(headers[index]);
          }}
          onClose={() => {
            setshow(false);
          }}
        >
          <View className="drawer-item"></View>
          {/* <View className="drawer-item">如果items没有数据就会展示children</View> */}
          {/* <View className="drawer-item">
          这是自定义内容 <AtIcon value="home" size="20" />
        </View> */}
        </AtDrawer>

        {/* 判断是否是微信 */}
        {!isWeChat && <div style={{ color: "red" }}>请在手机微信打开</div>}

        {/* 判断有没有wxid */}
        {book != 1 ? (
          <AtButton
            type="primary"
            size="normal"
            className="joinSalon"
            onClick={() => {
              if (book == 1) {
                return false;
              } else {
                if (!!isWeChat) {
                  //98元
                  payh5("book", 9800);
                } else {
                  window.location.href = `https://mp.weixin.qq.com/s/16xcMIgxEEGBPY7fanNq0g`;
                }
              }
            }}
          >
            {`阅读更多`}
          </AtButton>
        ) : (
          <span style={{ color: "green" }}>持续更新中....</span>
        )}

        {/* <AtButton
          type="primary"
          size="normal"
          className="joinSalon"
          onClick={() => {
            if (book == 1) {
              return false;
            } else {
              if (!!isWeChat) {
                // 198元
                payh5("group", 29800);
              } else {
                window.location.href = `https://mp.weixin.qq.com/s/GBU3THKaXRRkdpZXH_18jw`;
              }
            }
          }}
        >
          {`游民社群`}
        </AtButton> */}
      </View>
    </>
  );
};

export default Book;
