import md5 from 'js-md5';

// 由于是跨域登录，需要手动设置并携带 Cookie
const setPHPSessionToCookie = (sessionID) => {
    if (sessionID) {
        // 使用 SameSite=None 和 secure 属性，在 tauri 环境会设置失败
        // document.cookie = `PHPSESSID=${sessionID}; max-age=604800; SameSite=None; secure; path=/`;
        document.cookie = `PHPSESSID=${sessionID}; max-age=604800; path=/`;
    }
}

const getPHPSessionFromCookie = () => {
    let PHPSESSID = '';
    const cookies = document.cookie.split('; ');
    cookies.forEach(cookie => {
        const [key, value] = cookie.split('=');
        if (key === 'PHPSESSID') {
            PHPSESSID = decodeURIComponent(value); // 解码特殊字符（如空格、%20）
        }
    });
    return PHPSESSID;
}

const delPHPSessionFromCookie = () => {
    document.cookie = `PHPSESSID=; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
}

const SignIn = (username, password, autoLogin) => {
    return new Promise((resolve, reject) => {
        fetch('https://myafei.cn/php/ajax.php', {
            method: 'POST',
            body: JSON.stringify({
                'func': 'login',
                'username': username,
                'is_email': /^[0-9a-zA-Z_-]{1,100}$/.test(username) ? false : true,
                'password': md5(password),
                'isRemember': autoLogin,
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                setPHPSessionToCookie(data.PHPSESSID);
                resolve(data);
            } else {
                reject(new Error(data.error));
            }
        }).catch(error => {
            reject(error);
        });
    })
}

const SignUp = (username, mail, password) => {
    return new Promise((resolve, reject) => {
        fetch('https://myafei.cn/php/ajax.php', {
            method: 'POST',
            body: JSON.stringify({
                'func': 'register',
                'username': username,
                'email': mail,
                'password': md5(password),
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                resolve(data);
            } else {
                reject(new Error(data.error));
            }
        }).catch(error => {
            reject(error);
        });
    });
}

const SendSignUpEmail = (userID) => {
    return new Promise((resolve, reject) => {
        fetch('https://myafei.cn/php/ajax.php', {
            method: 'POST',
            body: JSON.stringify({
                'func': 'resend_email',
                'id': userID,
                'path': '/',
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                resolve(data);
            } else if (data.status == -100) {
                reject(new Error('邮箱已被激活'));
            } else {
                reject(new Error(data.error));
            }
        }).catch(error => {
            reject(error);
        });
    });
}

const CheckLoginStatus = () => {
    return new Promise((resolve, reject) => {
        // 先从 cookie 中拿到 PHPSESSID
        const PHPSESSID = getPHPSessionFromCookie();
        fetch('https://myafei.cn/php/ajax.php?PHPSESSID=' + PHPSESSID, {
            method: 'POST',
            body: JSON.stringify({
                'func': 'is_login',
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                resolve(data);
            } else {
                // 未登录不抛出异常
            }
        }).catch(error => {
            reject(error);
        });
    });
}

const Logout = () => {
    return new Promise((resolve, reject) => {
        const PHPSESSID = getPHPSessionFromCookie();
        fetch('https://myafei.cn/php/ajax.php?PHPSESSID=' + PHPSESSID, {
            method: 'POST',
            body: JSON.stringify({
                'func': 'logout',
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                delPHPSessionFromCookie();
                resolve();
            } else {
                reject(new Error(data.error));
            }
        }).catch(error => {
            reject(error);
        });
    });
}

const SubmitArticle = (title, mdCode) => {
    return new Promise((resolve, reject) => {
        const PHPSESSID = getPHPSessionFromCookie();
        fetch('https://myafei.cn/php/ajax.php?PHPSESSID=' + PHPSESSID, {
            method: 'POST',
            body: JSON.stringify({
                'func': 'submit_article',
                'title': title,
                'mdCode': mdCode,
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                resolve(data);
            } else {
                reject(new Error(data.error));
            }
        }).catch(error => {
            reject(error);
        });
    });
}

const UpdateArticle = (id, title, mdCode) => {
    return new Promise((resolve, reject) => {
        const PHPSESSID = getPHPSessionFromCookie();
        let body = {
            'func': 'update_article',
            'id': id,
        }
        if (title !== null && title !== undefined) {
            body.title = title;
        }
        if (mdCode !== null && mdCode !== undefined) {
            body.mdCode = mdCode;
        }
        fetch('https://myafei.cn/php/ajax.php?PHPSESSID=' + PHPSESSID, {
            method: 'POST',
            body: JSON.stringify(body),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                resolve(data);
            } else {
                reject(new Error(data.error));
            }
        }).catch(error => {
            reject(error);
        });
    });
}

const GetSingleArticle = (id) => {
    return new Promise((resolve, reject) => {
        const PHPSESSID = getPHPSessionFromCookie();
        fetch('https://myafei.cn/php/ajax.php?PHPSESSID=' + PHPSESSID, {
            method: 'POST',
            body: JSON.stringify({
                'func': 'init_submit',
                'id': id,
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                resolve(data);
            } else {
                reject(new Error(data.error));
            }
        }).catch(error => {
            reject(error);
        });
    });
}

const GetUserArticle = (id, title, mdCode) => {
    return new Promise((resolve, reject) => {
        const PHPSESSID = getPHPSessionFromCookie();
        fetch('https://myafei.cn/php/ajax.php?PHPSESSID=' + PHPSESSID, {
            method: 'POST',
            body: JSON.stringify({
                'func': 'get_articles',
            }),
        }).then(response => {
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            return response.json();
        }).then(data => {
            if (data.status == 0) {
                resolve(data);
            } else {
                // 未登录不抛出异常
            }
        }).catch(error => {
            reject(error);
        });
    });
}

export {
    SignIn,
    SignUp,
    SendSignUpEmail,
    CheckLoginStatus,
    Logout,
    SubmitArticle,
    UpdateArticle,
    GetSingleArticle,
    GetUserArticle,
};