import { Select, Modal, Input, Button,message } from "antd";
import React, { useEffect, useState } from "react";
import userIcon from "../../asstes/icon/user.png";
import copyIcon from "../../asstes/icon/copy.png";
import autorenewIcon from "../../asstes/icon/autorenew.png";
import axios from "axios";
import config from "../../config/config";
import { useDispatch } from "react-redux";
import { getUserInfo } from "../../states/global";

interface User {
    alias?: string;
    username?: string;
    defaultSchool?: string;
    apiKey?: string;
    userid?: string;
}
const Login: React.FC = () => {
    const dispatch = useDispatch();
    const [messageApi, contextHolder] = message.useMessage();
    const [isLogin, setIsLogin] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [cloudList, setCloudList] = useState([]);
    const [user, setUser] = useState<User>({});
    const [apiKey, setApiKey] = useState("");
    const [cloud, setCloud] = useState("");
    const iframUrl = config.iframeLogin;
    const cloudUrl = config.clouUrl;
    const cloudSrc = config.goCloud;

    useEffect(() => {
        window.addEventListener("message", (event: any) => {
            if (event.data.id === "loginVerify") {
                if (event.data.status === "logged") {
                    // console.log("loginVerify", event.data, cloudUrl);
                    setIsLogin(true);
                    setUser(event.data.data);
                    dispatch(getUserInfo(event.data.data));
                    getCloudList(event.data.data.apiKey, cloudUrl);
                }
            }
        });
    }, []);

    const getCloudList = async (apiKey: string, cloudUrl: string) => {
        // https://api.cocorobo.cn/iot/data/apikey/a038d10730b8618ca7f338be9013d7b2e425a03f8ffcffd03d9b37f88e099161/event/
        axios.get(`${cloudUrl}/iot/data/apikey/${apiKey}/event/`).then(res => {
            // console.log("getCloudList", res.data);
            if (res.data.length > 0) {
                setApiKey(res.data[0].eventAPIKey);
                setCloud(res.data[0].name);
                const list = res.data.map((item: any) => {
                    return {
                        label: item.name,
                        value: item.eventAPIKey,
                        key: item.url,
                    }
                });
                setCloudList(list);
                // console.log("cloudList", res.data[0].name);
            } else {
                setCloudList([]);
            }
        }).catch(err => {
            console.error("error", err);
        });
    }
    const handleLogin = () => {
        // Implement your login logic here
        setModalVisible(true);
    }

    const logout = () => {
        axios.defaults.withCredentials = true;
        axios.get(`${cloudUrl}/api/logout`).then(res=>{
            if(res.data === "logout"){
                setIsLogin(false);
            }
        })
    }

    // 复制apiKey
    const copyApiKey = () => {
        navigator.clipboard.writeText(apiKey).then(() => {
            messageApi.success('复制成功');
        }).catch((err) => {
            messageApi.error('复制失败');
        });
    }
    return (
        <div className="header-right-login">
            {contextHolder}
            {!isLogin ? <span className="login" onClick={() => handleLogin()}>
                <img src={userIcon} alt="user" className="header-right-icon" />
                Login
            </span> : <span className="login-success" onClick={() => handleLogin()}>
                <img src={userIcon} alt="user" className="header-right-icon" />
                {user.alias || user.username}
            </span>}
            <iframe src={iframUrl} title="Login" style={{ border: "none", display: "none" }}></iframe>
            <Modal style={{ top: 70, left: "calc(50% - 220px)" }} className="login-modal"
                title=""
                width={350}
                visible={modalVisible}
                footer={null}
                onCancel={()=>setModalVisible(false)}
            >
                {!isLogin ? <iframe src={iframUrl} title="Login"
                    width="100%" height="765px" scrolling="no" style={{ border: "none", marginTop: -380 }}></iframe> :
                    <div className="login-success-content">
                        <h2>{user.alias || user.username}</h2>
                        <div className="login-success-info">
                            <span>您的邮箱: </span>
                            <span>{user.username}</span>
                        </div>
                        <div className="login-success-info">
                            <span>您的学校: </span>
                            <span>{user.defaultSchool}</span>
                        </div>
                        <div className="login-success-info">
                            <span>云端项目: </span>
                            <img src={autorenewIcon} alt="autorenew" onClick={()=>getCloudList(user.apiKey ?? "", cloudUrl)}/>
                            <Select options={cloudList} style={{ width: "100%" }} defaultValue={cloud} onChange={(value) => setApiKey(value)}>

                            </Select>
                        </div>
                        <div className="login-success-info">
                            <span>API Key: </span>
                            <img src={copyIcon} alt="copy" onClick={() => copyApiKey()} />
                            <Input value={apiKey} readOnly style={{ width: "100%" }} />
                        </div>
                        <div className="login-success-info login-footer">
                            <a href={cloudSrc} target="_blink"><Button type="primary" onClick={() => setModalVisible(false)}>前往云端服务</Button></a>
                            <Button type="primary" onClick={() => logout()}>退出</Button>
                        </div>
                    </div>
                }

            </Modal>
        </div>
    );
};

export default Login;