import {useEffect, useLayoutEffect, useRef} from "react";
import {useParams} from "react-router";
import {flushSync} from "react-dom";
import {message} from "antd";
import {history} from "@@/core/history";
import {useIntl, useModel} from "@@/exports";
import {fsQrLogin} from "@/services/role";
import './fsqd.css'
const FsQr = () => {
  //创建实例 当用户扫码成功后会触发handleMessage方法然后跳转到【goto】,然后又会携带code跳转到当前的登录页面
  // const a = useRef(1);

  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

  const goto = useRef('');
  const redirectUri = useRef('');
  const QRLoginObj = useRef(null);
  useEffect(() => {
    window.addEventListener('message', handleMessage, false);
    return () => {
      // 移除 message 通知，防止再次重定向
      window.removeEventListener('message', handleMessage, false);
    };
  }, []);

  useLayoutEffect(() => {

    // 若存在 code 则为已扫码或者已授权状态，不做重定向--坑点
    if (window.location.search.indexOf('code') !== -1) {
      let params = new URLSearchParams(window.location.search);
      let paramValue = params.get('code');
      //
      // console.log(paramValue)
      fsQrLogin({code:paramValue}).then(res=>{
        // console.log(res,'1111111')
        // 获取权限信息，跳转到主页面

        // 登录
        const msg = res;
        if (msg.token) {
          // localStorage.setItem('srmToken',msg.token)

          localStorage.setItem('Token',msg?.token)
          localStorage.setItem('userInfo',JSON.stringify(msg?.member))

          // alert(msg?.token)
          // msg.user.name = msg.member.name
          // localStorage.setItem('userInfo',JSON.stringify(msg?.member))

          //

          const defaultLoginSuccessMessage = intl.formatMessage({
            id: 'pages.login.success',
            defaultMessage: '登录成功！',
          });
          message.success(defaultLoginSuccessMessage);
          fetchUserInfo(msg?.member)
          const urlParams = new URL(window.location.href).searchParams;
          history.push(urlParams.get('redirect') || '/');
          return;
        }
        // console.log(msg);
        // 如果失败去设置用户错误信息
        // setUserLoginState(msg);
        // }

      }).catch(err=> {
        // 如果接口报错，清除 浏览器code信息
        const defaultLoginFailureMessage = intl.formatMessage({
          id: 'pages.login.failure',
          defaultMessage: '登录失败，请重试！',
        });
        console.log(err);
        message.error(defaultLoginFailureMessage);
        history.push('/user/login');
      })
      //
    }

    const domain = window.location.hostname;
    const port = window.location.port;
    console.log(domain);
    console.log(port);
    const src = domain
    redirectUri.current = `${window?.location?.origin}/user/login`;//重定向地址，需在管理后台进行配置
    goto.current =  `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=cli_a3631f654971500d&redirect_uri=http://${src}/user/login&response_type=code&state=state123456`

    console.log(goto.current,'++++++++++++++++++++++++')
    let script = document.querySelector('#script');
    if (script) {
      return;
    }
    script = document.createElement('script');
    script.id = 'script';
    script.src = 'https://sf3-cn.feishucdn.com/obj/feishu-static/lark/passport/qrcode/LarkSSOSDKWebQRCode-1.0.2.js';
    document.querySelector('body').appendChild(script);
    //
    setTimeout(()=> {

      QRLoginObj.current = QRLogin({
        id: 'login_container',
        goto: goto.current,
        width: '250',
        height: '260',
        position: 'fixed',
        top: '50vh',
        left: 0,
        right: 0,
        margin: '0 auto',
        display: 'flex',
        justifyContent: 'center'
      });
    },1000)

  }, []);

  const fetchUserInfo = (member:any) => {
    //
    const userInfo = member;
    //
    if (userInfo) {

      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });

      // 同步登录信息到 local
      // localStorage.setItem('user',JSON.stringify(userInfo))

    }
  };


  const handleMessage = (event: any) => {
    // console.log(event.data,'++++++')
    const loginTmpCode = event.data;
    const origin = event.origin;
    //

    // if( QRLoginObj?.current?.matchOrigin(origin) ) {
    // 若存在 code 则为已扫码或者已授权状态，不做重定向--坑点

    if (window.location.search.indexOf('code') !== -1)  return
    //
    // 不存在 code 则 飞书重定向
    window.location.href = `${goto.current}&tmp_code=${loginTmpCode}`;
    // console.log(loginTmpCode,'后')
    // }
  };

  return (
    <div id='login_container'></div>
  )
}

export default FsQr
