import React, { useEffect, useState } from 'react';
import { encode } from 'js-base64';
import Cookies from 'js-cookie';
import WxLogin from '../components/WxLogin';
import { WECHART_APPID, WX_REDIRECT_URI } from '../../../../constants';

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 props = Object.assign(
    {},
    {
      self_redirect: false,
      scope: 'snsapi_login',
      appid: WECHART_APPID,
      state: rstate,
      redirect_uri: WX_REDIRECT_URI,
      href: 'https://panda-water.cn/web4/styles/PandaIOTQrcodeStyle.css',
    },
  );
  return <WxLogin {...props} />;
};

export default useIOTQRCode;
