
import React , { useState } from 'react'

import Taro, { useDidShow } from '@tarojs/taro'

import { View, Image, Button } from '@tarojs/components'

import "taro-ui/dist/style/components/button.scss" // 按需引入

import './index.scss'

import { getUserPhoneNumber } from '../../api/user'

import Tip from '../../utils/tip'

console.log(Taro, 'Taro.getStorageSync');

const Index: React.FC = () => { 

  const [token, setToken] = useState<string>('')

  useDidShow(() => {
    setToken(Taro.getStorageSync('token'))
  })
  
  // 获取用户手机号
  const Getphonenumber = async (item: number ,e: any): Promise<void> => {
    
    Tip.loading('正在登录...')
    const { code } = await Taro.login()
    const data = await getUserPhoneNumber({code, ...e.detail})
    Tip.loaded()

    Taro.setStorageSync('token', data)

    goPage(item)
  }

  // 跳转页面
  const goPage = ( index: number ): void => {
    console.log(index, 'indexindexindexindexindexindex');
    
    if (!Taro.getStorageSync('token')) {
      Tip.toast('登录错误')
      return
    }
    switch (index) {
      case 0:
        Taro.navigateTo({
           url: '/pages/ScanQrcode/index'
        });
        break
      case 1:
        Taro.navigateTo({
           url: '/pages/AuthQuery/index'
        });
    }
  }

  const RenderItem = (item: number) => {
    
    const noHasPhoneEle = (
      <Button 
        className='button' 
        open-type='getPhoneNumber'
        onGetPhoneNumber={(e) => Getphonenumber(item, e)}
      >
          <Image
            className='item-img' 
            src={require(`../../assets/home/home${item}.png`)}
          />
      </Button>
    )

    const hasPhoneELe = (
      <Image
        className='item-img' 
        src={require(`../../assets/home/home${item}.png`)}
        onClick={() => goPage(item)}
      />
    )

    return (
      <React.Fragment>
        {
          token ? hasPhoneELe : noHasPhoneEle
        }
      </React.Fragment>
    )
  }

  return (
    <View className='index'>
      <Image className='index-bg'  src={require('../../assets/home/bg.png')} />
      {
        [0, 1].map( item => (
          <React.Fragment key={item}>
          {
            RenderItem(item)
          }
          </React.Fragment>
        ))
      }
    </View>
  )

}

export default Index
