import { View, Image, Input, Swiper, SwiperItem } from "@tarojs/components";
import "./index.less";
import { Button, Popup, Field, Flex } from "@taroify/core";
import { useState } from "react";
import icon from "../../../assets/icon/icon.png";
import bgFingerpost from "@/assets/bg/bg-fingerpost.png"
import Taro from "@tarojs/taro";
import services from "@/services";
import useGlobalStore from "@/store";
import api from "@/services/core/api";
const defaultAvatarUrl =
    "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";

const Login = () => {
    const [open, setOpen] = useState(false);
    const [avatarUrl, setAvatarUrl] = useState<string>();
    const { userInfo, updateUserInfo, queryAuthenticationInfo } =
        useGlobalStore();

    const [nickName, setNickname] = useState("");
    // console.log(userInfo);
    const getRealtimePhoneNumber = (e: any) => {
        services.login
            .login(e.detail.code)
            .then((res) => {
                Taro.setStorageSync("token", res.data.access_token);

                if (res.code === 200) {
                    if (res.data.user_info.nickname !== null) {
                        Taro.showToast({
                            title: "登录成功",
                        });
                        updateUserInfo();
                        queryAuthenticationInfo();
                    } else {
                        setOpen(true);
                    }
                }
            })
            .catch((e) => {
                console.log(e);
                Taro.showToast({
                    title: "登录失败",
                });
            });
    };

    const onChooseAvatar = (e) => {
        const { avatarUrl } = e.detail;
        setAvatarUrl(avatarUrl);
    };

    const onSetInfo = () => {
        if (!avatarUrl || avatarUrl?.length == 0) {
            Taro.showToast({
                title: "请上传头像",
                icon: "error",
            });
            return;
        }
        if (nickName.length === 0) {
            Taro.showToast({
                title: "请输入昵称",
                icon: "error",
            });
            return;
        }

        Taro.uploadFile({
            url: api.uploadUrl, //仅为示例，非真实的接口地址
            filePath: avatarUrl,
            name: "file",
            success(res) {
                if (res.statusCode === 200) {
                    const data = JSON.parse(res.data);
                    services.login
                        .updateUserInfo({
                            avatar: data.data,
                            nickname: nickName,
                        })
                        .then(() => {
                            setTimeout(() => {
                                updateUserInfo();

                                setOpen(false);
                            }, 100);
                        });
                }
            },
        });
    };

    const onclickAction = () => {
        Taro.navigateTo({
            url: "/pages/User/index",
        });
    };
    console.log(nickName);
    const toUserFingerpost = () => {
        Taro.navigateTo({
            url: '/pages/userFingerpost/userFingerpost'
        })
    }

    return (<>
        <Swiper autoplay>
            <SwiperItem className="swiperItem">
                <View className="topView">
                    <View className="title">
                        {userInfo ? (
                            <Flex align="center" gutter={12}>
                                <View>{userInfo?.nickname}</View>
                                <Image src={icon} className="storeIcon"></Image>
                            </Flex>
                        ) : (
                            "市民登录，商户认证"
                        )}
                    </View>
                    <View>
                        {userInfo ? (
                            <Button className="loginBtn" variant="text" onClick={onclickAction}>
                                个人中心
                            </Button>
                        ) : (
                            <Button
                                variant="text"
                                className="loginBtn"
                                open-type="getPhoneNumber"
                                onGetPhoneNumber={getRealtimePhoneNumber}
                            >
                                登录
                            </Button>
                        )}
                    </View>
                </View>
            </SwiperItem>
            <SwiperItem className="swiperItem">
                <Image style={{ width: '100%', height: '100%' }} src={bgFingerpost} onClick={toUserFingerpost} />
            </SwiperItem>
        </Swiper>

        <Popup
            open={open}
            rounded
            onClose={() => {
                setOpen(false);
                Taro.removeStorageSync("token");
            }}
            placement="bottom"
            style={{ height: "50%" }}
        >
            <View className="login-content">
                <View className="login-title">填写基本信息</View>
                <View style={{ fontSize: 12, marginBottom: 24 }}>
                    初次登陆，需要设置基本信息以完成注册
                </View>
                <Button
                    className="avatar-wrapper"
                    open-type="chooseAvatar"
                    variant="text"
                    onChooseAvatar={onChooseAvatar}
                >
                    <Image
                        className="avatar"
                        src={
                            avatarUrl && avatarUrl?.length > 0
                                ? avatarUrl
                                : defaultAvatarUrl
                        }
                    ></Image>
                </Button>

                <Field label="昵称">
                    <Input
                        type="nickname"
                        className="weui-input"
                        placeholder="请输入昵称"
                        holdKeyboard
                        value={nickName}
                        onInput={(e) => {
                            setNickname(e.detail.value);
                        }}
                    />
                </Field>

                <Button
                    shape="round"
                    style={{ marginTop: 24 }}
                    block
                    color="primary"
                    onClick={onSetInfo}
                >
                    完成注册
                </Button>
            </View>
        </Popup>
    </>
    );
};

export default Login;
