import Buttons from "@/components/basic/Buttons";
import { clear, logout, update } from "@/services/user";
import { View, Text, Image, Button } from "@tarojs/components";
import { useDispatch, useSelector } from "react-redux";
import './ProfileSetting.scss'
import Box from "@/components/layout/Box";
import Taro, { useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { baseUrl } from "@/services/http/api";
import { updateSuccess } from "@/store/user";
import TableCell from "@/components/layout/TableCell";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import Footer from "@/components/layout/Footer";
import { ChooseScenarioBtn } from "@/features/common/SpecBtns";
import { ColorType, MainColorType } from "@/context/themes/color";
import { checkAuthorized } from "@/utils/check_authorized";
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 dispatch = useDispatch();
    const router = useRouter();
    const user = useSelector((state: any) => state.user);
    const [name, setName] = useState(user.nickname)
    const [header, setHeader] = useState(user.avatar)
    const { t } = useTranslation()

    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

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

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

    function editNickname() {
        if (router.params.newuser == '1') {
            jumpPage('/_account/pages/EditPage?name=' + (name == user.nickname ? '' : user.nickname), 'EditPage', navigation, {
                name: name == user.nickname ? '' : user.nickname
            })
        }
        else {
            jumpPage('/_account/pages/EditPage?name=' + user.nickname, 'EditPage', navigation, {
                name: user.nickname
            })
        }

    }

    function choose() {
        if (process.env.TARO_ENV == 'rn') {
            Taro.chooseImage({
                count: 1, // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
                success: function (res) {
                    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                    var tempFilePaths = res.tempFilePaths
                    console.log(tempFilePaths)
                    operate(tempFilePaths[0])
                    checkAuthorized()
                },
                fail(res) {
                    checkAuthorized()
                },
            })
        }
    }

    function chooseAvatar(e) {
        const { avatarUrl } = e.detail
        operate(avatarUrl)
    }

    function operate(avatarUrl) {
        var dot = avatarUrl.lastIndexOf('.')
        var fileExt = dot > 0 ? avatarUrl.substring(dot) : ''
        // console.log(avatarUrl)
        Taro.request({
            method: 'GET',
            url: `${baseUrl}/api/thirdparty/aliyun/oss-form-upload`,
            header: {
                'Authorization': 'bearer ' + global.token
            },
            data: {
                type: 'AVATAR',
                file_ext: fileExt
            },
            success: (rsp) => {
                debugger
                Taro.uploadFile({
                    url: rsp.data.upload_url,
                    filePath: avatarUrl,
                    name: 'file',
                    formData: rsp.data.fields,
                    success: rlt => {
                        debugger
                        console.log(rlt)
                        uploadAvatar(rsp.data.view_url)
                        // _this.changeAvatar(rsp.data.view_url);
                    },
                    fail: rlt => {
                        debugger
                        Taro.showModal({
                            content: rlt.errMsg
                        })
                    }
                })
            }
        })
    }

    function uploadAvatar(url) {
        update({ avatar: url }).then(res => {
            dispatch(updateSuccess({ avatar: url }));
            Taro.showToast({
                title: t('feature.common.toast.update_success'),
                icon: 'none'
            })
        })
    }

    function tapDone() {
        if (process.env.TARO_ENV == 'weapp') {
            // Taro.navigateBack()
            // console.log('profile setting navi back')
            if (router.params.newuser == '1'){
                // jumpPage('')
                Taro.redirectTo({
                    url:'/_health/pages/guide_begin'
                })
            }
            else {
                Taro.navigateBack()
            }
        }
        else {
            navigation.goBack()
        }
    }

    return <View className="container" style={{ flex: 1 }}>
        <View className="avatar_row">
            <View className="avatar_bg">

                {
                    router.params.newuser == '1' && user.avatar == header ?
                        <Image src={require('@assets/images/avatar_empty.png')} className="avatar" mode="aspectFill" /> :
                        <Image src={user.avatar} className="avatar" mode="aspectFill" />
                }
                <View className="camera_bg">
                    <Image className="camera" src={require('@assets/images/camera.png')} />
                </View>
                <Button className="btn" openType="chooseAvatar" onChooseAvatar={chooseAvatar} ></Button>
                {
                    process.env.TARO_ENV == 'rn' && <View style={{ opacity: 0, position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} onClick={choose} />
                }
            </View>
        </View>



        <View onClick={editNickname}>
            <TableCell onClick={editNickname} title={t('page.user_profile.nickname')} showArrow={true} showMarginBottom={true}>
                <Text style={{ opacity: 0.8, color: MainColorType.g01 }}>{router.params.newuser == '1' ? (user.nickname == name ? t('health.enter_my_name') : user.nickname) : user.nickname}</Text>
            </TableCell>
        </View>
        <View style={{ flex: 1 }} />

        <View className="main_footer">
            <NewButton
                color={MainColorType.blue}
                type={NewButtonType.fill}
                title={t('feature.common.picker_confirm_btn')}
                width={rpxToPx(646)}
                height={rpxToPx(96)}
                disable={router.params.newuser == '1' && (user.avatar == header || user.nickname == name)}
                bold={true}
                onClick={() => tapDone()} />
        </View>

        {/* <Footer>
            <ChooseScenarioBtn disable={router.params.newuser == '1' && (user.avatar == header || user.nickname == name)} title={t('feature.common.picker_confirm_btn')} onClick={() => {
                if (process.env.TARO_ENV == 'weapp') {
                    Taro.navigateBack()
                    console.log('profile setting navi back')
                }
                else {
                    navigation.goBack()
                }
            }} background={ColorType.fast} />
        </Footer>
        <View style={{ height: 40 }} /> */}


    </View>
}