"use client";
import React, { useState, useEffect } from "react";
import AuthBar from "@/components/AuthBar";
import { Toast, Modal } from "antd-mobile";
import { checkAuth } from "@/utils/auth";
import { useRouter } from "next/navigation";
import baseRequest from "@/utils/baseRequest";
import { generateSignature } from "@/utils/crypto";
import copy from "@/utils/copy";

export default function Purchased() {
  //如果没登录直接跳转下载页
  const router = useRouter();
  useEffect(() => {
    const prepare = async () => {
      if (window.location.origin === "https://shop.tiefen.fun") {
        router.replace("https://tiefen.fun/purchased");
        return;
      }
      const isLogined = await checkAuth();
      if (!isLogined) {
        router.replace("/auth/login/phonenumlogin");
      }
    };
    prepare();
  }, []);

  //获取订单数据
  const [data, setData] = useState([]);
  useEffect(() => {
    const getData = async () => {
      try {
        const base = baseRequest();
        const signature = generateSignature({
          offset: 0,
          limit: 99,
          ...base,
        });
        const detailResponse = await fetch(
          `/api/vas/h5_get_unlock_wechat_list?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              offset: 0,
              limit: 99,
              ...base,
            }),
          }
        );
        const detailData = await detailResponse.json();
        if (detailData.ret === -1) {
          Toast.show({
            content: detailData.msg,
          });
          return;
        }
        setData(detailData.data.list);
      } catch (error) {
        console.error(error);
      }
    };
    getData();
  }, []);

  const [currentWechat, setCurrentWechat] = useState("");
  const getWechat = async (streamerMid) => {
    // 获取微信
    try {
      const base = baseRequest();
      const signature = generateSignature({
        uid: streamerMid,
        ...base,
      });
      const detailResponse = await fetch(
        `/api/vas/query_wechat?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            uid: streamerMid,
            ...base,
          }),
        }
      );
      const detailData = await detailResponse.json();
      if (detailData.ret === -1) {
        Toast.show({
          content: detailData.msg,
        });
        return;
      }
      setCurrentWechat(detailData.data.wechat_contact);
    } catch (error) {
      console.error(error);
    }
  };

  const DirectGetWechatItem = ({ item }) => {
    //点击查看微信
    const handleClick = async () => {
      await getWechat(item?.account.mid);
      setTimeout(
        () =>
          Modal.alert({
            showCloseButton: true,
            confirmText: "复制",
            onConfirm: () => {
              copy(currentWechat);
              Toast.show({
                content: "复制成功",
              });
            },
            content: (
              <div className="bg-[#17161A] p-2">
                <p className="text-white text-base font-medium text-center mb-4">
                  Ta的微信号：<span>{currentWechat}</span>
                </p>
              </div>
            ),
          }),
        100
      );
    };

    //点击主播
    const handleNavigation = () => {
      router.push(`../${item?.account.user_id}`);
    };

    let orderLabel;
    switch (item.order_status) {
      case 3:
        orderLabel =
          item.lock_type === 1
            ? `等待${item.account.name}添加您的微信`
            : "请查看并添加微信";
        break;
      case 4:
        orderLabel = `${item.account.name}已确认完成添加`;
        break;
      case 5:
        orderLabel = `订单已完成`;
        break;
      case 6:
        orderLabel = `已退款`;
        break;
      default:
        orderLabel = "";
    }
    return (
      <div className="flex flex-row justify-between items-center py-2 border-b-2 border-neutral">
        <div onClick={handleNavigation} className="flex flex-row items-center">
          <img
            className="w-12 h-12 rounded-full"
            src={item.account?.avatar?.images[0].urls[0]}
            alt=""
          />
          <div className="flex flex-col ml-2">
            <p className="text-base text-white font-medium">
              {item.account?.name}
            </p>
            <p className="text-sm text-secondary font-medium">{orderLabel}</p>
          </div>
        </div>
        {item.lock_type === 0 && item.order_status !== 6 && (
          <button
            className="btn btn-sm btn-primary text-white rounded-full"
            onClick={handleClick}
          >
            查看微信
          </button>
        )}
      </div>
    );
  };

  const SubmitUserWechatItem = ({ item }) => {
    const [wechat, setWechat] = useState("");
    const [remarks, setRemarks] = useState("");
    const [status, setStatus] = useState("pending");
    const handleSubmit = async (e) => {
      e.preventDefault();
      if (!wechat) {
        Toast.show({
          content: "请填写微信号",
        });
        return;
      }
      //提交用户微信号
      try {
        const base = baseRequest();
        const signature = generateSignature({
          order_id: item.order_id,
          wechat: wechat,
          note: remarks,
          ...base,
        });
        const detailResponse = await fetch(
          `/api/vas/consumer_fill_contact?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              order_id: item.order_id,
              wechat: wechat,
              note: remarks,
              ...base,
            }),
          }
        );
        const detailData = await detailResponse.json();
        if (detailData.ret === -1) {
          Toast.show({
            content: detailData.msg,
          });
          return;
        }
        //提交成功后隐藏form并显示toast
        setStatus("inprogress");
        Toast.show({
          content: "提交成功，请留意好友请求",
        });
      } catch (error) {
        console.error(error);
      }
    };
    return (
      <div className="flex flex-col py-2 border-b-2 border-neutral">
        <div className="flex flex-row items-center">
          <img
            className="w-12 h-12 rounded-full"
            src={item.account?.avatar?.images[0].urls[0]}
            alt=""
          />
          <div className="flex flex-col ml-2">
            <p className="text-base text-white font-medium">
              {item.account?.name}
            </p>
            <p className="text-sm text-secondary font-medium">
              {status === "pending"
                ? "请填写您的微信等待Ta添加您"
                : "已提交您的微信，请留意好友请求"}
            </p>
          </div>
        </div>
        {status === "pending" && (
          <form onSubmit={handleSubmit}>
            <p className="text-white text-base mt-2">您的微信：</p>
            <input
              type="text"
              name="wechat"
              placeholder="请输入微信号"
              value={wechat}
              onChange={(e) => setWechat(e.target.value)}
              className="input input-bordered input-md input-primary w-full max-w-sm"
            />
            <p className="text-white text-base mt-2">备注：</p>
            <input
              type="text"
              name="remarks"
              placeholder="若需要填写验证信息，请备注答案"
              value={remarks}
              onChange={(e) => setRemarks(e.target.value)}
              className="input input-bordered input-md input-primary w-full max-w-sm"
            />
            <p className="text-error text-xs mt-2">
              若超72小时仍未收到Ta的好友申请，请前往APP联系客服退款
            </p>
            <button className="btn btn-sm btn-primary text-white rounded-full w-full max-w-sm mt-2">
              提交
            </button>
          </form>
        )}
      </div>
    );
  };

  return (
    <section className="flex flex-col container relative p-4">
      <AuthBar />
      <h1 className="text-2xl text-white font-medium mb-4">已购买</h1>
      {data.length === 0 && (
        <div className="flex flex-col mt-4 w-full items-center">
          <svg viewBox="0 0 1024 1024" width="120" height="120">
            <path
              d="M102.4 896a409.6 51.2 0 1 0 819.2 0 409.6 51.2 0 1 0-819.2 0Z"
              fill="#4A68CC"
              opacity=".1"
            ></path>
            <path
              d="M116.736 376.832c0 8.704 6.656 15.36 15.36 15.36s15.36-6.656 15.36-15.36-6.656-15.36-15.36-15.36c-8.192 0-15.36 7.168-15.36 15.36zM926.72 832c-19.456 5.12-23.552 9.216-28.16 28.16-5.12-19.456-9.216-23.552-28.16-28.16 18.944-5.12 23.552-9.216 28.16-28.16 4.608 18.944 8.704 23.552 28.16 28.16zM202.24 323.072c-25.088 6.656-30.208 11.776-36.864 36.864-6.656-25.088-11.776-30.208-36.864-36.864 25.088-6.656 30.208-12.288 36.864-36.864 6.144 25.088 11.776 30.208 36.864 36.864zM816.64 235.008c-15.36 4.096-18.432 7.168-22.528 22.528-4.096-15.36-7.168-18.432-22.528-22.528 15.36-4.096 18.432-7.168 22.528-22.528 3.584 15.36 7.168 18.432 22.528 22.528zM882.688 156.16c-39.936 10.24-48.128 18.944-58.88 58.88-10.24-39.936-18.944-48.128-58.88-58.88 39.936-10.24 48.128-18.944 58.88-58.88 10.24 39.424 18.944 48.128 58.88 58.88z"
              fill="#4A68CC"
              opacity=".5"
            ></path>
            <path
              d="M419.84 713.216v4.096l33.792 31.232 129.536-62.976L465.92 760.832v36.864l18.944-18.432v-0.512 0.512l18.944 18.432 100.352-122.88v-4.096z"
              fill="#4A68CC"
              opacity=".2"
            ></path>
            <path
              d="M860.16 551.936v-1.024c0-1.024-0.512-1.536-0.512-2.56v-0.512l-110.08-287.232c-15.872-48.64-60.928-81.408-112.128-81.408H387.072c-51.2 0-96.256 32.768-112.128 81.408L164.864 547.84v0.512c-0.512 1.024-0.512 1.536-0.512 2.56V757.76c0 65.024 52.736 117.76 117.76 117.76h460.8c65.024 0 117.76-52.736 117.76-117.76v-204.8c-0.512-0.512-0.512-0.512-0.512-1.024zM303.616 271.36s0-0.512 0.512-0.512C315.392 233.984 349.184 209.92 387.072 209.92h249.856c37.888 0 71.68 24.064 83.456 60.416 0 0 0 0.512 0.512 0.512l101.888 266.24H588.8c-8.704 0-15.36 6.656-15.36 15.36 0 33.792-27.648 61.44-61.44 61.44s-61.44-27.648-61.44-61.44c0-8.704-6.656-15.36-15.36-15.36H201.728L303.616 271.36zM829.44 757.76c0 48.128-38.912 87.04-87.04 87.04H281.6c-48.128 0-87.04-38.912-87.04-87.04v-189.44h226.816c7.168 43.52 45.056 76.8 90.624 76.8s83.456-33.28 90.624-76.8H829.44v189.44z"
              fill="#4A68CC"
              opacity=".5"
            ></path>
            <path
              d="M512 578.56c-14.336 0-25.6-11.264-25.6-25.6V501.76H253.44l83.968-219.136 0.512-1.024c7.168-21.504 26.624-35.84 49.152-35.84h249.856c22.528 0 41.984 14.336 49.152 35.84l0.512 1.024L770.56 501.76H537.6v51.2c0 14.336-11.264 25.6-25.6 25.6z"
              fill="#4A68CC"
              opacity=".2"
            ></path>
          </svg>
          <p className="text-base mt-2 font-medium">
            若购买成功却未展示订单，请刷新页面
          </p>
        </div>
      )}
      {data.map((item) => {
        if (item.order_status === 2) {
          return <SubmitUserWechatItem key={item.order_id} item={item} />;
        } else {
          return <DirectGetWechatItem key={item.order_id} item={item} />;
        }
      })}
    </section>
  );
}
