import '~/styles/personal.scss'
import { Button, Divider, List, Overlay, Swiper, SwiperInstance, Toast } from "react-vant"
import BackBar from "~/components/BackBar"
import { useEffect, useRef, useState } from 'react'
import { getTime, splitAddress } from '~/utils'
import { observer } from 'mobx-react'
import store from '~/store'
import { my_invite, team_info } from '~/api'
import useCopyLink from '~/hooks/useCopy'
import { InviteRecordData } from '~/types/store'
import { useRouter } from '~/hooks/useRouter'
import { copy } from '~/utils/copy'
import QRCode from 'qrcode'

const Team = () => {

  const { push } = useRouter()
  const { token } = store.state
  const { copyVal } = useCopyLink()
  const [address, setAddress] = useState('')
  const [inviteList, setInviteList] = useState([] as InviteRecordData[])
  const [finished, setFinished] = useState(true);
  const [visible, setVisible] = useState(false);
  const [cardState, setCardState] = useState([
    [
      { title: '我的推薦人', value: '000000000', id: 1 },
      { title: '級別獎勵', value: '10% 5%', id: 2 },
    ],
    [
      { title: '獎勵金額', value: '0U', id: 4 },
      { title: '直推人數', value: '0人', id: 6 },
      { title: '閒推人數', value: '0人', id: 5 },
    ],
  ])

  const query = useRef({ page: 1, page_size: 20 })

  const getInviteData = async () => {
    let res: any = await my_invite(query.current);
    if (res && res.code === 0 && res.data) {
      if (res.data.length < 20) {
        if (inviteList.length <= 0) {
          setInviteList(res.data)
        } else {
          setInviteList([...inviteList, ...res.data])
        }
        setFinished(true)
        return
      }
      query.current.page = query.current.page + 1
      if (inviteList.length <= 0) {
        setInviteList(res.data)
      } else {
        setInviteList([...inviteList, ...res.data])
      };
      setFinished(false)
    }
  }


  useEffect(() => {
    const getData = async () => {
      const res: any = await team_info()
      if (res && res.code === 0) {
        cardState[0][0].value = res.data.inviti_address || '000000000000000'
        cardState[1][0].value = res.data.award ? res.data.award + "U" : "0U"
        cardState[1][1].value = res.data.direct_count ? res.data.direct_count + '人' : '0人'
        cardState[1][2].value = res.data.indirect_count ? res.data.indirect_count + '人' : '0人'
        setCardState([...cardState])
        setAddress(res.data.address)
      }
    }

    token && getData()
    token && getInviteData();
    !token && push('/', null, true)
  }, [token])

  return (
    <div className="plr-2 team">
      <BackBar
        title='团队'
      />
      <Button className="mt-2 button" onClick={() => setVisible(true)}>分享赚取佣金</Button>
      <div className="row-between" style={{ alignItems: 'flex-end' }}>
        <div className='fz-24 fz-wb-550 mb-6px'>邀请好友，挣奖励</div>
        <div className="tar">
          <div className="fz-wb-550">最高可得</div>
          <div className="fz-wb-550 fz-60">10%</div>
        </div>
      </div>

      <div className='card-box'>
        {
          cardState.map((v, index) => (
            <div key={index} className="row-between" style={{ justifyContent: 'space-around' }}>
              {
                v.map(item => (
                  <div key={item.id} className={`tac ${index === 1 && 'mt-2'}`}>
                    <div className='fz-14'>{item.title}</div>
                    <div className='mt-1 fz-wb-550'>
                      {item.id === 1 ? splitAddress(item.value) : item.value}
                      {
                        item.id === 1 && (
                          <i className='iconfont icon-fuzhi_copy white ml-5px' onClick={() => copyVal(item.value)}></i>
                        )
                      }
                    </div>
                  </div>
                ))
              }
            </div>
          ))
        }
      </div>

      <div className='mt-3'>
        <div className='fz-18'>我的邀请</div>
        <div className='mt-5px'>
          <Divider style={{ margin: 0, borderColor: '#2A2C24' }} />
        </div>
        <div className='row mt-1 tac fz-14'>
          <div style={{ flex: 1 }}>地址</div>
          <div style={{ flex: 1 }}></div>
          <div style={{ flex: 1 }}>時間</div>
        </div>
        <List
          finished={finished}
          onLoad={getInviteData}
          errorText="請求失敗，點擊重新加載"
          finishedText="已經到底了"
          offset={10}
        >
          <div>
            {
              inviteList.map((item, index) => (
                <div className='row mt-2 tac fz-14' key={index}>
                  <div style={{ flex: 1 }}>{splitAddress(item.address)}</div>
                  <div style={{ flex: 1 }}></div>
                  <div style={{ flex: 1 }}>{getTime(item.time * 1000)}</div>
                </div>
              ))
            }
          </div>
        </List>
      </div>
      {
        visible && <ShareModal visible={visible} setVisible={setVisible} address={address} />
      }
    </div>
  )
}

const ShareModal = (
  { visible, setVisible, address }: { visible: boolean, setVisible: Function, address: string }
) => {

  const [swiperIndex, setSwiperIndex] = useState(0)
  const swiperRef = useRef<SwiperInstance>(null)
  const [qrcodeUri, setQrcodeUri] = useState('')

  const handleSwiper = () => {
    if (swiperIndex === 0) {
      swiperRef.current?.swipeNext()
    } else {
      swiperRef.current?.swipePrev()
    }
  }

  const downloadQrcode = () => {
    if (!qrcodeUri) return
    const link = document.createElement('a')
    link.href = qrcodeUri
    link.download = `${Date.now()}.png`
    link.click()
    link.remove()
  }

  useEffect(() => {
    copy(process.env.REACT_APP_SHARE_LINK + address)
    QRCode.toDataURL(process.env.REACT_APP_SHARE_LINK + address, (err, url) => {
      if (url) {
        setQrcodeUri(url)
      }
    })
  }, [])

  return (
    <Overlay visible={visible}>
      <div className='mt-5 white-color overlay'>
        <div className='row-justify-end pr-3'>
          <i className='iconfont icon-close fz-36' onClick={() => setVisible(false)}></i>
        </div>
        <Swiper
          ref={swiperRef}
          indicator={() => <></>}
          onChange={(index) => setSwiperIndex(index)}
          initialSwipe={swiperIndex}
          touchable={false}
        >
          <Swiper.Item>
            <div className='swiper-height'>
              <div className='row-center'>
                <div className='mt-5'>
                  <img src={require('~/assets/share.png')} alt="" className='share-img' />
                </div>
              </div>
              <div className='url mt-2 row-center'>
                {splitAddress(process.env.REACT_APP_SHARE_LINK + address, 14)}
                <i className='iconfont icon-fuzhi_copy ml-1 fz-24' onClick={() => {
                  copy(process.env.REACT_APP_SHARE_LINK + address, () => {
                    Toast.success('复制成功')
                  })
                }}></i>
              </div>
              <div className='mt-2 tac fz-wb-550 fz-26'>成功複製分享碼</div>
              <div className='mt-2 tac'>轉發給好友並在錢包裏打開完成綁定</div>
            </div>
          </Swiper.Item>
          <Swiper.Item>
            <div className='swiper-height'>
              <div className='row-center mt-5'>
                <img src={qrcodeUri} alt="" className='share-img' />
              </div>
              <div className='url mt-2 row-center'>
                截圖或下載圖片
                <i className='iconfont icon-download ml-1 fz-24' onClick={downloadQrcode}></i>
              </div>
              <div className='mt-2 tac fz-wb-550 fz-26'>掃描綁定關係</div>
              <div className='mt-2 tac'>在好友錢包裡掃一掃完成綁定</div>
            </div>
          </Swiper.Item>
        </Swiper>

        <div className='row-center' >
          <div className='button' onClick={handleSwiper}>
            <div className='text-index plr-2'>
              <div>
                {swiperIndex === 0 ? '切換二維碼' : '切換分享鏈接'}
              </div>
              <i className='iconfont icon-arrow-right-bold fz-20'></i>
            </div>
          </div>
        </div>
      </div>
    </Overlay>
  )
}


export default observer(Team)