import {FC, useEffect, useState} from "react";
import {Profile} from "@/store";
import {Image, Text, View} from "@tarojs/components";
import Taro from "@tarojs/taro";
import styles from './login.module.scss'
import Icon from "@/components/icon";
import {userApi} from "@/api";
import {loginApi, LoginParams} from "@/api/login";
import MyButton from "@/components/button/MyButton";


const Login: FC = () => {
  const [isLoading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const {setUser, setToken, setCompany, empty} = Profile.useContainer()
  const [h5params, setH5Params] = useState<LoginParams | null>(null)

  useEffect(() => {
    empty(false)
    if (process.env.TARO_ENV === 'h5') {
      setLoading(true);
      loginApi.getParams().then((res) => {
        setH5Params(res);
        setError(null);
      }).catch(e => {
        setError(e?.errMsg ?? '系统内部错误')
      }).finally(() => {
        setLoading(false);
      })
    }
  }, [])

  function login() {
    if (isLoading) return;

    if (h5params == null && process.env.TARO_ENV === 'h5') {
      setError('页面参数错误，请刷新页面！')
      return;
    }

    setLoading(true)

    if (process.env.TARO_ENV === 'h5') {
      location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
        "appid=" + h5params!.appid +
        "&redirect_uri=" + encodeURIComponent(h5params!.route) +
        "&response_type=code" +
        "&scope=snsapi_userinfo" +
        "#wechat_redirect";
    } else {
      Taro.login({
        success: async (res) => {
          try {
            const {catch_key, user, token, company} = await userApi.login(res.code)
            if (token) {
              setUser(user)
              setToken(token)
              setCompany(company)
              setLoading(false)
              Taro.navigateBack()
            } else {
              Taro.setStorageSync('openid', catch_key)
              Taro.reLaunch({url: '/pages/check/check'})
            }
          } catch (e) {
          }
          setLoading(false)
        },
        fail: (res) => {
          setError(res.errMsg)
          setLoading(false)
        },
      })
    }
  }

  // async function TESTLOGIN() {
  //   const res = await loginApi.testLogin()
  //   Taro.setStorageSync('profile', JSON.stringify(res))
  //   Taro.reLaunch({url: '/pages/home/home'})
  // }

  return (
    <View className={styles.container}>
      <View className={styles.brand}>
        <Image mode={'scaleToFill'} src="https://playedu.yaojiankang.top/favicon.ico"/>
        <View className='mt-3'>医学道</View>
      </View>

      <View className={styles.loginTips}>
        <Text>请完成微信授权以继续使用！</Text>
      </View>
      <MyButton onClick={login} loading={isLoading}>微信授权登录</MyButton>

      {error ? <View className={styles.errorTips}>
        <View style={{flex: 1}}>{error}</View>
        <Icon name={'close'} onClick={() => setError(null)}/>
      </View> : null}
      {/*{process.env.TARO_APP_LGOIN === 'true' && <MyButton onClick={TESTLOGIN}>线下登录</MyButton>}*/}
    </View>
  )
}


export default Login
