"use client";

import React, { useState, useEffect, useCallback } from "react";
import { generateSignature } from "@/utils/crypto";
import webviewBaseRequest from "@/utils/webviewBaseRequest";
import Link from "next/link";
import { Toast } from "antd-mobile";
import { useRouter, useSearchParams } from "next/navigation";
export default function Vip() {
  const router = useRouter();
  const searchParams = useSearchParams();

  //检查用户是否是vip
  const [isVip, setIsVip] = useState(false);
  const [name, setName] = useState("");
  const [isFetching, setIsFetching] = useState(true);

  //备用支付渠道是否展示
  const [isBackupPaymentVisible, setIsBackupPaymentVisible] = useState(false);

  //备用支付渠道是否展示
  const handleBackupPaymentVisible = () => {
    setIsBackupPaymentVisible(true);
  };

  const getBase = useCallback(
    (webviewBase) => {
      let searchParamsObj = null;
      let currentBaseCode = searchParams.get("base");
      if (currentBaseCode) {
        let currentBase = JSON.parse(currentBaseCode);
        searchParamsObj = { ...currentBase };
      }
      return searchParamsObj || webviewBase;
    },
    [searchParams]
  );
  const getUserData = async () => {
    const webviewBase = webviewBaseRequest();
    let base = getBase(webviewBase);
    try {
      const signature = generateSignature({
        ...base,
        mid: base.b_mid,
      });
      const detailResponse = await fetch(
        `/api/account/list_by_mid?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
            mid: base.b_mid,
          }),
        }
      );
      const detailData = await detailResponse.json();
      if (detailData.ret === -1) {
        Toast.show({
          content: detailData.msg,
        });
        return;
      }
      setName(detailData.data.account.name);
      if (detailData.data.account.is_a_member === 1) setIsVip(true);
      setIsFetching(false);
    } catch (error) {
      console.error(error);
    }
  };
  //轮询请求
  useEffect(() => {
    setTimeout(() => {
      getUserData();
    }, 500);
    const intervalId = setInterval(() => {
      getUserData();
    }, 2000);
    return () => clearInterval(intervalId);
  }, []);

  //创建充值订单
  const [isLoading, setIsLoading] = useState(false);
  const createOrder = async (type = "alipay_h5") => {
    const webviewBase = webviewBaseRequest();
    let base = getBase(webviewBase);
    const body = {
      ...base,
      product_id: "membership",
      pay_type: type,
      redirect_url: type === "yeepay_wxpay_h5" ? window.location.href : "",
      from: searchParams.get("base") ? "web" : "app",
    };

    //如果是微信jsapi支付直接跳转到中间页
    if (type === "wxpay_jsapi") {
      router.push(`/pay/${encodeURIComponent(JSON.stringify(body))}`);
      return;
    }

    setIsLoading(true);

    const signature = generateSignature(body);
    try {
      const response = await fetch(
        `/api/vas/create_order?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          content: data.msg,
        });
        return;
      }
      switch (type) {
        case "yeepay_alipay_h5":
          router.push(`${data.data.yeepay_alipay_h5_param_str}`);
          break;
        case "yeepay_wxpay_h5":
          router.push(`${data.data.yeepay_wxpay_h5_param_str}`);
          break;
        case "alipay_h5":
          router.push(`${data.data.alipay_h5_param_str}`);
          break;
        case "wxpay_h5":
          router.push(
            `https://yibowanhe.top?url=${encodeURIComponent(
              data.data.wxpay_h5_param_str
            )}`
          );
          break;
        default:
          router.push(`${data.data.alipay_h5_param_str}`);
          break;
      }
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  //创建备用充值订单
  const createBackupPaymentOrder = async (type = "alipay_h5") => {
    const webviewBase = webviewBaseRequest();
    let base = getBase(webviewBase);
    const body = {
      ...base,
      product_id: "membership",
      pay_type: type,
      redirect_url: type === "yeepay_wxpay_h5" ? window.location.href : "",
      from: searchParams.get("base") ? "web" : "app",
      ver: "aliv2",
    };

    //如果是微信jsapi支付直接跳转到中间页
    if (type === "wxpay_jsapi") {
      router.push(`/pay/${encodeURIComponent(JSON.stringify(body))}`);
      return;
    }

    setIsLoading(true);

    const signature = generateSignature(body);
    try {
      const response = await fetch(
        `/api/vas/create_order?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          content: data.msg,
        });
        return;
      }
      switch (type) {
        case "yeepay_alipay_h5":
          router.push(`${data.data.yeepay_alipay_h5_param_str}`);
          break;
        case "yeepay_wxpay_h5":
          router.push(`${data.data.yeepay_wxpay_h5_param_str}`);
          break;
        case "alipay_h5":
          router.push(`${data.data.alipay_h5_param_str}`);
          break;
        case "wxpay_h5":
          router.push(
            `https://yibowanhe.top?url=${encodeURIComponent(
              data.data.wxpay_h5_param_str
            )}`
          );
          break;
        default:
          router.push(`${data.data.alipay_h5_param_str}`);
          break;
      }
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  if (isFetching) {
    return (
      <section className="flex flex-1 justify-center container">
        <span className="absolute top-1/2 loading loading-spinner loading-lg"></span>
      </section>
    );
  }

  return (
    <section className="flex flex-1 justify-center container">
      {isLoading && (
        <span className="absolute top-1/2 loading loading-spinner loading-lg z-20"></span>
      )}
      <img
        className="absolute top-0 left-0 z-0 w-full"
        src={
          process.env.NEXT_PUBLIC_CDN_URL + "/public/images/vipbackground.png"
        }
        alt=""
      />
      <div className="flex flex-col z-10">
        <img
          className="pt-24"
          src={process.env.NEXT_PUBLIC_CDN_URL + "/public/images/viptitle.png"}
          alt=""
        />
        <div className="flex flex-col px-4 pb-48">
          {isVip ? (
            <div className="relative">
              <img
                src={
                  process.env.NEXT_PUBLIC_CDN_URL + "/public/images/isvip.png"
                }
                alt=""
              />
              <p className="absolute bottom-5 left-5 text-[#521824B2] text-sm font-medium">
                {name}
              </p>
            </div>
          ) : (
            <img
              src={
                process.env.NEXT_PUBLIC_CDN_URL + "/public/images/notvip.png"
              }
              alt=""
            />
          )}
          <div
            className="flex flex-col p-4 rounded-2xl mt-4"
            style={{
              background:
                "linear-gradient(94.52deg, #241018 3.66%, #0F080B 100%), linear-gradient(90deg, rgba(66, 50, 56, 0.5) 0%, rgba(61, 42, 48, 0.5) 100%)",
              border: "2px solid",
              borderColor: "#42323880",
            }}
          >
            <p className="text-[#F5C4CC] text-2xl font-bold">会员权益</p>
            <div className="flex flex-row flex-wrap gap-y-3.5 mt-4">
              <div className="flex flex-row items-center basis-1/2">
                <img
                  className="w-11"
                  src={
                    process.env.NEXT_PUBLIC_CDN_URL +
                    "/public/images/vipright1.png"
                  }
                  alt=""
                />
                <div className="flex flex-col ml-1.5">
                  <p className="text-[#F5C4CC] text-sm">高清图片</p>
                  <p className="text-[#613F46] text-xs">下载保存</p>
                </div>
              </div>
              <div className="flex flex-row items-center basis-1/2">
                <img
                  className="w-11"
                  src={
                    process.env.NEXT_PUBLIC_CDN_URL +
                    "/public/images/vipright4.png"
                  }
                  alt=""
                />
                <div className="flex flex-col ml-1.5">
                  <p className="text-[#F5C4CC] text-sm">搜索筛选</p>
                  <p className="text-[#613F46] text-xs">发现心仪</p>
                </div>
              </div>
              <div className="flex flex-row items-center basis-1/2">
                <img
                  className="w-11"
                  src={
                    process.env.NEXT_PUBLIC_CDN_URL +
                    "/public/images/vipright2.png"
                  }
                  alt=""
                />
                <div className="flex flex-col ml-1.5">
                  <p className="text-[#F5C4CC] text-sm">身份标签</p>
                  <p className="text-[#613F46] text-xs">专属标识</p>
                </div>
              </div>
              <div className="flex flex-row items-center basis-1/2">
                <img
                  className="w-11"
                  src={
                    process.env.NEXT_PUBLIC_CDN_URL +
                    "/public/images/vipright3.png"
                  }
                  alt=""
                />
                <div className="flex flex-col ml-1.5">
                  <p className="text-[#F5C4CC] text-sm">专属客服</p>
                  <p className="text-[#613F46] text-xs">极速服务</p>
                </div>
              </div>
            </div>
          </div>
          <div
            className="flex flex-col p-4 rounded-2xl mt-4"
            style={{
              border: "2px solid",
              borderColor: "#42323880",
            }}
          >
            <p className="text-base font-medium text-[#F5C4CC]">会员规则</p>
            <p className="text-xs font-medium text-[#F5C4CC] mt-2">
              1、会员权限永久有效,开通后请勿传播平台付费内容;
            </p>
            <p className="text-xs font-medium text-[#F5C4CC]">
              2、更多特权内容敬请期待,详情请关注本页面会员权益信息变化。
            </p>
            <p className="text-base font-medium text-[#F5C4CC] mt-6">
              注意事项
            </p>
            <p className="text-xs font-medium text-[#F5C4CC] mt-2">
              1、会员特权属于虚拟商品,一经售出概不退换;
            </p>
            <p className="text-xs font-medium text-[#F5C4CC]">
              2、请确保支付时您的网络环境保持畅通,避免因第三方网络环境导致的支付失败;
            </p>
            <p className="text-xs font-medium text-[#F5C4CC]">
              3、本项特权内容最终解释权归铁粉空间运营方所有。
            </p>
          </div>
        </div>
        {!isVip && (
          <div className="flex flex-col w-full fixed left-0 bottom-0 z-20">
            <div className="h-12 bg-gradient-to-t from-[#07050AE5] to-[#07050A00]"></div>
            <div className="flex flex-col pt-3 pb-11 px-4 bg-[#07050AE5]">
              <div className="flex flex-row justify-between">
                <div className="basis-1/2 pr-2">
                  <div
                    onClick={() => createOrder("alipay_h5")}
                    className="flex flex-row cursor-pointer gap-1.5 h-11 items-center justify-center bg-primary rounded-full"
                  >
                    <img
                      className="w-[22px]"
                      src={
                        process.env.NEXT_PUBLIC_CDN_URL +
                        "/public/images/alipay.png"
                      }
                      alt=""
                    />
                    <p className="text-white text-base font-medium whitespace-nowrap">
                      支付宝支付
                    </p>
                  </div>
                </div>
                <div className="basis-1/2 pl-2">
                  <div
                    onClick={() => createOrder("wxpay_h5")}
                    className="flex flex-row cursor-pointer gap-1.5 h-11 items-center justify-center bg-primary rounded-full"
                  >
                    <svg viewBox="0 0 1228 1024" width="18" height="18">
                      <path
                        d="M530.8928 703.1296a41.472 41.472 0 0 1-35.7376-19.8144l-2.7136-5.5808L278.272 394.752a18.7392 18.7392 0 0 1-2.048-8.1408 19.968 19.968 0 0 1 20.48-19.3536c4.608 0 8.8576 1.4336 12.288 3.84l234.3936 139.9296a64.4096 64.4096 0 0 0 54.528 5.9392L1116.2624 204.8C1004.9536 80.896 821.76 0 614.4 0 275.0464 0 0 216.576 0 483.6352c0 145.7152 82.7392 276.8896 212.2752 365.5168a38.1952 38.1952 0 0 1 17.2032 31.488 44.4928 44.4928 0 0 1-2.1504 12.3904l-27.6992 97.4848c-1.3312 4.608-3.328 9.3696-3.328 14.1312 0 10.752 9.216 19.3536 20.48 19.3536 4.4032 0 8.0384-1.536 11.776-3.584l134.5536-73.3184c10.1376-5.5296 20.7872-8.96 32.6144-8.96 6.2976 0 12.288 0.9216 18.0736 2.5088 62.72 17.0496 130.4576 26.5728 200.5504 26.5728C953.7024 967.168 1228.8 750.592 1228.8 483.6352c0-80.9472-25.4464-157.1328-70.0416-224.1024l-604.9792 436.992-4.4544 2.4064a42.1376 42.1376 0 0 1-18.432 4.1984z"
                        fill="#FFFFFF"
                      ></path>
                    </svg>
                    <p className="text-white text-base font-medium whitespace-nowrap">
                      微信支付
                    </p>
                  </div>
                </div>
              </div>
              {isBackupPaymentVisible ? (
                <div className="px-2 mt-4">
                  <div
                    onClick={() => createBackupPaymentOrder("alipay_h5")}
                    className="flex flex-row cursor-pointer gap-1.5 h-11 items-center justify-center bg-primary rounded-full"
                  >
                    <img
                      className="w-[22px]"
                      src={
                        process.env.NEXT_PUBLIC_CDN_URL +
                        "/public/images/alipay.png"
                      }
                      alt=""
                    />
                    <p className="text-white text-base font-medium whitespace-nowrap">
                      【备用】支付宝支付
                    </p>
                  </div>
                </div>
              ) : (
                <p className="text-secondary text-xs font-medium mt-4 text-center mb-1">
                  若无法支付,请尝试
                  <span
                    className="link text-[#309EDC]"
                    onClick={handleBackupPaymentVisible}
                  >
                    备用支付渠道
                  </span>
                </p>
              )}
              <p className="text-secondary text-xs font-medium mt-2 text-center mb-1">
                确认购买即视为同意
                <Link
                  className="link text-[#309EDC]"
                  href="/doc/rechargeagreement"
                >
                  《用户充值协议》
                </Link>
              </p>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}