import { View, Text, Image } from "@tarojs/components";
import Buttons from '@/components/basic/Buttons'
import Texts from '@/components/basic/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";
import { ColorType, MainColorType } from "@/context/themes/color";
import { ChooseScenarioBtn } from "@/features/common/SpecBtns";
import { useTranslation } from "react-i18next";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { loginSuccess } from "@/store/user";
import RequestType, { thirdPartRequest } from "@/services/thirdPartRequest";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { rpxToPx } from "@/utils/tools";

let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}


export default function Page() {
    const [btnDisable, setBtnDisable] = useState(false)
    const [code, setCode] = useState('')
    const dispatch = useDispatch();
    const { t } = useTranslation()

    const user = useSelector((state: any) => state.user);
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        if (navigation) {
            navigation.setOptions({
                headerTitle: '',
            });
        }
        if (user.isLogin) {
            if (user.is_new_user) {
                console.log('new user')
                if (user.scenario_select_count == 0) {
                    console.log('new')
                    // Taro.redirectTo({
                    //     url: '/pages/clock/ChooseScenario?trigger_event=SETUP_UPON_ACCOUNT_CREATION'
                    // })
                    setTimeout(() => {
                        Taro.redirectTo({
                            url: '/_account/pages/ProfileSetting?newuser=1'
                        })
                    }, 100)
                }
                else {
                    console.log('replace')
                    Taro.redirectTo({
                        url: '/_account/pages/ProfileSetting?newuser=1'
                    })
                }


            }
            else {
                console.log('old user')
                // if (user.scenario_select_count > 0) {
                //     Taro.navigateBack({
                //         delta: 1
                //     })
                // }
                // else {
                //     Taro.redirectTo({
                //         url: '/pages/clock/ChooseScenario'
                //     })
                // }
            }


        }
    }, [user.isLogin])

    useReady(() => {
        // getCode()

    })

    function getCode() {
        setBtnDisable(true)
        if (process.env.TARO_ENV === 'weapp') {
            thirdPartRequest(RequestType.RequestTypeWXLogin).then(res => {
                login((res as any).code)
            }).catch(err => {
                Taro.showToast({
                    title: '登录失败，请稍等重试',
                    icon: 'none'
                })
                setBtnDisable(false)
            })

            // Taro.login().then(res => {
            //     setCode(res.code)
            //     login(res.code)
            //     // setBtnDisable(false)
            // }).catch(e => {
            //     console.log(e)
            //     // getCode()
            //     setBtnDisable(false)
            // })
        }
    }

    async function login(strCode) {
        setBtnDisable(true)
        var params: any = {}
        var share_uid = Taro.getStorageSync('share_uid')
        var share_info = Taro.getStorageSync('share_info')
        if (share_uid) {
            params.follow_origin = share_info ? 'WECHAT_GROUP_CHAT' : 'WECHAT_PRIVATE_CHAT'
            if (share_info) {
                var groupInfo = JSON.parse(share_info)
                params.wechat = groupInfo
                // {
                //     encryptedData: groupInfo.encryptedData,
                //     iv: groupInfo.iv
                // }
            }
        }

        console.log(share_uid, share_info, params)

        wxLogin(strCode, params).then(res => {
            console.log(res)
            dispatch(loginSuccess(res));
            setBtnDisable(false)
            if (!(res as any).is_new_user) {
                Taro.navigateBack({
                    delta: 1
                })
            } else {
                Taro.setStorage({ key: '149alert', data: true })
            }

            // if (!(res as any).is_new_user){
            //     if ((res as any).scenario_select_count > 0) {
            //         console.log('choose auth navi back')
            //         Taro.navigateBack({
            //             delta: 1
            //         })
            //     }
            //     else {
            //         debugger
            //         Taro.redirectTo({
            //             url: '/pages/clock/ChooseScenario?trigger_event=SETUP_UPON_ACCOUNT_CREATION'
            //         })
            //     }
            // }
        }).catch(e => {
            setBtnDisable(false)
        })
        // dispatch(wxLogin(code) as any);
        // try {
        //     const { encryptedData, iv } = await Taro.getUserProfile({
        //         desc: '获取用户信息',
        //     });

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

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

    function createAccount1() {
        jumpPage('/_account/pages/Auth', 'Auth', navigation)
    }

    function login1() {
        jumpPage('/_account/pages/Auth', 'Auth', navigation, { isLogin: true })
    }

    return <View className="container choose_container">
        <Image src={require('@assets/_health/main_logo.png')} style={{ width: rpxToPx(160), height: rpxToPx(160) }} />
        <View className="h50 bold" style={{ marginTop: rpxToPx(24), marginBottom: rpxToPx(12) }}>fast16cc</View>
        <Text className="h30" style={{ marginBottom: rpxToPx(678) }}>{t('page.choose_auth.slogan')}</Text>
        <View className="main_footer">
            {
                process.env.TARO_ENV == 'weapp' ? <NewButton
                    type={NewButtonType.fill}
                    color={MainColorType.success}
                    title={t('page.choose_auth.btn_wechat')}
                    width={rpxToPx(646)}
                    height={rpxToPx(96)}
                    onClick={getCode}
                /> :
                    <NewButton
                        type={NewButtonType.fill}
                        color={MainColorType.success}
                        title={t('page.choose_auth.btn_login')}
                        width={rpxToPx(646)}
                        height={rpxToPx(96)}
                        onClick={login1}
                    />
            }
            {
                process.env.TARO_ENV == 'rn' && <View style={{ height: 30 }} />
            }
            {
                process.env.TARO_ENV == 'rn' && <NewButton
                    type={NewButtonType.fill}
                    color={MainColorType.success}
                    title={t('page.choose_auth.btn_signup')}
                    width={rpxToPx(646)}
                    height={rpxToPx(96)}
                    onClick={createAccount1}
                />
                // <ChooseScenarioBtn disable={btnDisable} title={t('page.choose_auth.btn_signup')} onClick={createAccount1} background={ColorType.fast} />
            }
        </View>



    </View>;
}