"use client";

import React, { useState, useEffect } from "react";
import Image from "next/image";
import webviewBaseRequest from "@/utils/webviewBaseRequest";

export default function Weixin({ params }) {
  //生成二维码
  const [qrcodeUrl, setQrcodeUrl] = useState("");
  const [device, setDevice] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
    var QRCode = require("qrcode");
    QRCode.toDataURL(
      `https://tiefen.fun/pay/jsapi/${params.weixin}`,
      function (err, url) {
        setQrcodeUrl(url);
      }
    );
    //确认设备类型
    const base = webviewBaseRequest();
    if (base?.b_dt === 1) setDevice(1);
    setIsLoading(false);
  }, []);

  //保存二维码
  const saveQrcode = async () => {
    window.ReactNativeWebView.postMessage(
      JSON.stringify({
        type: "SAVE_IMAGE",
        data: qrcodeUrl,
      })
    );
  };

  //android打开微信,ios打开微信扫一扫,0:android,1:ios
  const openWechat = () => {
    if (device === 0) {
      window.open("weixin://", "_blank");
      return;
    }
    window.open("weixin://scanqrcode", "_blank");
  };

  if (isLoading) {
    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 flex-col container py-4">
      <div className="mt-24 flex flex-col gap-2">
        <h1 className="text-white text-2xl font-semibold text-center">
          请保存二维码到相册后
          <br />
          打开微信扫码支付
        </h1>
        <p className="text-white text-base text-center">
          支付成功后返回APP关闭页面即可
        </p>
      </div>
      <div className="flex flex-col gap-4 px-4 mt-4">
        <button
          onClick={saveQrcode}
          className="btn btn-primary rounded-full text-white text-base"
        >
          {device === 0 ? "① 点此保存二维码" : "点此保存二维码"}
        </button>
        {device === 0 && (
          <button
            onClick={openWechat}
            className="btn btn-primary rounded-full text-white text-base"
          >
            {device === 0 ? "② 点此打开微信" : "② 点此打开微信扫一扫"}
          </button>
        )}
      </div>
      <div className="mt-4 flex justify-center">
        {qrcodeUrl && (
          <Image
            className="aspect-square object-contain rounded-xl"
            src={qrcodeUrl}
            width={120}
            height={120}
            alt=""
          ></Image>
        )}
      </div>
    </section>
  );
}