import { View } from "@tarojs/components";
import Buttons from '@components/Buttons'
import Texts from '@components/Texts'
import './ChooseAuth.scss'
import { ButtonType, ComponentStatus, TextType } from "../utils/types";
import Taro, { useReady } from "@tarojs/taro";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { wxLogin } from "@/services/user";

export default function Page() {
    const dispatch = useDispatch();
    const counter = useSelector((state: any) => state.counter.value);
    var code = '';

    const user = useSelector((state: any) => state.user);

    useEffect(() => {
        if (user.isLogin) {
            if (user.scenario_select_count > 0) {
                Taro.navigateBack({
                    delta: 1
                })
            }
            else {
                Taro.redirectTo({
                    url: '/pages/ChooseScenario'
                })
            }

        }
    }, [user.isLogin])

    useReady(() => {
        Taro.login().then(res => {
            code = res.code;
            // dispatch(wxLogin({code:res.code}) as any);

        })
    })

    async function login() {
        try {
            const { encryptedData, iv } = await Taro.getUserProfile({
                desc: '获取用户信息',
            });

            dispatch(wxLogin(code, encryptedData, iv) as any);

            // 在这里处理用户信息
        } catch (error) {
            console.log('获取用户信息失败:', error);
        }
    }

    function createAccount() {
        Taro.navigateTo({
            url: '/pages/Auth'
        })
    }

    return <View className="container choose_container">
        <Texts text='App name' type={TextType.big} />
        <Texts text={counter} />
        <View style={{ height: 100 }} />
        <Buttons title='WeChat' onClick={login} style={{ width: 289, marginBottom: 30 }} />
        <Buttons title='Create account' type={ButtonType.outline} onClick={createAccount} style={{ width: 289, marginBottom: 30 }} />
    </View>;
}