// 处理时间
export const handleDate = (dateTimeStamp = new Date()) => {
    dateTimeStamp = dateTimeStamp ? dateTimeStamp : null;
    var timestamp = new Date(dateTimeStamp);
    timestamp = timestamp.getTime();
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var now = new Date().getTime();
    var diffValue = now - timestamp;
    var result;
    if (diffValue < 0) return;

    var dayC = diffValue / day;
    var hourC = diffValue / (hour + 1);
    var minC = diffValue / minute;
    if (dayC >= 7) {
        let date = new Date(timestamp);
        let Y = date.getFullYear() + "-";
        let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
        let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
        let h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
        let m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        result = "" + Y + M + D + " " + h + m;
    } else if (dayC >= 1) result = "" + Math.round(dayC) + "天前";
    else if (hourC >= 1) result = "" + Math.round(hourC) + "小时前";
    else if (minC >= 1) result = "" + Math.round(minC) + "分钟前";
    else result = "刚刚";

    return result;
};

export const timestampToDate = (timestamp) => {
    var date = new Date(timestamp);
    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2); // Months are zero based. Add leading 0.
    var day = ("0" + date.getDate()).slice(-2); // Add leading 0.
    return `${year}-${month}-${day}`;
};

// isblank 是否需要 新标签页 默认是新标签页
export const goToURL = (url, isblank = true) => {
    if (typeof document !== "object") return;

    let aTab = document.createElement("a");
    document.body.appendChild(aTab);
    aTab.setAttribute("href", url);
    if (isblank) aTab.setAttribute("target", "_blank");
    aTab.click();
};

export const numberToEnclosed = (index) => {
    let obj = {
        1: "①",
        2: "②",
        3: "③",
        4: "④",
        5: "⑤",
    };
    return obj[index];
};

export const managerHide = (token, state, type = "offer") => {
    return new Promise((resolve, reject) => {
        const obj = {
            offer: "Offer",
            offer_summary: "总结",
            interviewexperience: "面经",
            thread: "帖子",
            question: "帖子",
            vote: "投票",
        };

        const isConfirmed = confirm(`确定要${state == 0 ? "隐藏" : "显示"}该${obj[type]}吗？`);
        if (isConfirmed) {
            topicHideHttp({
                token,
                hidden: Number(state !== 1),
            }).then((res) => {
                const data = res.data;
                creationAlertBox("success", res.message || "");
                resolve(data.hidden);
            });
        }
    });
};

// 推荐
export const managerRecommend = (token, state) => {
    return new Promise((resolve, reject) => {
        const post = () => {
            topicRecommendHttp({
                token,
                recommend: state == 1 ? 0 : 1,
            }).then((res) => {
                const data = res.data;
                creationAlertBox("success", res.message || "");
                resolve(data.recommend);
            });
        };

        if (state == 1) {
            const isConfirmed = confirm(`确定要取消推荐吗？`);
            if (isConfirmed) post();
            else resolve(state);
        } else post();
    });
};

// 精华
export const managerEssence = (token, state) => {
    return new Promise((resolve, reject) => {
        const post = () => {
            topicEssenceHttp({
                token,
                best: state == 1 ? 0 : 1,
            }).then((res) => {
                const data = res.data;
                creationAlertBox("success", res.message || "");
                resolve(data.best);
            });
        };

        if (state == 1) {
            const isConfirmed = confirm(`确定要取消精华吗？`);
            if (isConfirmed) post();
            else resolve(state);
        } else post();
    });
};

// 删除
export const managerDelete = (token) => {
    return new Promise((resolve, reject) => {
        const post = () => {
            topicDeleteHttp({
                token,
            }).then((res) => {
                creationAlertBox("success", res.message || "");
                resolve();
            });
        };

        const isConfirmed = confirm(`确定要删除吗？`);
        if (!isConfirmed) reject();
        else post();
    });
};

export const strtimeago = (dateStr, type = 1) => {
    dateStr = dateStr + ""; // 反之传入的不是字符串
    dateStr = dateStr.replaceAll("-", "/"); // 修改格式
    var minute = 1000 * 60; // 把分，时，天，周，半个月，一个月用毫秒表示
    var hour = minute * 60;
    var day = hour * 24;
    var now = new Date().getTime(); // 获取当前时间毫秒
    let objectTime = new Date(dateStr).getTime();
    var diffValue = now - objectTime; // 时间差
    if (diffValue < 0) return "刚刚";

    var minC = diffValue / minute; // 计算时间差的分，时，天，周，月
    var hourC = diffValue / hour;
    var dayC = diffValue / day;

    const diffInMilliseconds = now - objectTime;
    const diffInYears = diffInMilliseconds / (1000 * 60 * 60 * 24 * 365);
    const diffInMonths = diffInYears * 12;

    let result = "";
    if (dayC >= 7) {
        var datetime = new Date(dateStr);
        var Nyear = datetime.getFullYear();
        var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var Nmin = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        if (type == 4) {
            if (new Date().getFullYear() !== Nyear) result = `${Nyear}年${Nmonth}月${Ndate}日`;
            else result = `${Nmonth}月${Ndate}日 ${Nhour}:${Nmin}`;
        }
        if (type == 1) result = Nyear + "-" + Nmonth + "-" + Ndate;
        if (type == 2) {
            result = `${Nmonth}月${Ndate}日 ${Nhour}:${Nmin}`;
            if (new Date().getFullYear() !== Nyear) result = `${Nyear}年${result}`;
        }
        if (type == 3) {
            if (diffInYears >= 1) result = Math.floor(diffInYears) + "年前";
            else if (diffInMonths >= 1) result = Math.floor(diffInMonths) + "个月前";
            else result = parseInt(dayC) + "天前";
        }
    } else if (dayC >= 1) result = parseInt(dayC) + "天前";
    else if (hourC >= 1 && hourC <= 24) result = parseInt(hourC) + "小时前";
    else if (minC >= 1 && minC <= 60) result = parseInt(minC) + "分钟前";
    else result = "刚刚";

    return result;
};
