import {CSSProperties, FC, useState} from "react";
import {View, Image} from "@tarojs/components";
import styles from './index.module.scss'
import NoLogin from '@/static/img/noLogin.png'
import {Profile} from "@/store";
import Taro from "@tarojs/taro";
import {userApi} from "@/api";

interface Props {
  tips?: string
  height?: number
  paddingTop?: number
  style?: CSSProperties
  offImage?: boolean
  onSuccess?: VoidFunction
}

const LoginView: FC<Props> = (props) => {
  const [isLoading, setLoading] = useState(false)
  const {setUser, setToken, setCompany} = Profile.useContainer()
  const sizeStyle: CSSProperties = {
    height: `${props.height || 1000}rpx`,
    paddingTop: `${props.paddingTop || 0}rpx`,
    ...props.style,
  }

  function login() {
    if (isLoading) return;
    Taro.showLoading({title: '微信授权中...'})
    setLoading(true)
    Taro.login({
      success: async (res) => {
        try {
          const {catch_key, user, token, company} = await userApi.login(res.code)
          Taro.hideLoading()
          if (token) {
            Taro.showToast({title: '授权成功', duration: 1500, icon: 'success', mask: true})
            setTimeout(() => {
              setUser(user)
              setToken(token)
              setCompany(company)
              setLoading(false)
              if (props.onSuccess) {
                props.onSuccess()
              } else {
                Taro.switchTab({url: '/pages/home/home'})
              }
            }, 1500)
          } else {
            Taro.setStorageSync('openid', catch_key)
            Taro.reLaunch({url: '/pages/check/check'})
          }
        } catch (e) {
          Taro.hideLoading()
        }
        setLoading(false)
      }
    })
  }

  return (
    <View className={styles.content} style={sizeStyle}>
      {
        !props.offImage && <>
          <Image src={NoLogin}/>
          <View className={styles.title}>暂未登录</View>
        </>
      }
      <View className={styles.label}>点击按钮完成微信授权</View>
      <View onClick={login} className={styles.button}>立即登录</View>
    </View>
  )
}

export default LoginView
