
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>('')

  const [code, setCode] = useState<string>('')

  useDidShow(async () => {
    setToken(Taro.getStorageSync('token'))
    const r = await Taro.login()
    console.log(r, 'codecodecodecode');

    setCode(r.code)
  })

  const checkSession = () => {
    return new Promise(resolve => {
      Taro.checkSession({
        success: async res => {
          console.log('session_key 未过期，并且在本生命周期一直有效', res);
          resolve(1)
        },
        fail: async res => {
          console.log('fail:', res);
          // session_key 已经失效，需要重新执行登录流程
          const r = await Taro.login() //重新登录
          setCode(r.code)
          resolve(0)
        }
      })
    }).catch(e => e)
  }

  // 获取用户手机号
  const Getphonenumber = async (item: number, e: any): Promise<void> => {

    Tip.loading('正在登录...')

    await checkSession()

    console.log(code,item, e, '获取用户手机号');

    const data = await getUserPhoneNumber(code)

    console.log(data,'getUserPhoneNumber')

    Tip.loaded()

    Taro.setStorageSync('token', data)

    goPage(item)
  }

  // 跳转页面
  const goPage = (index: number): void => {

    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'
        });
        break
      case 2:
        Taro.navigateTo({
          url: '/pages/ReportPiracy/index'
        });
    }
  }

  const RenderItem = (item: number) => {

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

    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, 2].map(item => (
          <React.Fragment key={item}>
            {
              RenderItem(item)
            }
          </React.Fragment>
        ))
      }
    </View>
  )

}

export default Index
