import React, { useEffect, useState } from 'react';
import { encode } from 'js-base64';
import Cookies from 'js-cookie';
import { LOGIN_WAY } from '@/constants';
import { WECOM_APPID, AGENTID_CLOUD } from '@/constants';
import styles from './index.less';

const useWeCom = props => {
  useEffect(() => {
    window.WwLogin({
      id: props.container || 'wxlogin_container',
      appid: props.appid || WECOM_APPID,
      agentid: props.agentid || AGENTID_CLOUD,
      redirect_uri: props.redirect_uri || encodeURIComponent(window.location.href),
      href: props.href || 'https://panda-water.cn/web4/styles/wx.css',
      self_redirect: false,
      state: props.state || 'STATE',
    });
  }, []);
};

const useIOTQRCode = () => {
  const [rstate, setRstate] = useState(() =>
    encode(`panda_${Math.round(Math.random() * 10000 + Date.now()).toString(16)}`),
  );
  useEffect(() => {
    Cookies.set('redirect_state', rstate, {
      expires: 5 * 60 * 1000,
      path: '/',
    });
  }, []);

  const redirectURI = function() {
    let redirectUri = window.location.href;
    if(redirectUri.indexOf('loginWay') > -1) return redirectUri;
    if(redirectUri.indexOf('?') > -1) redirectUri += `&loginWay=${LOGIN_WAY.WeCom}`;
    else redirectUri += `?loginWay=${LOGIN_WAY.WeCom}`;
    return redirectUri;
  }
  const props = Object.assign(
    {},
    {
      container: 'wxlogin_container',
      appid: WECOM_APPID,
      agentid: AGENTID_CLOUD,
      redirect_uri: encodeURIComponent(window.location.href), // window.location.href
      href: 'https://panda-water.cn/web4/styles/wecom.css',
      state: rstate,
    },
  );
  useWeCom(props);
  return (
    <div id="wxlogin_container" className={styles.wxlogin_container}></div>
  );
};

export default useIOTQRCode;
