"use client";
import React, { useState, useEffect } from "react";
import { getCookie } from "cookies-next";
import { useRouter } from "next/navigation";
import baseRequest from "@/utils/baseRequest";
import { Toast, Modal } from "antd-mobile";
import { generateSignature } from "@/utils/crypto";
import { JSEncrypt } from "jsencrypt";

export default function Checkout() {
  const router = useRouter();

  //查看主播实名认证情况、可提现钻石数量
  const [data, setData] = useState({});
  const getData = async () => {
    const mid = getCookie("mid");
    if (!mid) return;
    try {
      const base = baseRequest();
      //查实名认证情况
      const body = {
        ...base,
      };
      const signature = generateSignature(body);
      const verificationResponse = await fetch(
        `/api/hvyogo/query_agree_state?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const verificationData = await verificationResponse.json();
      if (verificationData.ret === -1) {
        Toast.show({
          content: verificationData.msg,
        });
      }
      //查认证信息详情
      const body2 = {
        ...base,
      };
      const signature2 = generateSignature(body2);
      const detailResponse = await fetch(
        `/api/hvyogo/worker_find_detail?signature=${signature2}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const detailData = await detailResponse.json();
      if (detailData.ret === -1) {
        Toast.show({
          content: detailData.msg,
        });
      }
      //查可提现钻石数量
      const body3 = {
        ...base,
      };
      const signature3 = generateSignature(body3);
      const withdrawalResponse = await fetch(
        `/api/vas/withdraw_page?signature=${signature3}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body3),
        }
      );
      const withdrawalData = await withdrawalResponse.json();
      if (withdrawalData.ret === -1) {
        Toast.show({
          content: withdrawalData.msg,
        });
        return;
      }
      setData({
        verificationStatus: verificationData.data?.agree_state,
        detail: detailData.data,
        withdrawal_diamond: withdrawalData.data.withdraw_diamonds,
      });
    } catch (error) {
      console.error(error);
    }
  };
  useEffect(() => {
    getData();
  }, []);

  const [withdrawalNum, setWithdrawalNum] = useState("");
  const [receiptChannel, setReceiptChannel] = useState(10);
  const [alipayAccount, setAlipayAccount] = useState("");
  const [newBankCardNo, setNewBankCardNo] = useState("");

  //这是提现钻石的数量
  const handleChangeWithdrawalNum = (e) => {
    let newValue = parseInt(e.target.value, 10);
    // 确保输入的值在最小值和最大值范围内
    if (
      newValue >= 0 &&
      newValue <= Math.min(data?.withdrawal_diamond, 200000)
    ) {
      setWithdrawalNum(newValue);
    } else if (isNaN(newValue)) {
      setWithdrawalNum(0);
    } else if (newValue > Math.min(data?.withdrawal_diamond, 200000)) {
      setWithdrawalNum(Math.min(data?.withdrawal_diamond, 200000));
    }
  };

  //点击提交申请按钮
  const handleSubmit = async () => {
    // if (!withdrawalNum || withdrawalNum < 1000) {
    //   Toast.show({
    //     content: "提现最低金额为100元（即1000钻石）",
    //   });
    //   return;
    // }
    if (receiptChannel === 20 && !alipayAccount) {
      Toast.show({
        content: "请填写支付宝账号",
      });
      return;
    }
    document.getElementById("comfirm_modal").showModal();
  };

  //点击二次确认按钮
  const [errorMessage, setErrorMessage] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const handleConfirm = async () => {
    try {
      setIsSubmitting(true);
      //对支付宝账号进行RSA加密
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(process.env.NEXT_PUBLIC_RSA_KEY);
      const encryptedAlipayAccount = encrypt.encrypt(alipayAccount);
      const base = baseRequest();
      const body =
        receiptChannel === 20
          ? {
              receipt_channel: receiptChannel,
              worker_account: encryptedAlipayAccount,
              distribute_amount: (withdrawalNum * 10).toString(),
              ...base,
            }
          : {
              distribute_amount: (withdrawalNum * 10).toString(),
              ...base,
            };
      const signature = generateSignature(body);
      const applyResponse = await fetch(
        `/api/hvyogo/single_distribute?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const applyData = await applyResponse.json();
      if (applyData.ret === -1) {
        setErrorMessage(applyData.msg);
        setIsSubmitting(false);
        return;
      }
      router.push("/withdrawal/success");
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  //修改银行卡账号
  const handleEditBankCardNo = async () => {
    try {
      setIsSubmitting(true);
      //对手机号和银行卡号进行rsa加密
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(process.env.NEXT_PUBLIC_RSA_KEY);
      const encryptedWorkerMobile = encrypt.encrypt(
        data?.detail?.worker_mobile
      );
      const encryptedBankCard = encrypt.encrypt(newBankCardNo);
      const base = baseRequest();
      const body = {
        worker_mobile: encryptedWorkerMobile,
        bank_card: encryptedBankCard,
        receipt_channel: 10,
        ...base,
      };
      const signature = generateSignature(body);
      const _response = await fetch(
        `/api/hvyogo/worker_update?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        setIsSubmitting(false);
        return;
      }
      await getData();
      document.getElementById("edit_bank_card_no_modal").close();
      Toast.show({
        content: _data.data.status_text,
      });
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <section className="container flex flex-col flex-1 p-4">
      <div className="flex flex-col items-center justify-around w-full h-32 rounded-2xl bg-gradient-to-r from-[#FF668B] to-[#FF66F0]">
        <p className="text-base text-white font-medium">可提现钻石：</p>
        <div className="flex flex-col items-center">
          <p className="text-2xl text-white font-medium">
            {data?.withdrawal_diamond}
          </p>
          <p className="text-xs text-white font-medium">
            （新入帐钻石需等待7日才能提现哦）
          </p>
        </div>
        <p className="text-base text-white font-medium">
          兑换比例：10钻石=1RMB
        </p>
      </div>
      <p className="text-white text-base mt-2">
        <span className="text-error">*</span>提现数量
      </p>
      {data?.verificationStatus !== 2 ? (
        <div className="btn btn-info text-white w-full">您还未通过实名认证</div>
      ) : (
        <input
          type="number"
          placeholder={`可提现${data?.withdrawal_diamond}钻石`}
          value={withdrawalNum.toString()}
          onChange={handleChangeWithdrawalNum}
          className="input input-bordered input-md input-primary w-full mt-2"
        />
      )}
      <p className="text-secondary text-base">
        预估实到金额：
        {withdrawalNum
          ? ((withdrawalNum / 10) * 0.97).toFixed(2) + "元"
          : "自动计算"}
      </p>
      <p className="text-white text-base mt-2">
        <span className="text-error">*</span>提现方式
      </p>
      <div className="flex flex-col gap-2 mt-2">
        <div
          onClick={() => setReceiptChannel(10)}
          className={`${
            receiptChannel === 10 ? "border-primary" : "border-[#FFFFFF1A]"
          } border flex flex-row items-center justify-between cursor-pointer bg-[#FFFFFF1A] rounded-lg px-4 py-2`}
        >
          <div className="flex flex-row items-center">
            <svg viewBox="0 0 1024 1024" width="24" height="24">
              <path
                d="M426.688 650.688a32 32 0 0 0 0 64h64a32 32 0 1 0 0-64h-64zM586.624 682.688a32 32 0 0 1 32-32H768a32 32 0 1 1 0 64H618.624a32 32 0 0 1-32-32z"
                fill="#ffffff"
              ></path>
              <path
                d="M578.048 138.688H445.952c-78.464 0-140.096 0-188.672 5.44-49.536 5.632-89.792 17.28-123.2 43.712-9.984 7.872-19.264 16.64-27.712 26.048-28.416 31.936-41.152 70.528-47.168 117.952-5.888 46.08-5.888 104.32-5.888 177.92v4.48c0 73.6 0 131.84 5.888 177.92 6.016 47.36 18.752 86.016 47.168 117.888 8.448 9.472 17.728 18.24 27.712 26.112 33.408 26.368 73.6 38.08 123.2 43.712 48.64 5.44 110.208 5.44 188.672 5.44h132.096c78.464 0 140.032 0 188.608-5.44 49.6-5.632 89.856-17.28 123.264-43.712 9.984-7.872 19.264-16.64 27.712-26.112 28.416-31.872 41.088-70.464 47.168-117.888 5.888-46.08 5.888-104.32 5.888-177.92v-4.48c0-73.6 0-131.84-5.888-177.92-6.08-47.36-18.752-86.016-47.168-117.952a218.56 218.56 0 0 0-27.712-26.048c-33.408-26.432-73.6-38.08-123.2-43.712-48.64-5.44-110.208-5.44-188.672-5.44zM173.76 238.08c20.096-15.936 46.72-25.344 90.752-30.336 44.544-5.056 102.528-5.12 183.488-5.12h128c80.896 0 138.88 0.064 183.488 5.12 44.032 4.992 70.656 14.4 90.752 30.336 7.104 5.568 13.696 11.776 19.584 18.432 16.512 18.56 26.24 42.752 31.488 83.456 0.512 3.84 0.96 7.872 1.344 12.032H121.344c0.384-4.16 0.832-8.128 1.344-12.032 5.184-40.704 14.976-64.96 31.424-83.456 5.952-6.656 12.544-12.8 19.648-18.432zM117.952 416h788.096c0.64 27.52 0.64 59.2 0.64 96 0 76.288-0.064 130.56-5.376 172.032-5.184 40.64-14.976 64.96-31.488 83.456-5.888 6.656-12.48 12.8-19.584 18.432-20.096 15.872-46.72 25.344-90.752 30.336-44.544 5.056-102.592 5.12-183.488 5.12H448c-80.96 0-138.944-0.128-183.488-5.12-44.032-4.992-70.656-14.464-90.752-30.336a154.56 154.56 0 0 1-19.648-18.432c-16.448-18.56-26.24-42.816-31.424-83.456-5.312-41.536-5.376-95.744-5.376-172.032 0-36.8 0-68.48 0.64-96z"
                fill="#ffffff"
              ></path>
            </svg>
            <p className="text-white text-base font-medium ml-2">银行卡</p>
            <p className="text-secondary text-base font-medium">
              （
              {data?.detail?.bank_card_no?.replace(
                /(\d{4})\d+(\d{4})/,
                "$1****$2"
              )}
              ）
            </p>
          </div>
          <p
            onClick={() =>
              document.getElementById("edit_bank_card_no_modal").showModal()
            }
            className="text-primary text-base font-medium cursor-pointer"
          >
            修改
          </p>
        </div>
        <div
          onClick={() => setReceiptChannel(20)}
          className={`${
            receiptChannel === 20 ? "border-primary" : "border-[#FFFFFF1A]"
          } border flex flex-row items-center cursor-pointer bg-[#FFFFFF1A] rounded-lg px-4 py-2`}
        >
          <svg viewBox="0 0 1024 1024" width="24" height="24">
            <path
              d="M906.666667 347.733333c-4.266667-10.666667-17.066667-17.066667-27.733334-10.666666-10.666667 4.266667-17.066667 17.066667-10.666666 27.733333 19.2 46.933333 29.866667 96 29.866666 147.2 0 51.2-10.666667 98.133333-27.733333 142.933333-40.533333-12.8-189.866667-57.6-226.133333-70.4 25.6-42.666667 46.933333-91.733333 59.733333-147.2h-145.066667v-49.066666h179.2v-29.866667h-179.2V277.333333H490.666667c-12.8 0-12.8 10.666667-12.8 10.666667v70.4h-168.533334v29.866667h168.533334v49.066666h-138.666667v27.733334h277.333333c-10.666667 34.133333-23.466667 66.133333-40.533333 96-61.866667-21.333333-98.133333-34.133333-174.933333-42.666667-145.066667-12.8-179.2 66.133333-185.6 113.066667-8.533333 74.666667 57.6 134.4 157.866666 134.4 98.133333 0 164.266667-44.8 228.266667-119.466667 64 29.866667 170.666667 81.066667 215.466667 102.4C742.4 838.4 633.6 896 512 896c-211.2 0-384-172.8-384-384S300.8 128 512 128c51.2 0 100.266667 10.666667 147.2 29.866667 10.666667 4.266667 23.466667 0 27.733333-10.666667 4.266667-10.666667 0-23.466667-10.666666-27.733333-51.2-21.333333-106.666667-32-164.266667-32C277.333333 85.333333 85.333333 277.333333 85.333333 512s192 426.666667 426.666667 426.666667 426.666667-192 426.666667-426.666667c0-57.6-10.666667-110.933333-32-164.266667zM360.533333 721.066667c-104.533333 0-121.6-66.133333-115.2-91.733334 6.4-27.733333 36.266667-61.866667 93.866667-61.866666 66.133333 0 125.866667 17.066667 198.4 51.2-51.2 64-113.066667 102.4-177.066667 102.4z"
              fill="#ffffff"
            ></path>
          </svg>
          <p className="text-white text-base font-medium ml-2">支付宝</p>
        </div>
        {receiptChannel === 20 &&
          (data?.verificationStatus !== 2 ? (
            <div className="btn btn-info text-white w-full">
              您还未通过实名认证
            </div>
          ) : (
            <input
              type="text"
              placeholder="请输入本人支付宝账号"
              value={alipayAccount}
              onChange={(e) => setAlipayAccount(e.target.value)}
              className="input input-bordered input-md input-primary w-full"
            />
          ))}
      </div>
      <p className="text-secondary text-base mt-16">注意事项：</p>
      <p className="text-secondary text-sm">
        1.需实名认证并绑定收款方式后方可提现；
      </p>
      <p className="text-secondary text-sm">
        2.平台将收取提现金额的3%作为提现手续费用，该笔费用将用于为收款人缴纳相关税费；
      </p>
      <p className="text-secondary text-sm">
        3.收款账户需与实名认证本人保持一致；
      </p>
      <p className="text-secondary text-sm">
        4.单笔最低提现金额为100元（即1,000钻石），单月最高提现金额为95,000元（即950,000钻石）；
      </p>
      <p className="text-secondary text-sm">
        5.自助提现渠道每日只能提现一次，若有更多提现需求，请联系客服。
      </p>
      <button
        onClick={handleSubmit}
        className="btn btn-md btn-primary text-white rounded-full w-full mb-4 mt-4"
      >
        提交申请
      </button>
      {/* 修改银行卡 */}
      <dialog id="edit_bank_card_no_modal" className="modal">
        <div className="modal-box bg-[#17161A]">
          <p className="text-white text-base font-medium ml-2">
            原银行卡：
            {data?.detail?.bank_card_no?.replace(
              /(\d{4})\d+(\d{4})/,
              "$1****$2"
            )}
          </p>
          <div className="flex flex-row items-center mt-2">
            <p className="text-white text-base font-medium ml-2">新银行卡：</p>
            <input
              type="text"
              placeholder="请输入本人银行卡账号"
              value={newBankCardNo}
              onChange={(e) => setNewBankCardNo(e.target.value)}
              className="input input-bordered input-sm input-primary"
            />
          </div>
          <div className="flex flex-col mt-4">
            <button
              disabled={isSubmitting}
              onClick={handleEditBankCardNo}
              className="flex items-center justify-center bg-[#FF669E] rounded-lg py-2"
            >
              {isSubmitting && (
                <span className="loading loading-spinner"></span>
              )}
              {isSubmitting ? "提交中..." : "确认提交"}
            </button>
            <form method="dialog" className="flex mt-2">
              <button className="flex flex-row flex-1 items-center justify-center border border-secondary rounded-lg py-2">
                <p className="text-secondary text-base ml-1">返回</p>
              </button>
            </form>
          </div>
        </div>
      </dialog>
      {/* 确认提现 */}
      <dialog id="comfirm_modal" className="modal">
        <div className="modal-box bg-[#17161A]">
          <p className="text-white text-base font-medium">
            提现钻石：
            <span className="text-secondary">{withdrawalNum}</span>
          </p>
          <p className="text-white text-base font-medium">
            预估实到金额：
            <span className="text-secondary">
              ¥{((withdrawalNum / 10) * 0.97).toFixed(2)}
            </span>
          </p>
          <p className="text-white text-base font-medium">
            收款人姓名：
            <span className="text-secondary">{data?.detail?.worker_name}</span>
          </p>
          <p className="text-white text-base font-medium">
            收款渠道：
            <span className="text-secondary">
              {receiptChannel === 10 ? "银行卡" : "支付宝"}
            </span>
          </p>
          <p className="text-white text-base font-medium">
            收款账号：
            <span className="text-secondary">
              {receiptChannel === 10
                ? data?.detail?.bank_card_no
                : alipayAccount}
            </span>
          </p>
          {errorMessage && (
            <p className="text-error text-base font-medium mt-2">
              提现失败：{errorMessage}
            </p>
          )}
          <div className="flex flex-col mt-4">
            <button
              disabled={isSubmitting}
              onClick={handleConfirm}
              className="flex items-center justify-center bg-[#FF669E] rounded-lg py-2"
            >
              {isSubmitting && (
                <span className="loading loading-spinner"></span>
              )}
              {isSubmitting ? "提交中..." : "确认提交"}
            </button>
            <form method="dialog" className="flex mt-2">
              <button className="flex flex-row flex-1 items-center justify-center border border-secondary rounded-lg py-2">
                <p className="text-secondary text-base ml-1">返回修改</p>
              </button>
            </form>
          </div>
        </div>
      </dialog>
    </section>
  );
}
