import '~/styles/layout.scss'
import { useEffect, useState } from 'react';
import { useRouter } from '~/hooks/useRouter';
import Notify from './Notify';
import RenderRouter from './RenderRouter';
import routes, { tabbarData } from '../routes';
import Navbar from './Navbar';
import Tabbar from './Tabbar';
import { observer } from 'mobx-react';
import store from '~/store';
import useNotify from '~/hooks/useNotify';
import { ethers } from 'ethers';
import { bind_rmd } from '~/api';
import { AlreadyBind, BindRmd, BindSuccess, DefaultBind, UnLogin, VaildLink } from './ui';

const LayoutRouter = () => {

  const { location, push } = useRouter()
  const [visible, setVisible] = useState(false)
  const messageWs = useNotify('getMessage', visible)
  const { token, walletAddress, userInfo, visibleUnLogin } = store.state

  const [visibleVaildLink, setVisibleVaildLink] = useState(false) //无效的链接
  const [visibleAlreadyBind, setVisibleAlreadyBind] = useState(false) //已绑定
  const [visibleBindRmd, setVisibleBindRmd] = useState(false) //直接绑定
  const [shareAddress, setShareAddress] = useState('')
  const [visibleBindSuccess, setVisibleBindSuccess] = useState(false) //綁定成功
  const [visibleDefault, setVisibleDefault] = useState(false) //默認綁定


  const bindRecommend = async () => {
    const res: any = await bind_rmd(shareAddress)
    if (res.code === 0) {
      setVisibleBindRmd(false)
      store.getUserInfo()
      setTimeout(() => {
        push('/', null, true)
        setVisibleBindSuccess(true)
      }, 200)
    }
  }

  useEffect(() => {
    if (token) {
      store.getUserInfo()
      store.getCoinList()
      store.getMyNft('myNft')
      store.getMyNft('likeNft')
    }

    if (!token) {
      store.resetCoinList()
      store.resetUserInfo()
      store.resetNft("likeNft")
      store.resetNft("myNft")
    }

    token && messageWs.connect(token)
    !token && messageWs.disconnect()
  }, [token])

  useEffect(() => {
    const isModal = async () => {
      let user = userInfo
      let isRouter = routes.find(v => v.path === location.pathname)
      const address = location.pathname.substring(1, location.pathname.length)

      if (isRouter) return

      if (Object.keys(user).length <= 0) {
        const res: any = await store.getUserInfo()
        if (res) {
          user = res
        }
      }
      if (!ethers.utils.isAddress(address)) {
        // 无效的分享链接
        setVisibleVaildLink(true)
        return
      }
      // 地址相同
      if (address.toLocaleLowerCase() === walletAddress.toLocaleLowerCase()) return
      setShareAddress(address)
      // 绑定推荐人

      if (!user.is_bound && ethers.utils.isAddress(address)) {
        setVisibleBindRmd(true)
        return
      }
      // 已有推荐人
      if (user.is_bound && ethers.utils.isAddress(address)) {
        setVisibleAlreadyBind(true)
      }
    }

    token && isModal()
    !token && setVisibleBindRmd(false)
  }, [token, walletAddress])

  return (
    <div className='layout'>
      <Navbar
        pathname={location.pathname}
        setVisible={setVisible}
        token={token}
        messages={messageWs.messages}
        readAllMsg={messageWs.readAllMsg}
      />
      <div className='pages'>
        <RenderRouter />
        {
          tabbarData.includes(location.pathname) && location.pathname !== '/personal' && <div className='tabbar-block'></div>
        }
      </div>
      {
        tabbarData.includes(location.pathname) && (
          <Tabbar
            tabbarData={tabbarData}
            push={push}
            pathname={location.pathname}
          />
        )
      }
      <Notify
        visible={visible}
        setVisible={setVisible}
        messages={messageWs.messages}
        deleteAllMsg={messageWs.deleteAllMsg}
      />

      <div className="ui">
        {/* 無效鏈接 */}
        {visibleVaildLink && <VaildLink visible={visibleVaildLink} setVisible={setVisibleVaildLink} />}
        {/* 已經綁定 */}
        {visibleAlreadyBind && (
          <AlreadyBind
            onClick={() => {
              push('/', null, true)
              setVisibleAlreadyBind(false)
              push('/team')
            }}
            visible={visibleAlreadyBind}
            setVisible={setVisibleAlreadyBind}
          />
        )}
        {/* 綁定推薦人 */}
        {visibleBindRmd && (
          <BindRmd
            onClick={bindRecommend}
            address={shareAddress}
            visible={visibleBindRmd}
            setVisible={setVisibleBindRmd}
          />
        )}
        {
          visibleUnLogin && (
            <UnLogin
              visible={visibleUnLogin}
              setVisible={() => store.setVisibleUnLogin(false)}
            />
          )
        }
        {visibleDefault && (
          <DefaultBind
            visible={visibleDefault}
            setVisible={() => setVisibleDefault(false)}
            onClick={bindRecommend}
          />
        )}
        {visibleBindSuccess && (
          <BindSuccess
            visible={visibleBindSuccess}
            setVisible={() => setVisibleBindSuccess(false)}
            address={shareAddress}
          />
        )}

      </div>
    </div>
  );
}

export default observer(LayoutRouter)