// @ts-nocheck
import { Component } from "react";
import { View, Text, Image } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
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 { 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";
import hackrobot from "../../images/hackrobot.jpg";
// PocketBase 配置
const PB_URL = "https://pocketbase.hackrobot.cn";
const pb = new PocketBase(PB_URL);

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

  const [paidType, setPaidType] = useState(null); // 新增：支付类型 'vip' | 'book' | null

  // 把这些变量名全部改为 userId
  const [userId, setUserId] = useState(Taro.getStorageSync("userId") || null);
  const [loading, setLoading] = useState(true); // 新增：加载状态
  const router = useRouter(); // Taro 3+ 获取路由参数

  const [vipbook, setVipbook] = useState(false);  //是否在vip群打开


  // 在组件挂载时检测 referrer
  useEffect(() => {
    if (router && router.params && router.params.type === 'vipbook') {
      setVipbook(true)
    } else {
      setVipbook(false)
    }
  }, []);

  // 保存 userId 到本地
  const saveUserId = (id) => {
    Taro.setStorageSync("userId", id);
    setUserId(id);
  };

  // 检查本地是否已有支付类型
  const getLocalPaidType = () => {
    return Taro.getStorageSync("paidType") || null;
  };

  // 保存支付类型到本地
  const savePaidType = (type) => {
    Taro.setStorageSync("paidType", type);
    setPaidType(type);
  };

  // 查询 PocketBase 是否支付过
  const checkPaymentFromPB = async (userId) => {
    // window.alert('查询pocketbase')
    try {
      // 查询 payments 表中该 user_id 的记录，按创建时间倒序（最新的一笔）
      const records = await pb.collection("payments").getList(1, 1, {
        filter: `user_id = "${userId}"`,
        sort: "-created", // 最新支付优先
      });

      if (records.items.length > 0) {
        alert("records.items[0]", records.items[0]);
        const latestType = records.items[0].type; // 取最新一笔的 type
        const dbUserId = records.items[0].user_id; // 数据库里的真实 user_id
        // window.alert('latestType', dbUserId)
        savePaidType(latestType);

        saveUserId(dbUserId); // 正确保存真实的 user_id
        console.log("从 PocketBase 查询到已支付:", latestType);
        return latestType;
      } else {
        // window.alert('未找到支付记录')

        console.log("未找到支付记录");
        savePaidType(null);
        return null;
      }
    } catch (err) {
      // window.alert('查询 PocketBase 失败', err)
      console.error("查询 PocketBase 失败:", err);
      // 网络错误时不影响本地缓存，使用本地旧值
      return getLocalPaidType();
    } finally {
    }
  };

  // 清空所有本地存储（测试专用）
  const clearAllStorage = () => {
    try {
      // 清空 Taro 的 storage（推荐方式）
      Taro.clearStorageSync();

      // 同时清空 window.localStorage（H5 环境兼容）
      if (typeof window !== "undefined" && window.localStorage) {
        window.localStorage.clear();
      }

      // 可选：手动清除你知道的关键字段，防止残留
      Taro.removeStorageSync("userId");
      Taro.removeStorageSync("paidType");
      Taro.removeStorageSync("openid");
      Taro.removeStorageSync("wxid");

      // 状态重置
      setPaidType(null);
      setUserName(null);
      setLoading(false);

      Taro.showToast({
        title: "本地存储已清空",
        icon: "success",
        duration: 2000,
      });

      // 可选：刷新页面让效果立即生效
      setTimeout(() => {
        // window.location.reload();
      }, 1000);
    } catch (error) {
      console.error("清空存储失败:", error);
      Taro.showToast({
        title: "清空存储失败",
        icon: "none",
      });
    }
  };

  useEffect(() => {
    // 判断是否在微信
    isWeChatFun();
    // 方法1：Taro 3+ 推荐方式（支持小程序 + H5）
    if (router && router.params && router.params.type === "clean") {
      clearAllStorage();
      return;
    }

    const init = async () => {
      const currentUserId = getOrCreateUserId(); // 确保 userId 存在

      const localType = getLocalPaidType();
      const localUserId = Taro.getStorageSync("userId");

      // 只有当本地同时有 paidType 和 userId 时，才信任本地缓存
      if (localType && localUserId) {
        setPaidType(localType);
        setUserId(localUserId);
        setLoading(false);
        console.log("使用本地缓存支付状态:", localType);
        return;
      }

      // 否则去 PocketBase 查最新状态
      await checkPaymentFromPB(currentUserId);
      setLoading(false);
    };

    init();
  }, []);

  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 payh51111 = (type, total_fee = 1000) => {
    Taro.request({
      method: "POST",
      url: `${process.env.TARO_API_API}/payh5`,
      data: {
        total_fee: total_fee,
        type: type,
        // callback_url 临时不传
      },
      header: {
        "content-type": "application/json",
      },
      success: (res) => {
        if (res.data?.status === "ok" && res.data?.xorpay_params) {
          // 创建隐藏 form POST 到 XorPay
          const form = document.createElement("form");
          form.method = "POST";
          form.action = res.data.xorpay_url;
          form.style.display = "none";

          for (const key in res.data.xorpay_params) {
            const input = document.createElement("input");
            input.type = "hidden";
            input.name = key;
            input.value = res.data.xorpay_params[key];
            form.appendChild(input);
          }

          document.body.appendChild(form);
          form.submit();
        } else {
          Taro.showToast({
            title: "支付发起失败",
            icon: "none",
          });
        }
      },
      fail: () => {
        Taro.showToast({
          title: "网络错误",
          icon: "none",
        });
      },
    });
  };

  // 生成或获取 userId（修改为无下划线）
  const getOrCreateUserId = () => {
    let userId = Taro.getStorageSync("userId");
    if (!userId) {
      // 修改这里：去掉下划线
      userId = `user${Date.now()}`; // 示例：user1766043770158
      Taro.setStorageSync("userId", userId);
      console.log("新生成 userId:", userId);
    }
    return userId;
  };

  const payh5 = (type, total_fee = 1000) => {
    const userId = getOrCreateUserId(); // ← 新增：获取 userId
    Taro.request({
      method: "POST",
      url: `${process.env.TARO_API_API}/payh5`,
      data: {
        total_fee: total_fee,
        type: type,
        // callback_url 临时不传
        user_id: userId, // ← 新增字段
      },
      header: {
        "content-type": "application/json",
      },
      success: (res) => {
        if (res.data?.status === "ok" && res.data?.xorpay_params) {
          // 1. 乐观更新：立即缓存 paidType，用户看到“加载中”或直接显示已支付
          // savePaidType(type);
          // saveUserName(userId);  // ← 乐观缓存当前 userId
          // Taro.showToast({
          //   title: "正在跳转支付，请稍后...",
          //   icon: "loading",
          //   duration: 2000,
          // });

          // 创建隐藏 form POST 到 XorPay
          const form = document.createElement("form");
          form.method = "POST";
          form.action = res.data.xorpay_url;
          form.style.display = "none";

          for (const key in res.data.xorpay_params) {
            const input = document.createElement("input");
            input.type = "hidden";
            input.name = key;
            input.value = res.data.xorpay_params[key];
            form.appendChild(input);
          }

          document.body.appendChild(form);
          form.submit();

          // 2. 可选：提交后清理 form，避免内存泄漏
          setTimeout(() => {
            document.body.removeChild(form);
          }, 1000);
        } else {
          Taro.showToast({
            title: "支付发起失败",
            icon: "none",
          });
        }
      },
      fail: () => {
        Taro.showToast({
          title: "网络错误",
          icon: "none",
        });
      },
    });
  };
  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),
            __html: marked(paidType=='book'|| vipbook ? 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",
              display: "flex", // 关键：flex 布局
              justifyContent: "center", // 水平居中
              alignItems: "center", // 垂直居中（可选，如果你想整块垂直也居中）
              flexDirection: "column", // 可选：让内容垂直排列（如果下面还有文字）
              margin: "20px 0", // 可选：上下留点间距
            }}
          >
            <Image
              className="hackrobot"
              src={hackrobot}
              style={{
                width: "300px",
                height: "300px",
                maxWidth: "none",
                maxHeight: "none",
              }}
              // src={`https://minioweb.hackrobot.cn/hackrobot/propless.svg`}
              lazyLoad
            ></Image>
          </div>
        )}

        {/* 判断有没有wxid */}
        {/* {book != 1 ? ( */}
        {paidType != "book" ? (
          <AtButton
            type="primary"
            size="normal"
            className="joinSalon"
            onClick={() => {
              if (paidType == "book" || vipbook) {
                return false;
              } else {
                if (!!isWeChat) {
                  //88元
                  payh5("book", 8800);
                  // window.location.href = `https://vip.hackrobot.cn`;
                } else {
                  window.location.href = `https://mp.weixin.qq.com/s/PBbnS8qC_kqhL9HJO5m-Iw`;
                }
              }
            }}
          >
            {`🔒阅读更多`}
          </AtButton>
        ) : // <span style={{ color: "green" }}>持续更新中....</span>
        null}
      </View>
    </>
  );
};

export default Book;
