import {useEffect, useState} from "react";
import Taro from '@tarojs/taro'
import {View} from '@tarojs/components'
import {Radio, Button} from '@nutui/nutui-react-taro'
import {getStoredInviteParams} from "@/utils/invite";
import {TenantId} from "@/config/app";
import {useUser} from "@/hooks/useUser";

const Login = () => {
  const [isAgree, setIsAgree] = useState(false)

  const {loginUser} = useUser();

  const reload = () => {
    Taro.hideTabBar()
  }

  /* 获取用户手机号 */
  const handleGetPhoneNumber = ({detail}: { detail: { code?: string, encryptedData?: string, iv?: string } }) => {
    const {code, encryptedData, iv} = detail

    // 获取存储的邀请参数
    const inviteParams = getStoredInviteParams()
    const refereeId = inviteParams?.inviter ? parseInt(inviteParams.inviter) : 0

    Taro.login({
      success: function (loginRes) {
        if (code) {
          Taro.request({
            url: 'https://server.websoft.top/api/wx-login/loginByMpWxPhone',
            method: 'POST',
            data: {
              authCode: loginRes.code,
              code,
              encryptedData,
              iv,
              notVerifyPhone: true,
              refereeId: refereeId, // 使用解析出的推荐人ID
              sceneType: 'save_referee',
              tenantId: TenantId
            },
            header: {
              'content-type': 'application/json',
              TenantId
            },
            success: function (res) {
              if (res.data.code == 1) {
                Taro.showToast({
                  title: res.data.message,
                  icon: 'error',
                  duration: 2000
                })
                return false;
              }
              // 登录成功
              const token = res.data.data.access_token;
              const userData = res.data.data.user;

              // 使用useUser Hook的loginUser方法更新状态
              loginUser(token, userData);

              // 显示登录成功提示
              Taro.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1500
              })

              // 返回上一页
              Taro.navigateBack();
            }
          })
        } else {
          console.log('登录失败！')
        }
      }
    })
  }

  useEffect(() => {
    reload()
  }, [])

  return (
    <>
      <View className={'flex flex-col justify-center px-5'}>
        <View className={'text-3xl text-center py-5 font-normal my-10'}>授权登录</View>

        <>
          {isAgree && (
            <View className={'flex justify-center my-5 py-3 rounded-lg '} style={{
              backgroundColor: '#22c55e',
            }}>
              <Button open-type="getPhoneNumber"
                      style={{color: '#ffffff', height: 'auto'}}
                      onGetPhoneNumber={handleGetPhoneNumber} size={'large'} className={'w-full rounded-lg p-2'}
                      disabled={!isAgree}>授权手机号并登录</Button>
            </View>
          )}
          {!isAgree && (
            <View className={'flex justify-center my-5 py-1 rounded-lg '} style={{
              backgroundColor: '#93a3af',
            }}>
              <View style={{color: '#ffffff', height: 'auto'}} className={'w-full rounded-lg text-sm text-center p-2'}>授权手机号并登录</View>
            </View>
          )}
        </>

        <View className={'my-2 flex text-sm items-center px-1'}>
          <Radio style={{color: '#333333'}} checked={isAgree} onClick={() => setIsAgree(!isAgree)}></Radio>
          <span className={'text-gray-400'} onClick={() => setIsAgree(!isAgree)}>勾选表示您已阅读并同意</span><a
          onClick={() => Taro.navigateTo({url: '/passport/agreement'})}
          className={'text-blue-600'}>《服务协议及隐私政策》</a>
        </View>
      </View>
    </>
  )
}
export default Login
