import React, { useEffect, useRef, useState } from "react";
import md5 from "md5";
import { Form } from "antd";
import { login, qrCode, postQrCode } from "@/services/login";
import { json, useSearchParams } from "react-router-dom";
import LoginUse from "./LoginUse";
import LoginQrcode from "./LoginQrcode.bak";
export default (props) => {
  const [searchParams] = useSearchParams();
  const appid = searchParams.get("appid");
  const { onSuccess, mode } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [showLogin, setShowLogin] = useState(true);
  const [codeLapse, setCodeLapse] = useState(0); //0 未扫码,1 扫码, 2确认扫码 3取消扫码 4已删除

  const qrcodeRef = useRef();
  const refData = useRef();
  useEffect(() => {
    getQrCode();
    console.log(refData);
  }, [refData.id]);

  const onFinish = (values) => {
    const formData = new FormData();
    formData.append("name", values.name);
    formData.append("pwd", md5(values.pwd));
    if (mode) {
      formData.append("mode", mode);
    }
    formData.append("client", appid);

    setLoading(true);
    login(formData)
      .then((res) => {
        onSuccess(res);
        setLoading(false);
      })
      .catch((err) => {
        console.log("----err--", err);
        setLoading(false);
      });
  };

  const getQrCode = () => {
    qrCode({ client: appid || "authcenter" })
      .then((res) => {
        refData.current = res;
        createdCode(res);
        checkTimeUp();

        console.log(res);
      })
      .catch((err) => {
        setCodeLapse(4);
      });
  };

  const createdCode = (res) => {
    new QRCode(qrcodeRef.current, {
      width: 150,
      height: 150,
      text: res.qrCode,
      correctLevel: 3,
    });
  };
  /**
   * @param {*轮询方法}
   */
  //  检测二维码状态 业务代码
  const checkStatus = () => {
    const { current } = refData;
    return new Promise((resolve, reject) => {
      postQrCode(current.id, mode)
        .then((it) => {
          if (current.expire >= 0) {
            // 二维码还没有失效
            current.expire--;
            if (it.state == 0) {
              // console.log("未扫码");
              setCodeLapse(0);
              resolve();
            } else if (it.state == 1) {
              // console.log("已扫码");
              setCodeLapse(1);
              resolve();
            } else if (it.state == 3 || it.state == 4) {
              setCodeLapse(4);
              reject();
            } else if (it.token) {
              onSuccess(it);
            } else if (it == null) {
              console.log("null");
              setCodeLapse(4);
            }
          } else {
            // 二维码失效
            console.log("二维码失效");
            qrStop();
            setCodeLapse(4);
            reject();
          }
        })
        .catch((err) => {
          console.log(err);
          qrStop();
          setCodeLapse(4);
          reject();
        });
    });
  };

  // 检测二维码状态 逻辑代码
  let time = useRef();
  const checkTimeUp = () => {
    checkStatus()
      .then(() => {
        // console.log("===================");
        // console.log("最上面的", time.current);
        time.current = setTimeout(() => {
          // console.log("上面的", time.current);
          if (time.current) {
            // console.log("下面的", time.current);
            console.log("我先清除一下定时器");
            clearTimeout(time.current);
            checkTimeUp();
          }
        }, 1000);
      })
      .catch(() => {
        if (time.current) {
          clearTimeout(time.current);
        }
      });
  };

  // 删除二维码
  const qrStop = () => {
    if (qrcodeRef.current) {
      const idv = qrcodeRef.current.children;
      for (var i = idv.length - 1; i >= 0; i--) {
        qrcodeRef.current.removeChild(idv[i]);
      }
    } else {
      return;
    }
  };
  // 重新刷新二维码
  const onRenovate4 = () => {
    // 重新查询
    getQrCode();
    setCodeLapse(0);
  };
  // 重新刷新二维码
  const onRenovate1 = () => {
    // 重新查询
    clearTimeout(time.current);
    setCodeLapse(0);
    getQrCode();
  };
  // 切换账号登录
  const checkLoginUse = () => {
    setShowLogin(false);
    clearTimeout(time.current);
  };
  // 切换二维码登录
  const checkLoginwx = () => {
    setShowLogin(true);
    setCodeLapse(0);
    getQrCode();
  };
  return (
    <Form form={form} layout="vertical" onFinish={onFinish}>
      {showLogin ? (
        <LoginQrcode
          qrcodeRef={qrcodeRef}
          codeLapse={codeLapse}
          onRenovate4={onRenovate4}
          onRenovate1={onRenovate1}
          checkLoginUse={checkLoginUse}
        />
      ) : (
        <LoginUse loading={loading} checkLoginwx={checkLoginwx} />
      )}
    </Form>
  );
};
