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 } from "@/context/themes/color";

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()

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

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

    }

    function chooseAvatar(e) {
        const { avatarUrl } = e.detail
        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 => {
                        console.log(rlt)
                        uploadAvatar(rsp.data.view_url)
                        // _this.changeAvatar(rsp.data.view_url);
                    },
                    fail: rlt => {
                        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'
            })


        })
    }

    return <View className="container">
        <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>
            </View>
        </View>


        <View onClick={editNickname}>
            <TableCell title={t('page.user_profile.nickname')} showArrow={true} showMarginBottom={true}>
                <Text style={{ opacity: 0.8 }}>{router.params.newuser == '1' ? (user.nickname == name ? '取个名字' : user.nickname) : user.nickname}</Text>
            </TableCell>
        </View>

        <Footer>
            <ChooseScenarioBtn disable={router.params.newuser == '1' && (user.avatar == header || user.nickname == name)} title='确定' onClick={() => {
                Taro.navigateBack()
            }} background={ColorType.fast} />
        </Footer>


    </View>
}