// const routerArray = [{
//     path: '/', name: '首页',
// }]
// const handler = {
//      JumpRouter, getToken, setToken, GetUserInfo
// }
var loginState = false;
var RouterLinkName = "routerLink";
document.addEventListener('DOMContentLoaded', function () {
    if (window.location.pathname === "/" || window.location.pathname === "") {
        console.log("6666668")
        sessionStorage.setItem(RouterLinkName, JSON.stringify([]))
    }
    RouterBarCreate()
})

//=======================链接跳转
function JumpRouter(url, name) {
    //获取当前路径和请求参数
    let path = window.location.href;
    if (path.indexOf(window.location.host) !== -1) {
        path = path.substring(path.indexOf(window.location.host) + window.location.host.length)
    }
    let title = name ? name : document.title;
    if (path === '' || path === "/") {
        sessionStorage.setItem(RouterLinkName, JSON.stringify([]))
    }
    //不存在 存储创建一个
    if (!sessionStorage.getItem(RouterLinkName)) {
        sessionStorage.setItem(RouterLinkName, JSON.stringify([path]))
    } else {
        //存在则添加
        let arr = JSON.parse(sessionStorage.getItem(RouterLinkName));
        arr[arr.length] = {title, url: path}
        sessionStorage.setItem(RouterLinkName, JSON.stringify(arr))
    }

    window.location.href = url;
}

function RouterBarJump(name, url) {
    let routerLink = JSON.parse(sessionStorage.getItem(RouterLinkName))
    let newArray = []
    if (!routerLink) {
        return
    }
    for (let i = 0; i < routerLink.length; i++) {
        if (routerLink[i].title === name) {
            break
        } else {
            newArray[i] = (routerLink[i])
        }
    }
    sessionStorage.setItem(RouterLinkName, JSON.stringify(newArray))

    window.location.href = url;
}

function RouterBarCreate() {

    let routerLink = JSON.parse(sessionStorage.getItem(RouterLinkName))
    let ulEle = document.getElementById("router-bar-list");
    if (!ulEle) {
        return
    }
    ulEle.children = []
    let rightArrowEle = document.createElement("li");
    rightArrowEle.innerText = ">"
    rightArrowEle.className = "router-bar-arrow"


    let ele = document.createElement("li");
    ele.innerText = '首页'
    ele.className = "router-bar-item"
    ele.addEventListener("click", function () {
        RouterBarJump('首页', "/")
    })
    ulEle.appendChild(ele)
    ulEle.appendChild(rightArrowEle)

    if (routerLink) {
        for (let i = 0; i < routerLink.length; i++) {
            if (routerLink[i].url==="/"){
                continue
            }
            let liEle = document.createElement("li");
            liEle.innerText = routerLink[i].title
            liEle.className = "router-bar-item"
            liEle.addEventListener("click", function () {
                RouterBarJump(routerLink[i].title, routerLink[i].url)
            })
            ulEle.appendChild(liEle)
            let rae = document.createElement("li");
            rae.innerText = ">"
            rae.className = "router-bar-arrow"
            ulEle.appendChild(rae)
        }
    }

    let nowEle = document.createElement("li")
    nowEle.innerText = document.title
    nowEle.className = "router-bar-text"
    ulEle.appendChild(nowEle)
}

function jumpClass(className) {
    // document.querySelector('.to-class' + className).scrollIntoView()
    // 获取元素的网页高度
    var height = document.querySelector('.to-class' + className).offsetTop;
    //这个80是导航栏的高度
    window.scrollTo(0, height - 80);


}

function getToken() {
    return localStorage.getItem("token");
}

function setToken(value) {
    localStorage.setItem("token", value);
    console.log("token set", getToken())
}

function GetUserInfo() {
    console.log("获取用户信息")
    fetch('/api/user/info', {
        method: 'GET', headers: {
            // 'Content-Type': 'application/json',
            "auth-sign": getToken()
        }, // body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(data => {
            if (data.code !== 200) {
                loginState = false;
                //头像修改
                document.getElementById("not-login").style.display = "black";
                document.getElementById("logged-in").style.display = "none";
                //用户名称
                document.getElementById("login-name").innerText = "登录";
            } else {
                //导航栏头像处理
                if (data.data.avatar) {
                    document.getElementById("not-login").style.display = "none";
                    let logged = document.getElementById("logged-in");
                    logged.style.display = "block"
                    logged.src = data.data.avatar;
                } else {
                    document.getElementById("not-login").style.display = "black";
                    document.getElementById("logged-in").style.display = "none";
                }
                // 导航栏名字问题
                document.getElementById("login-name").innerText = data.data.name;
                loginState = true;
            }
        })
        .catch((error) => {
            loginState = false;
            //头像修改
            document.getElementById("not-login").style.display = "black";
            document.getElementById("logged-in").style.display = "none";
            //用户名称
            document.getElementById("login-name").innerText = "登录";
            console.error('Error:', error);
            // alert("获取登录信息失败");
        });

}

//点击导航栏头像
function clickAvatar() {
    if (loginState) {
        //已经登录的，进入管理页面
        JumpRouter("/manage/info");
    } else {
        let loginBody = document.getElementById("login-body");
        let loginCenter = document.getElementById("login-center");
        let registerCenter = document.getElementById("register-center");
        loginBody.style.display = "";
        loginCenter.style.display = "";
        registerCenter.style.display = "none"
    }
}

//关闭登录框
function closeLoginBody() {
    console.log(6666666666)
    let loginBody = document.getElementById("login-body");
    let loginCenter = document.getElementById("login-center");
    let registerCenter = document.getElementById("register-center");
    loginBody.style.display = "none";
    loginCenter.style.display = "none";
    registerCenter.style.display = "none"
}

//打开登录框
function openLoginBody(type) {
    if (type === "register") {
        let loginBody = document.getElementById("login-body");
        let loginCenter = document.getElementById("login-center");
        let registerCenter = document.getElementById("register-center");
        loginBody.style.display = "";
        loginCenter.style.display = "none";
        registerCenter.style.display = ""
    } else if (type === "login") {
        let loginBody = document.getElementById("login-body");
        let loginCenter = document.getElementById("login-center");
        let registerCenter = document.getElementById("register-center");
        loginBody.style.display = "";
        loginCenter.style.display = "";
        registerCenter.style.display = "none"
    }
}

//登录
document.addEventListener('DOMContentLoaded', () => {
    const selectType = 'email';
    const phoneTab = document.getElementById('phone-tab');
    const emailTab = document.getElementById('email-tab');
    const wxTab = document.getElementById('wx-tab');
    const phoneSection = document.getElementById('phone-section');
    const emailSection = document.getElementById('email-section');
    const wxSection = document.getElementById('wx-section');
    const selectBar = document.getElementById('select-bar');

    const sendCodeBtn = document.getElementById('send-code-btn');
    const phoneLoginBtn = document.getElementById('phone-login-btn');

    const emailLoginBtn = document.getElementById('email-login-btn');
    const refreshWxCode = document.getElementById('refresh-wx-code');

    function setType(type) {
        phoneSection.style.display = 'none';
        emailSection.style.display = 'none';
        wxSection.style.display = 'none';

        if (type === 'phone') {
            phoneSection.style.display = 'block';

            selectBar.style.marginLeft = '-200px';
        } else if (type === 'email') {
            emailSection.style.display = 'block';
            selectBar.style.marginLeft = '0';
        } else if (type === 'wx') {
            wxSection.style.display = 'block';
            selectBar.style.marginLeft = '200px';
        }
    }

    phoneTab.addEventListener('click', () => setType('phone'));
    emailTab.addEventListener('click', () => setType('email'));
    wxTab.addEventListener('click', () => setType('wx'));

    function showTip(msg) {
        alert(msg);
    }

    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(String(email).toLowerCase());
    }

    function validatePhone(phone) {
        const re = /^1[3-9]\d{9}$/;
        return re.test(String(phone));
    }

    function validateCode(code) {
        const re = /^\d{6}$/;
        return re.test(String(code));
    }


    sendCodeBtn.addEventListener('click', () => {
        const phone = document.getElementById('phone-input').value;
        if (!validatePhone(phone)) {
            showTip('手机号格式错误');
            return;
        }
        fetch("/api/user/loginCode", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                phone: phone
            })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    console.log('Verification code sent successfully:', data);
                } else {
                    console.error('Failed to send verification code:', data.message);
                }
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
            });
        alert('验证码已发送');


    });

    phoneLoginBtn.addEventListener('click', () => {
        const phone = document.getElementById('phone-input').value;
        const code = document.getElementById('phone-code-input').value;
        if (!validatePhone(phone)) {
            showTip('手机号格式错误');
            return;
        }
        if (!validateCode(code)) {
            showTip('验证码错误');
            return;
        }
        fetch("/api/user/login", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: phone,
                password: code,
                type: "phone"
            })
        }).then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        }).then(data => {
            if (data.code === 200) {
                setToken(data.data.token)
                //刷新页面
                window.location.reload();
            } else {
                alert(data.msg)
            }
        }).catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });


        alert('手机号登录成功');
    });

    emailLoginBtn.addEventListener('click', () => {
        const email = document.getElementById('email-input').value;
        const password = document.getElementById('email-password-input').value;
        if (!validateEmail(email)) {
            showTip('邮箱格式错误');
            return;
        }
        if (password.length < 6) {
            showTip('密码过短');
            return;
        }
        fetch("/api/user/login", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: email,
                password: password,
                type: "email"
            })
        }).then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        }).then(data => {
            if (data.code === 200) {
                setToken(data.data.token)
                //刷新页面
                window.location.reload();
            } else {
                alert(data.msg)
            }
        }).catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });
    });

    refreshWxCode.addEventListener('click', () => {
        console.log('二维码已刷新');
    });
    setType(selectType);
});
//注册
document.addEventListener('DOMContentLoaded', () => {
    const username = document.getElementById('username');
    const password = document.getElementById('password');
    const requirePassword = document.getElementById('requirePassword');
    const phone = document.getElementById('phone');
    const code = document.getElementById('code');
    const sendCodeBtn = document.getElementById('send-register-code');
    const registerBtn = document.getElementById('register-btn');

    let awaitCode = 0;

    function showTip(msg) {
        alert(msg);
    }

    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(String(email).toLowerCase());
    }

    function validatePhone(phone) {
        const re = /^1[3-9]\d{9}$/;
        return re.test(String(phone));
    }

    function validatePassword(password) {
        const re = /^[a-zA-Z0-9,./<>?;'\\:"|\[\]{}~!@#$%^&*()_+=-]{6,32}$/;
        return re.test(String(password));
    }

    function validateCode(code) {
        const re = /^[0-9]{6}$/;
        return re.test(String(code));
    }

    sendCodeBtn.addEventListener('click', () => {
        if (awaitCode === 0) {
            const phoneVal = phone.value;
            if (!validatePhone(phoneVal)) {
                showTip('手机号格式错误');
                return;
            }
            alert('验证码已发送');
            awaitCode = 5;
            const interval = setInterval(() => {
                awaitCode--;
                sendCodeBtn.textContent = awaitCode > 0 ? `${awaitCode}s` : '发送验证码';
                if (awaitCode === 0) {
                    clearInterval(interval);
                }
            }, 1000);
        }
    });

    registerBtn.addEventListener('click', () => {
        const usernameVal = username.value;
        const passwordVal = password.value;
        const requirePasswordVal = requirePassword.value;
        const phoneVal = phone.value;
        const codeVal = code.value;

        if (!validateEmail(usernameVal)) {
            showTip('邮箱格式错误');
            return;
        }
        if (!validatePassword(passwordVal)) {
            showTip('密码格式错误');
            return;
        }
        if (passwordVal !== requirePasswordVal) {
            showTip('两次密码不一致');
            return;
        }
        if (!validatePhone(phoneVal)) {
            showTip('手机号格式错误');
            return;
        }
        if (!validateCode(codeVal)) {
            showTip('验证码错误');
            return;
        }

        alert('注册成功');
        // Here you can make an API request to register the user
    });
});
