$(function() {
    validateKickout();
    validateRule();
    $('.imgcode').click(function() {
        var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
        $(".imgcode").attr("src", url);
    });
    initEmbedLoginBridge();
});

/** 是否为 HIS iframe 嵌入登录（URL embed=1，或实际处于 iframe 中） */
function isEmbedMode() {
    if (getParam("embed") === "1") return true;
    if (document.documentElement.className.indexOf("his-ipcc-embed") >= 0) return true;
    try { return window.self !== window.top; } catch (e) { return true; }
}

/** 嵌入登录成功后进工作台（跳过 index 外壳） */
function getLoginSuccessUrl() {
    if (isEmbedMode()) {
        return ctx + "system/main?embed=1";
    }
    return ctx + "index";
}

function login(extra) {
    extra = extra || {};
    var username = $.common.trim(extra.username != null ? extra.username : $("input[name='username']").val());
    var password = $.common.trim(extra.password != null ? extra.password : $("input[name='password']").val());
    var extNum = $.common.trim(extra.extNum != null ? extra.extNum : $("input[name='extNum']").val());
    var groupId = $.common.trim(extra.groupId != null ? extra.groupId : ($("select[name='groupId']").val() || "1"));
    var myGateway = "";
    if (extra.myGateway != null) {
        myGateway = $.common.trim(String(extra.myGateway));
    } else if ($("input[name='useGateway']:checked").val() === "1") {
        myGateway = $.common.trim($("#gatewaySelect").val() || $("input[name='myGateway']").val() || "");
    } else {
        myGateway = $.common.trim(getParam("myGateway") || "");
    }
    $("input[name='myGateway']").val(myGateway);
    var validateCode = $("input[name='validateCode']").val();
    var rememberMe = $("input[name='rememberme']").is(':checked');
    if ($.common.isEmpty(validateCode) && captchaEnabled) {
        $.modal.msg("请输入验证码");
        postEmbedToParent("HIS_IPCC_LOGIN_RESULT", { ok: false, msg: "请输入验证码" });
        return false;
    }
    if ($("input[name='useGateway']:checked").val() === "1" && $.common.isEmpty(myGateway) && !isEmbedMode()) {
        $.modal.msg("请选择外呼网关");
        return false;
    }
    $.ajax({
        type: "post",
        url: ctx + "login",
        data: {
            "username": username,
            "password": password,
            "extNum": extNum,
            "validateCode": validateCode,
            "rememberMe": rememberMe,
            "groupId": groupId,
            "myGateway": myGateway,
            "embed": isEmbedMode() ? "1" : ""
        },
        xhrFields: { withCredentials: true },
        beforeSend: function () {
            if (!isEmbedMode()) {
                $.modal.loading($("#btnSubmit").data("loading"));
            }
        },
        success: function(r) {
            if (r.code == web_status.SUCCESS) {
                var nextUrl = getLoginSuccessUrl();
                // 先通知父页，再由【本 iframe 内】同源跳转工作台。
                // 切勿让父页改 iframe.src（跨源会导致会话 Cookie 丢失 → 踢回登录死循环）
                try { sessionStorage.setItem("his_ipcc_login_jump", "1"); } catch (e) {}
                postEmbedToParent("HIS_IPCC_LOGIN_RESULT", { ok: true, nextUrl: nextUrl });
                if (isEmbedMode()) {
                    window.location.replace(nextUrl);
                } else {
                    window.location.href = nextUrl;
                }
            } else {
                window.__hisIpccLoginJumping = false;
                try { sessionStorage.removeItem("his_ipcc_login_jump"); } catch (e) {}
                $('.imgcode').click();
                $(".code").val("");
                if (!isEmbedMode()) {
                    $.modal.msg(r.msg);
                }
                postEmbedToParent("HIS_IPCC_LOGIN_RESULT", { ok: false, msg: r.msg || "登录失败" });
            }
            if (!isEmbedMode()) {
                $.modal.closeLoading();
            }
        },
        error: function(xhr, status, error) {
            window.__hisIpccLoginJumping = false;
            try { sessionStorage.removeItem("his_ipcc_login_jump"); } catch (e) {}
            if (!isEmbedMode()) {
                $.modal.closeLoading();
                $.modal.msg(error || "登录异常");
            }
            postEmbedToParent("HIS_IPCC_LOGIN_RESULT", { ok: false, msg: error || "登录异常" });
        }
    });
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            username: { required: true },
            password: { required: true }
        },
        messages: {
            username: { required: icon + "请输入您的用户名" },
            password: { required: icon + "请输入您的密码" }
        },
        submitHandler: function() {
            login();
        }
    });
}

function validateKickout() {
    if (getParam("kickout") == 1) {
        if (isEmbedMode()) {
            postEmbedToParent("HIS_IPCC_LOGIN_RESULT", { ok: false, msg: "您已在别处登录" });
            return;
        }
        layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
            icon: 0,
            title: "系统提示"
        }, function(index) {
            layer.close(index);
            if (top != self) {
                top.location = self.location;
            } else {
                var url = location.search;
                if (url) {
                    var oldUrl = window.location.href;
                    var newUrl = oldUrl.substring(0, oldUrl.indexOf('?'));
                    self.location = newUrl;
                }
            }
        });
    }
}

function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

/** 与 main.html / HIS 约定：{ channel, type, payload } */
function postEmbedToParent(type, payload) {
    if (!isEmbedMode() || !window.parent || window.parent === window) return;
    try {
        window.parent.postMessage({
            channel: "HIS_IPCC_EMBED",
            type: type,
            payload: payload || {}
        }, "*");
    } catch (e) {}
}

function bindEmbedLoginMessage() {
    if (window.__hisIpccLoginBridgeBound) return;
    window.__hisIpccLoginBridgeBound = true;
    window.addEventListener("message", function(event) {
        var data = event.data;
        if (!data || data.channel !== "HIS_IPCC_EMBED") return;
        if (data.type === "HIS_IPCC_LOGIN") {
            var p = data.payload || {};
            if (!p.username || !p.password || !p.extNum) {
                postEmbedToParent("HIS_IPCC_LOGIN_RESULT", { ok: false, msg: "登录参数不完整" });
                return;
            }
            // 正在跳转工作台时忽略重复 LOGIN，避免死循环
            if (window.__hisIpccLoginJumping) return;
            window.__hisIpccLoginJumping = true;
            login({
                username: p.username,
                password: p.password,
                extNum: String(p.extNum),
                groupId: p.groupId || "1",
                myGateway: p.myGateway != null ? String(p.myGateway) : ""
            });
            // 登录失败时允许再次尝试
            setTimeout(function () {
                if (/\/login/i.test(window.location.pathname || "")) {
                    window.__hisIpccLoginJumping = false;
                }
            }, 3000);
        }
    });
}

function initEmbedLoginBridge() {
    if (!isEmbedMode()) return;
    bindEmbedLoginMessage();

    // 登录成功后又回到登录页：真会话丢失（Cookie 未带上）
    var bounced = false;
    try { bounced = sessionStorage.getItem("his_ipcc_login_jump") === "1"; } catch (e) {}
    if (bounced) {
        try { sessionStorage.removeItem("his_ipcc_login_jump"); } catch (e) {}
        window.__hisIpccLoginJumping = false;
        postEmbedToParent("ERROR", {
            msg: "工作台会话未带上（Cookie 丢失或被拒），请检查同主机:8899 反代是否剥离 Domain/Secure",
            code: "SESSION_COOKIE_LOST",
            type: "SESSION_COOKIE_LOST"
        });
        postEmbedToParent("HIS_IPCC_LOGIN_RESULT", {
            ok: false,
            msg: "工作台会话未带上（Cookie 丢失或被拒）",
            code: "SESSION_COOKIE_LOST"
        });
        // 延迟 READY，避免立刻触发父页「登录回弹」误判；供整轮重登使用
        setTimeout(function () {
            postEmbedToParent("HIS_IPCC_LOGIN_READY", {});
        }, 1500);
        return;
    }

    // 正常进入登录页：工作台就绪后清跳转标记
    try { sessionStorage.removeItem("his_ipcc_login_jump"); } catch (e) {}
    postEmbedToParent("HIS_IPCC_LOGIN_READY", {});
}
