import NewButton, { NewButtonType } from "@/_health/base/new_button";
import Card from "@/_health/components/card";
import showActionSheet from "@/components/basic/ActionSheet";
import showAlert from "@/components/basic/Alert";
import Buttons from "@/components/basic/Buttons";
import Footer from "@/components/layout/Footer";
import TableCell from "@/components/layout/TableCell";
import { ColorType, MainColorType } from "@/context/themes/color";
import { ChooseScenarioBtn } from "@/features/common/SpecBtns";
import { APP_VERSION, WX_VERSION } from "@/services/http/api";
import { clear, logout } from "@/services/user";
import { logoutSuccess } from "@/store/user";
import { kIsAndroid, rpxToPx } from "@/utils/tools";
import { View, Text, Button } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";

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

let hasCache = false;

export default function Page() {
    const dispatch = useDispatch();
    const { t, i18n } = useTranslation()
    const user = useSelector((state: any) => state.user);
    const [languageType, setLanguageType] = useState('')
    let showActionSheetWithOptions;
    if (process.env.TARO_ENV == 'rn') {
        showActionSheetWithOptions = useActionSheet()
    }
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        Taro.setNavigationBarTitle({
            title: t('page.setting.title')
        })

        if (process.env.TARO_ENV == 'rn') {
            navigation.setOptions({ title: t('page.setting.title') ?? '' });
        }

        Taro.getStorage({ key: 'notification' }).then(res => {
            hasCache = true;
        })

        loadLanguage()


        console.log(Taro.getAppBaseInfo().language)
    }, [])

    async function loadLanguage() {
        var lg = await getStorage('language')
        if (lg.length > 0) {
            switch (lg) {
                case 'wechat':
                    setLanguageType('微信系统语言')
                    break
                case 'zh':
                    setLanguageType('中文')
                    break
                case 'en':
                    setLanguageType('English')
                    break
            }
        }
        else {
            setLanguageType('中文')
        }
    }

    async function getStorage(key: string) {
        try {
            const res = await Taro.getStorage({ key });
            return res.data;
        } catch {
            return '';
        }
    }

    async function logoutF() {
        // var showDayRing = await getStorage('showedDisqualifiedAlert') || false;
        showAlert({
            title: t('feature.common.modal.logout_title'),
            content: t('feature.common.modal.logout_content'),
            showCancel: true,
            confirm: () => {
                logout().then(res => {
                    dispatch(logoutSuccess())

                    if (hasCache) {
                        Taro.setStorage({
                            key: 'notification',
                            data: true
                        })
                    }

                    if (process.env.TARO_ENV == 'rn') {
                        var Jto = require('react-native').NativeModules.NativeBridge;
                        Jto.clearNotification()

                    }

                    // if (showDayRing) {
                    //     Taro.setStorage({
                    //         key: 'showedDisqualifiedAlert',
                    //         data: true
                    //     })
                    // }

                    if (process.env.TARO_ENV == 'weapp') {
                        Taro.switchTab({
                            url: '/pages/clock/Clock'
                        })
                        //check
                        //退出到首页后，点击登录，会再次执行naviback函数
                        // Taro.navigateBack();
                        console.log('setting navi back')
                    }
                    else {
                        navigation.goBack()
                    }
                }).catch((e) => {

                })
            }
        })

    }

    function del() {
        showActionSheet({
            title: t('feature.common.modal.deluser_action_title'),
            showActionSheetWithOptions: showActionSheetWithOptions,
            itemList: [t('feature.common.modal.deluser_action_confirm')],
            success: (res) => {
                switch (res) {
                    case 0:
                        {
                            showAlert({
                                title: t('feature.common.modal.deluser_title'),
                                content: t('feature.common.modal.deluser_content'),
                                showCancel: true,
                                confirmText: t('feature.common.modal.deluser_cancel'),
                                cancelText: t('feature.common.modal.deluser_confirm'),
                                redCancel: true,
                                cancel: () => {
                                    delUser()
                                }
                            })
                        }
                        break;
                }
            }
        })
    }

    function delUser() {
        dispatch(clear() as any);
        setTimeout(() => {
            navigation.goBack()
        }, 1500)
    }

    function changeLanguage() {
        showActionSheet({
            alertText: '更改语言',
            itemList: ['中文', 'English', '微信系统语言'],
            success: function (res) {
                if (res != -1) {
                    global.refreshWindow()
                    if (global.refreshHistory) {
                        global.refreshHistory()
                    }
                }
                switch (res) {
                    case 0:
                        global.language = 'zh'
                        Taro.setStorageSync('language', 'zh')
                        i18n.changeLanguage('zh')
                        setLanguageType('中文')

                        break;
                    case 1:
                        global.language = 'en'
                        Taro.setStorageSync('language', 'en')
                        i18n.changeLanguage('en')
                        setLanguageType('English')
                        break;
                    case 2:
                        const isZh = Taro.getAppBaseInfo().language == 'zh_CN'
                        global.language = isZh ? 'zh' : 'en'
                        Taro.setStorageSync('language', 'wechat')
                        i18n.changeLanguage(isZh ? 'zh' : 'en')
                        setLanguageType('微信系统语言')
                        break;
                }
            }
        })
        // if (global.language == 'en') {
        //     global.language = 'zh'
        //     Taro.setStorageSync('language', 'zh')
        //     i18n.changeLanguage('zh')
        // }
        // else {
        //     global.language = 'en'
        //     Taro.setStorageSync('language', 'en')
        //     i18n.changeLanguage('en')
        // }
    }

    return <View style={{ color: '#fff', display: 'flex', flexDirection: 'column', flex: 1 }}>
        <View style={{ height: 20 }} />
        <Card>
            <View style={{
                display: 'flex', flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center',
                height: rpxToPx(128),
                boxSizing: 'border-box',
                paddingLeft: rpxToPx(40),
                paddingRight: rpxToPx(40),
                position: 'relative'

            }}>
                <Text className="h34" style={{ color: '#000' }}>{t('page.setting.version')}</Text>
                <Text className="h30" style={{ color: MainColorType.g01 }}>{process.env.TARO_ENV == 'weapp' ? WX_VERSION : APP_VERSION}</Text>
                <View className="border_footer_line" style={{ left: rpxToPx(40) }} />
            </View>
            <View
                onClick={changeLanguage}
                style={{
                    display: 'flex', flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    height: rpxToPx(128),
                    boxSizing: 'border-box',
                    paddingLeft: rpxToPx(40),
                    paddingRight: rpxToPx(40),
                    position: 'relative'

                }}>
                <Text className="h34" style={{ color: '#000' }}>{t('health.language')}</Text>
                <Text className="h30" style={{ color: MainColorType.g01 }}>{languageType}</Text>
            </View>
        </Card>
        {
            process.env.TARO_ENV == 'rn' && <View style={{ flex: 1 }} />
        }

        <Footer>
            <View>
                <View style={{ marginBottom: rpxToPx(24) }}>
                    <NewButton
                        type={NewButtonType.gray}
                        title={t('page.setting.logout')}
                        onClick={logoutF}
                        width={rpxToPx(400)}
                        height={rpxToPx(96)}
                    />
                </View>

                <View style={{ height: rpxToPx(72), display: 'flex' }}>
                    <NewButton
                        type={NewButtonType.link}
                        title={t('feature.common.modal.del')}
                        onClick={del}
                    />
                </View>

            </View>
        </Footer>
        {
            process.env.TARO_ENV == 'rn' && <View style={{ height: 50 }} />
        }
        {/* <Buttons title='退出登录' onClick={logoutF} btnStyle={{ width: 289, marginBottom: 30 }} /> */}

        {/* {
            user.test_user && <Buttons title='注销账号' onClick={clearF} btnStyle={{ width: 289, marginBottom: 30 }} />
        } */}


    </View>
}