var selectId; // �쒗뭹 �꾩씠��
var selectName; // �쒗뭹 �대쫫
var selected_alm_server_id;
var selected_alm_server_name;
var alm_server_list = {};
var req_state_category_list = {};

////////////////////////////////////////////////////////////////////////////////////////
//Document Ready
////////////////////////////////////////////////////////////////////////////////////////
function execDocReady() {
    let pluginGroups = [
        [
            "../reference/jquery-plugins/select2-4.0.2/dist/css/select2_lightblue4.css",
            "../reference/jquery-plugins/select2-4.0.2/dist/js/select2.min.js",
            "../reference/lightblue4/docs/lib/slimScroll/jquery.slimscroll.min.js",
            "../reference/lightblue4/docs/lib/widgster/widgster.js",
            "../reference/jquery-plugins/timerStyles.js"
        ],
        [
            "../reference/jquery-plugins/jstree-v.pre1.0/_lib/jquery.cookie.js",
            "../reference/jquery-plugins/jstree-v.pre1.0/_lib/jquery.hotkeys.js",
            "../reference/jquery-plugins/jstree-v.pre1.0/jquery.jstree.js",
            "../reference/gojs/go-debug.js",
            "../arms/js/mapping/gojs_setup.js"
        ]
    ];

    loadPluginGroupsParallelAndSequential(pluginGroups)
        .then(function () {
            //�ъ씠�� 硫붾돱 泥섎━
            $(".widget").widgster();
            setSideMenu("sidebar_menu_jira", "sidebar_menu_state_mapping");

            //coming soon
            $("#count-down").TimeCircles(
                {
                    circle_bg_color: "#f8f8f8",
                    use_background: true,
                    bg_width: .2,
                    fg_width: 0.013,
                    time: {
                        Days: { color: "#f8f8f8" },
                        Hours: { color: "#f8f8f8" },
                        Minutes: { color: "#f8f8f8" },
                        Seconds: { color: "#f8f8f8" }
                    }
                }
            );

            //ALM �쒕쾭 ���됲듃 諛뺤뒪 �대땲�쒖뿉�댄꽣
            make_alm_server_select_box();
            gojs.init();

            save_req_state_btn_click();
            update_req_state_btn_click();
            delete_req_state_btn_click();
            preset_btn_click();
            // --- �먮뵒�� �ㅼ젙 --- //

            var waitCKEDITOR = setInterval(function () {
                try {
                    if (window.CKEDITOR) {
                        if (window.CKEDITOR.status === "loaded") {
                            CKEDITOR.replace("popup_view_state_description_editor", { skin: "office2013" });
                            clearInterval(waitCKEDITOR);
                        }
                    }
                } catch (err) {
                    console.log("CKEDITOR 濡쒕뱶媛� �꾨즺�섏� �딆븘�� 珥덇린�� �ъ떆�� 以�...");
                }
            }, 313 /*milli*/);

            $("#text").on("input", function () {
                var searchString = $(this).val();
                $("#alm_server_tree").jstree("search", searchString);
            });

            init_data_load();
        })
        .catch(function (e) {
            console.error("�뚮윭洹몄씤 濡쒕뱶 以� �ㅻ쪟 諛쒖깮");
            console.error(e);
        });
}

///////////////////////
// ALM �쒕쾭 ���됲듃 諛뺤뒪
//////////////////////
function make_alm_server_select_box() {
    //�쒗뭹 �쒕퉬�� ���됲듃 諛뺤뒪 �대땲�쒖뿉�댄꽣
    $(".chzn-select").each(function() {
        $(this).select2($(this).data());
    });

    //ALM �쒕쾭 ���됲듃 諛뺤뒪 �곗씠�� 諛붿씤��
    $.ajax({
        url: "/auth-user/api/arms/jiraServerPure/getNodesWithoutRoot.do",
        type: "GET",
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        progress: true,
        statusCode: {
            200: function(data) {
                console.log(data.result);
                //////////////////////////////////////////////////////////
                for (var k in data.result) {
                    var obj = data.result[k];
                    alm_server_list[obj.c_id] = obj;
                    var newOption = new Option(obj.c_title, obj.c_id, false, false);
                    $("#selected_alm_server").append(newOption).trigger("change");
                }

                jSuccess("ALM �쒕쾭 議고쉶媛� �꾨즺 �섏뿀�듬땲��.");
            }
        },
        error: function (e) {
            jError("ALM �쒕쾭 議고쉶 以� �먮윭媛� 諛쒖깮�덉뒿�덈떎. :: " + e);
        }
    });

    $("#selected_alm_server").on("select2:open", function() {
        //�щ┝�ㅽ겕濡�
        makeSlimScroll(".select2-results__options");
    });

    // --- select2 ( �쒗뭹(�쒕퉬��) 寃��� 諛� �좏깮 ) �대깽�� --- //
    $("#selected_alm_server").on("select2:select", function(e) {
        $("#preset").addClass("hidden");
        $("#preset_message").addClass("hidden");
        $("#cloud_project_tree").hide();
        $("#select-project-div").hide();
        $("#select-issuetype-div").hide();
        $("#select-project").text("�좏깮�섏� �딆쓬");
        $("#select-issuetype").text("�좏깮�섏� �딆쓬");
        selected_alm_server_id = $("#selected_alm_server").val();
        selected_alm_server_name = $("#selected_alm_server").select2("data")[0].text;
        $("#select-alm-server").text(selected_alm_server_name);

        let alm_server_data = alm_server_list[selected_alm_server_id];
        let alm_server_type = alm_server_data.c_jira_server_type;

        if (alm_server_type === "�대씪�곕뱶") {
            $("#preset_message").removeClass("hidden");
            $("#preset").removeClass("hidden");
            $("#cloud_project_tree").show();
            $("#select-project-div").show();
            $("#select-issuetype-div").show();

            build_alm_server_jstree(selected_alm_server_id);
            init_data_load();
        }
        else {
            mapping_data_load(selected_alm_server_id, alm_server_type);
        }
    });
} // end make_alm_server_select_box()

function init_data_load() {
    Promise.all([get_arms_state_category_list(), get_arms_state_list()])
        .then(([arms_state_category_list, arms_state_list]) => {

            for (var k in arms_state_category_list) {
                var obj = arms_state_category_list[k];
                req_state_category_list[obj.c_id] = obj;
            }

            console.log('ARMS Category State List:', req_state_category_list);
            console.log('ARMS State List:', arms_state_list);

            let data = generate_gojs_mapping_data(req_state_category_list, arms_state_list, null, null);
            gojs.load(data);
        })
        .catch((error) => {
            console.error('Error fetching data:', error);
        });
}

function mapping_data_load(almServerId, alm_server_type, project_id, issueTypeId) {
    if (!alm_server_type) {
        almServerId = almServerId || selected_alm_server_id;

        if (!almServerId) {
            alert("�좏깮�� �쒕쾭媛� �놁뒿�덈떎.");
            return;
        }

        let alm_server_data = alm_server_list[almServerId];
        alm_server_type = alm_server_data.c_jira_server_type;
    }

    if (alm_server_type === "�대씪�곕뱶") {
        if (!project_id|| !issueTypeId) {
            alert("�좏깮�� �꾨줈�앺듃 �댁뒋�좏삎�� �놁뒿�덈떎.");
            return;
        }

        Promise.all([get_arms_state_list(), getIssueStatusListByIssueType(issueTypeId)])
            .then(([arms_state_list, alm_status_list]) => {
                console.log('ARMS State List:', arms_state_list);
                console.log('ALM Status List:', alm_status_list);

                if (alm_status_list.length === 0) {
                    alert("�곌껐�� �곹깭媛� �놁뒿�덈떎. 沅뚰븳 �뺤씤�� �꾩슂�⑸땲��.");
                    let data = {};
                    gojs.load(data);
                    return;
                }

                let data = generate_gojs_mapping_data(req_state_category_list, arms_state_list, alm_status_list, alm_server_type);
                gojs.load(data);
            })
            .catch((error) => {
                console.error('Error fetching data:', error);
            });
    }
    else {
        Promise.all([get_arms_state_list(), getAlmIssueStatusList(almServerId)])
            .then(([arms_state_list, alm_status_list]) => {
                console.log('ARMS State List:', arms_state_list);
                console.log('ALM Status List:', alm_status_list);

                let gojs_mapping_data = generate_gojs_mapping_data(req_state_category_list, arms_state_list, alm_status_list, alm_server_type);
                gojs.load(gojs_mapping_data);
            })
            .catch((error) => {
                console.error('Error fetching data:', error);
            });
    }
}

function generate_gojs_mapping_data(req_state_category_list, arms_state_list, alm_status_list, alm_server_type) {
    const node_data_array = [];
    const link_data_array = [];

    const category_x_position = 0;
    const arms_state_x_position = 300;
    const alm_status_x_position = 600;

    const y_spacing = 50;
    const category_y_spacing = 50;

    let category_y_position = 0;
    let arms_state_y_position = 0;
    let alm_status_y_position = 0;

    const category_nodes = {};
    const arms_state_nodes = {};
    let alm_status_nodes = {};

    if (req_state_category_list && Array.isArray(Object.entries(req_state_category_list))) {
        Object.entries(req_state_category_list).forEach(([key, value]) => {
            const category_type = "arms-category";
            const category_node_key = category_type+ "-"+key;
            const node = {
                key: category_node_key,
                text: `${value.c_title}`,
                type: category_type,
                c_id: key,
                category: 'Loading',
                loc: `${category_x_position} ${category_y_position}`
            };

            node_data_array.push(node);
            category_nodes[key] = node;
            category_y_position += category_y_spacing;
        });
    }

    if (arms_state_list && Array.isArray(Object.entries(arms_state_list))) {
        arms_state_list.forEach((state) => {
            const arms_state_type = "arms-state";
            const arms_node_key = arms_state_type + "-" + state.c_id;
            const node = {
                key: arms_node_key,
                text: `${state.c_title}`,
                type: arms_state_type,
                c_id: state.c_id,
                c_check: state.c_check,
                category: 'NoAdd',
                loc: `${arms_state_x_position} ${arms_state_y_position}`,
            };

            if (state.reqStateCategoryEntity) {
                node.mapping_id = state.reqStateCategoryEntity.c_id;
            }
            else {
                node.mapping_id = null;
            }

            node_data_array.push(node);
            arms_state_nodes[state.c_id] = node;
            arms_state_y_position += y_spacing;
        });
    }

    if (alm_status_list && Array.isArray(alm_status_list)) {
        alm_status_list.forEach((status) => {
            const alm_status_type = "alm-status";
            const alm_node_key = alm_status_type + "-" + status.c_id;
            const node = {
                key: alm_node_key,
                text: `${status.c_issue_status_name}`,
                server_type: alm_server_type,
                type: alm_status_type,
                c_id: status.c_id,
                mapping_id: status.c_req_state_mapping_link,
                category: 'End',
                loc: `${alm_status_x_position} ${alm_status_y_position}`
            };

            node_data_array.push(node);
            alm_status_nodes[status.c_id] = node;
            alm_status_y_position += y_spacing;
        });
    }

    // 留곹겕 �곗씠�� �앹꽦
    node_data_array.forEach((node) => {
        if (node.type === 'arms-state' && node.mapping_id) {
            const fromNode = category_nodes[node.mapping_id];
            if (fromNode) {
                link_data_array.push({ from: fromNode.key, to: node.key, fromNode: fromNode, toNode: node, oldFromNode: fromNode, oldToNode: node });
            }
        } else if (node.type === 'alm-status' && node.mapping_id) {
            const fromNode = arms_state_nodes[node.mapping_id];
            if (fromNode) {
                link_data_array.push({ from: fromNode.key, to: node.key, fromNode: fromNode, toNode: node, oldFromNode: fromNode, oldToNode: node });
            }
        }
    });

    // �붿뒪 �곹깭 �몃뱶 �뺣젹
    const sorted_arms_state_nodes = Object.values(arms_state_nodes).sort((a, b) => {
        const mappingAExists = a.mapping_id !== undefined && a.mapping_id !== null;
        const mappingBExists = b.mapping_id !== undefined && b.mapping_id !== null;

        // mapping_id媛� �녿뒗 �곗씠�곕뒗 �꾨옒履쎌뿉 諛곗튂
        if (!mappingAExists) return 1;
        if (!mappingBExists) return -1;

        // 留ㅽ븨 湲곗� �곹깭 移댄뀒怨좊━ �몃뱶 議고쉶
        const category_node_a = category_nodes[a.mapping_id];
        const category_node_b = category_nodes[b.mapping_id];

        // 留ㅽ븨�� �곹깭 移댄뀒怨좊━媛� �놁쑝硫� �꾨옒 履쎌뿉 諛곗튂
        if (category_node_a === undefined) return 1;
        if (category_node_b === undefined) return -1;

        // �곹깭 移댄뀒怨좊━ y 醫뚰몴瑜� 湲곗� �뺣젹
        return get_y_position(category_node_a) - get_y_position(category_node_b);
    });

    arms_state_y_position = 0;
    if (sorted_arms_state_nodes && Array.isArray(sorted_arms_state_nodes)) {
        sorted_arms_state_nodes.forEach((node) => {
            node.loc = `${arms_state_x_position} ${arms_state_y_position}`;
            arms_state_y_position += y_spacing;
        });
    }

    // ALM �곹깭 �몃뱶 ARMS�� 留ㅽ븨�� �몃뱶 湲곗��쇰줈 �뺣젹
    const sorted_alm_status_nodes = Object.values(alm_status_nodes).sort((a, b) => {
        const mappingAExists = a.mapping_id !== undefined && a.mapping_id !== null;
        const mappingBExists = b.mapping_id !== undefined && b.mapping_id !== null;

        // mapping_id媛� �녿뒗 �곗씠�곕뒗 �꾨옒履쎌뿉 諛곗튂
        if (!mappingAExists) return 1;
        if (!mappingBExists) return -1;

        // 留ㅽ븨 湲곗� ARMS �곹깭 �몃뱶 議고쉶
        const state_node_a = arms_state_nodes[a.mapping_id];
        const state_node_b = arms_state_nodes[b.mapping_id];

        // 留ㅽ븨�� ARMS �곹깭媛� �놁쑝硫� �꾨옒 履쎌뿉 諛곗튂
        if (state_node_a === undefined) return 1;
        if (state_node_b === undefined) return -1;

        // ARNS �곹깭 y 醫뚰몴瑜� 湲곗� �뺣젹
        return get_y_position(state_node_a) - get_y_position(state_node_b);
    });

    alm_status_y_position = 0;
    if (sorted_alm_status_nodes && Array.isArray(sorted_alm_status_nodes)) {
        sorted_alm_status_nodes.forEach((node) => {
            node.loc = `${alm_status_x_position} ${alm_status_y_position}`;
            alm_status_y_position += y_spacing;
        });
    }

    return {
        class: 'GraphLinksModel',
        nodeDataArray: node_data_array,
        linkDataArray: link_data_array
    };
}

// y 醫뚰몴瑜� 異붿텧�섎뒗 �ы띁 �⑥닔
function get_y_position(node) {
    return parseFloat(node.loc.split(" ")[1]);
}

function get_arms_state_list() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "/auth-user/api/arms/reqState/getNodesWithoutRoot.do",
            type: "GET",
            dataType: "json",
            progress: true,
            statusCode: {
                200: function (data) {
                    resolve(data.result);
                }
            },
            error: function (e) {
                jError("ARMS �곹깭 議고쉶 以� �먮윭媛� 諛쒖깮�덉뒿�덈떎.");
                reject(e);
            }
        });
    });
}

function getAlmIssueStatusList(almServerId) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "/auth-user/api/arms/jiraServer/getIssueStatusList?c_id=" + almServerId,
            type: "GET",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            progress: true,
            statusCode: {
                200: function(result) {
                    console.log(result);
                    resolve(result.response);
                    jSuccess("ALM �쒕쾭 �곹깭 議고쉶媛� �꾨즺 �섏뿀�듬땲��.");
                }
            },
            error: function (e) {
                jError("ALM �쒕쾭 �곹깭 議고쉶 以� �먮윭媛� 諛쒖깮�덉뒿�덈떎. :: " + e);
                reject(e);
            }
        });
    });
}

function getIssueStatusListByIssueType(issueTypeId) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "/auth-user/api/arms/jiraIssueType/getIssueStatusList?c_id=" + issueTypeId,
            type: "GET",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            progress: true,
            statusCode: {
                200: function(result) {
                    console.log(result);
                    resolve(result.response);
                    jSuccess("ALM �꾨줈�앺듃 �곹깭 議고쉶媛� �꾨즺 �섏뿀�듬땲��.");
                }
            },
            error: function (e) {
                jError("ALM �꾨줈�앺듃 �곹깭 議고쉶 以� �먮윭媛� 諛쒖깮�덉뒿�덈떎. :: " + e);
                reject(e);
            }
        });
    });
}

function build_alm_server_jstree(selected_alm_server_id) {
    var jQueryElementID = "#alm_server_tree";
    var serviceNameForURL = "/auth-user/api/arms/jiraServerProjectPure/getJiraProjectList.do?c_id=" + selected_alm_server_id;

    jstree_build(jQueryElementID, serviceNameForURL);
}

////////////////////////////////////////////////////////////////////////////////////////
// -- jstree build �ㅼ젙 -- //
////////////////////////////////////////////////////////////////////////////////////////
function jstree_build(jQueryElementID, serviceNameForURL) {
    console.log("mapping :: jstree_build : ( jQueryElementID ) �� " + jQueryElementID);
    console.log("mapping :: jstree_build : ( serviceNameForURL ) �� " + serviceNameForURL);

    console.log("mapping :: jstree_build : ( href ) �� " + $(location).attr("href"));
    console.log("mapping :: jstree_build : ( protocol ) �� " + $(location).attr("protocol"));
    console.log("mapping :: jstree_build : ( host ) �� " + $(location).attr("host"));
    console.log("mapping :: jstree_build : ( pathname ) �� " + $(location).attr("pathname"));
    console.log("mapping :: jstree_build : ( search ) �� " + $(location).attr("search"));
    console.log("mapping :: jstree_build : ( hostname ) �� " + $(location).attr("hostname"));
    console.log("mapping :: jstree_build : ( port ) �� " + $(location).attr("port"));

    $(jQueryElementID)
        .jstree({
            plugins: ["themes", "json_data", "ui", "crrm", "dnd", "search", "types"],
            themes: { theme: ["lightblue4"] },
            json_data: {
                ajax: {
                    url: serviceNameForURL,
                    cache: false,
                    data: function (n) {
                        // the result is fed to the AJAX request `data` option
                        console.log("[ common :: jsTreeBuild ] :: json data load = " + JSON.stringify(n));
                        return {
                            c_id: n.attr ? n.attr("id").replace("node_", "").replace("copy_", "") : 1
                        };
                    },
                    success: function (n) {
                        jSuccess("�꾨줈�앺듃 議고쉶 �꾨즺");
                        n.forEach(project => {
                            project.attr.rel = "project";
                            project.attr.title = project.c_title;
                            project.children = [];
                            project.jiraIssueTypePureEntities.forEach(issueType => {
                                // �섏쐞 �묒뾽 �댁뒋�좏삎 �쒓굅 泥섎━
                                if (issueType.c_contents !== "-1" || issueType.c_desc !== "true") {
                                    project.children.push({
                                        attr: { rel: "issueType", id: "issueType_" + issueType.c_id, title: issueType.c_issue_type_name },
                                        data: [issueType.c_issue_type_name],
                                        text: issueType.c_issue_type_name,
                                    });
                                }
                            });
                        });

                        $(jQueryElementID).jstree("search", $("#text").val());
                    }
                }
            },
            search: {
                show_only_matches: true,
                search_callback: function (str, node) {
                    return node.data().search(str);
                }
            },
            types: {
                max_depth: -2,
                max_children: -2,
                valid_children: ["project"],
                types: {
                    default: {
                        // I want this type to have no children (so only leaf nodes)
                        // In my case - those are files
                        valid_children: "none",
                        // If we specify an icon for the default type it WILL OVERRIDE the theme icons
                        icon: {
                            image: "../reference/jquery-plugins/jstree-v.pre1.0/themes/attibutes.png"
                        }
                    },
                    project: {
                        valid_children: ["issueType"],
                        icon: {
                            image: "../reference/jquery-plugins/jstree-v.pre1.0/themes/ic_app.png"
                        }
                    },
                    issueType: {
                        valid_children: "none",
                        icon: {
                            image: "../reference/jquery-plugins/jstree-v.pre1.0/themes/toolbar_new.png"
                        }
                    }
                }
            },
        })
        .bind("select_node.jstree", function (event, data) {
            if ($.isFunction(jstree_click)) {
                console.log("[ jstree_build :: select_node ] :: data.rslt.obj.data('id')" + data.rslt.obj.attr("id"));
                console.log("[ jstree_build :: select_node ] :: data.rslt.obj.data('rel')" + data.rslt.obj.attr("rel"));
                console.log("[ jstree_build :: select_node ] :: data.rslt.obj.data('class')" + data.rslt.obj.attr("class"));
                console.log("[ jstree_build :: select_node ] :: data.rslt.obj.children('a')" + data.rslt.obj.children("a"));
                console.log("[ jstree_build :: select_node ] :: data.rslt.obj.children('ul')" + data.rslt.obj.children("ul"));
                jstree_click(data.rslt.obj);
            }
        })
        .bind("loaded.jstree", function (event, data) {
            $(jQueryElementID).slimscroll({
                height: "200px"
            });
        });

    $("#mmenu input, #mmenu button").click(function () {
        switch (this.id) {
            case "add_default":
            case "add_folder":
                $(jQueryElementID).jstree("create", null, "last", {
                    attr: {
                        rel: this.id.toString().replace("add_", "")
                    }
                });
                break;
            case "search":
                $(jQueryElementID).jstree("search", document.getElementById("text").value);
                break;
            case "text":
                break;
            default:
                $(jQueryElementID).jstree(this.id);
                break;
        }
    });

    $("#mmenu .form-search").submit(function (event) {
        event.preventDefault();

        $(jQueryElementID).jstree("search", document.getElementById("text").value);
    });
}

function jstree_click(data) {

    let rel = data.attr('rel');
    if (rel === "project") {
        $(".jstree-clicked").removeClass("jstree-clicked");
        console.log(rel);
        return;
    }
    else {
        let project_title = data.parent().parent().attr("title");
        $("#select-project").text(project_title);
        let issueType_title = data.attr("title");
        $("#select-issuetype").text(issueType_title);

        let project_c_id = data.parent().parent().attr("id").replace("node_", "").replace("copy_", "");
        let issueType_c_id = data.attr("id").replace("issueType_", "").replace("copy_", "");
        mapping_data_load(null, null, project_c_id, issueType_c_id);
    }
}

///////////////////////////////////
// �앹뾽 �꾩슱 ��, UI �쇰� �섏젙�섎룄濡�
///////////////////////////////////
function popup_modal(popup_type, state_id, state_name) {
    $('#my_modal1').modal('show');

    const container = $('#popup_view_state_category_div');
    container.empty();

    for (const key in req_state_category_list) {
        if (req_state_category_list.hasOwnProperty(key)) {
            const item = req_state_category_list[key];

            const label = $('<label>', {
                class: 'btn btn-disabled',
                style: 'margin-right: 5px;'
            });

            switch (item.c_title) {
                case '�대┝':
                    label.addClass('edit-red');
                    break;
                case '吏꾪뻾以�':
                    label.addClass('edit-orange');
                    break;
                case '�닿껐��':
                    label.addClass('edit-green');
                    break;
                case '�ロ옒':
                    label.addClass('edit-blue');
                    break;
            }

            const input = $('<input>', {
                type: 'radio',
                name: 'popup_view_state_category_options',
                value: item.c_id
            });

            label.append(input);
            label.append(item.c_category_icon + " " +item.c_title + " ");

            container.append(label);
        }
    }

    $("#popup_view_state_category_div label").removeClass("active");
    $("input[name='popup_view_state_category_options']:checked").prop("checked", false);
    $("#popup_view_state_name").val("");
    CKEDITOR.instances.popup_view_state_description_editor.setData("�곹깭 愿��� �ㅻ챸 �깆쓣 湲곕줉�⑸땲��.");

    $("#delete_req_state").addClass("hidden");
    $("#update_req_state").addClass("hidden");
    $("#save_req_state").addClass("hidden");
    $("#change_state_div").addClass("hidden");
    $("#state_category_div").addClass("hidden");
    $("#state_title_div").removeClass("hidden");
    $("#state_contents_div").removeClass("hidden");

    if (popup_type === "save_popup") {
        $("#my_modal1_title").text("ARMS �곹깭 �깅줉 �앹뾽");
        $("#my_modal1_description").text("A-RMS �붽뎄�ы빆�� �곹깭瑜� �깅줉�⑸땲��.");

        // 紐⑤떖 �깅줉, �섏젙蹂� 踰꾪듉 珥덇린��
        $("#save_req_state").removeClass("hidden");
        $("#state_category_div").removeClass("hidden");
    }
    else if (popup_type === "update_popup") {
        $("#my_modal1_title").text("ARMS �곹깭 �섏젙 �앹뾽");
        $("#my_modal1_description").text("A-RMS �붽뎄�ы빆�� �곹깭瑜� �섏젙�⑸땲��.");

        $("#update_req_state").removeClass("hidden");

        $.ajax({
            url: "/auth-user/api/arms/reqState/getNode.do?c_id=" + state_id,
            type: "get",
            statusCode: {
                200: function (data) {
                    console.log(data);

                    $("#popup_view_state_c_id").val(data.c_id);
                    $("#popup_view_state_name").val(data.c_title);
                    CKEDITOR.instances.popup_view_state_description_editor.setData(data.c_contents);
                    let state_category_value = null;
                    if (data.reqStateCategoryEntity) {
                        state_category_value = data.reqStateCategoryEntity.c_id;
                    }

                    if (data.c_check && data.c_check === "true") {
                        $("#my_modal1_description").html("A-RMS �붽뎄�ы빆�� �곹깭瑜� �섏젙�⑸땲��.<br>" + "湲곕낯 �곹깭�� 寃쎌슦 �곹깭 移댄뀒怨좊━�� �섏젙�� �� �놁뒿�덈떎.");
                    }
                    else {
                        $("#state_category_div").removeClass("hidden");
                    }

                    update_radio_buttons("#popup_view_state_category_div", state_category_value);
                }
            }
        });
    }
    else if (popup_type === "delete_popup") {
        $("#my_modal1_title").text("ARMS �곹깭 ��젣 �앹뾽");
        $("#my_modal1_description").text("A-RMS �붽뎄�ы빆�� �곹깭瑜� ��젣�섍퀬 �붽뎄�ы빆�� �곹깭瑜� 諛붽� �곹깭瑜� �좏깮�⑸땲��.");

        $("#state_title_div").addClass("hidden");
        $("#state_contents_div").addClass("hidden");
        $("#delete_req_state").removeClass("hidden");
        $("#change_state_div").removeClass("hidden");

        $("#popup_view_state_c_id").val(state_id);
        $("#popup_view_change_state_name").val(state_name);

        $("#popup_view_change_state_div").empty();
        get_arms_req_state_list()
            .then((state_list) => {
                let option_html = `<option value=""></option>`;

                for (var k in state_list) {
                    var state = state_list[k];
                    if (state_id !== state.c_id){
                        option_html += `<option value="${state.c_id}">${state.c_title}</option>`;
                    }
                }

                $("#popup_view_change_state_div").append(`<select
									class="select-block-level chzn-select darkBack"
									id="select-change-state"
									tabIndex="-1">
									${option_html}
								</select>`);

                $(".chzn-select").each(function () {
                    // $(this).select2($(this).data());
                    $(this).select2({
                        ...$(this).data(),
                        minimumResultsForSearch: -1 // 寃��� 湲곕뒫 �쒓굅
                    });
                });
            })
            .catch((error) => {
                console.error('Error fetching data:', error);
            });
    }
}

function update_radio_buttons(container_selector, value) {
    $(container_selector + " label").removeClass("active");
    $(container_selector + " input[type='radio']:checked").prop("checked", false);

    let radio_buttons = $(container_selector + " input[type='radio']");
    radio_buttons.each(function () {
        if (value && $(this).val() == value) {
            $(this).parent().addClass("active");
            $(this).prop("checked", true);
        }
    });
}

function save_req_state_btn_click() {
    $("#save_req_state").off().click(function() {
        let state_name = $("#popup_view_state_name").val().trim();
        if (!state_name) {
            alert("�곹깭�� �대쫫�� �낅젰�섏� �딆븯�듬땲��.");
            return;
        }
        let state_category_value = $("#popup_view_state_category_div input[name='popup_view_state_category_options']:checked").val();
        if (!state_category_value) {
            alert("�곹깭 移댄뀒怨좊━媛� �좏깮�섏� �딆븯�듬땲��.");
            return;
        }
        let state_description = CKEDITOR.instances["popup_view_state_description_editor"].getData();

        let data = {
            ref : 2,
            c_type : "default",
            c_state_category_mapping_id : state_category_value,
            c_title : state_name,
            c_contents : state_description
        };

        $.ajax({
            url: "/auth-user/api/arms/reqState/addStateNode.do",
            type: "POST",
            data: data,
            statusCode: {
                200: function () {
                    jSuccess('"' + state_name + '"' + " �곹깭媛� �앹꽦�섏뿀�듬땲��.");
                    $("#close_modal_popup").trigger("click");

                    init_mapping_diagram();
                }
            }
        });
    });
}

function update_req_state_btn_click() {
    $("#update_req_state").off().click(function() {
        let state_name = $("#popup_view_state_name").val().trim();
        if (!state_name) {
            alert("�곹깭�� �대쫫�� �낅젰�섏� �딆븯�듬땲��.");
            return;
        }
        let state_category_value = $("#popup_view_state_category_div input[name='popup_view_state_category_options']:checked").val();
        if (!state_category_value) {
            alert("�곹깭 移댄뀒怨좊━媛� �좏깮�섏� �딆븯�듬땲��.");
            return;
        }
        let state_description = CKEDITOR.instances["popup_view_state_description_editor"].getData();

        update_arms_state($("#popup_view_state_c_id").val(), state_category_value, state_name, state_description)
            .then((result) => {
                console.log(result);
                $("#close_modal_popup").trigger("click");

                init_mapping_diagram();
            })
            .catch((error) => {
                // �ㅻ쪟媛� 諛쒖깮�� 寃쎌슦 泥섎━�⑸땲��.
                console.error('Error fetching data:', error);
            });
    });
}

function delete_req_state_btn_click() {
    $("#delete_req_state").off().click(function() {

        let state_id_before_change = $("#popup_view_state_c_id").val();
        let state_id_to_change = $('#select-change-state').val(); // 蹂�寃쏀븷 �좏깮�� �곹깭 �꾩씠��
        if (!state_id_to_change) {
            alert("蹂�寃쏀븷 �곹깭 �좏깮�� �꾩슂�⑸땲��.");
            return false;
        }

        let state_name = $("#popup_view_change_state_name").val().trim();
        let change_state_name = $("#select-change-state option:selected").text().trim();

        let isDelete = confirm(state_name + " �곹깭瑜� ��젣 �섍퀬 " + change_state_name + " �곹깭濡� 蹂��섑븯�쒓쿋�듬땲源�?");
        if (!isDelete) {
            return false;
        }

        remove_arms_state(state_id_before_change, state_name, state_id_to_change)
            .then((result) => {
                console.log(result);
                $("#close_modal_popup").trigger("click");

                init_mapping_diagram();
            })
            .catch((error) => {
                console.error('Error fetching data:', error);
            });
    });
}

function init_mapping_diagram() {
    // �좏깮�� �쒕쾭媛� �덉쓣  Mapping �붾㈃ �щ줈��
    if ($("#selected_alm_server").val()) {
        let selected_alm_server_c_id = $("#selected_alm_server").val();
        let alm_server_data = alm_server_list[selected_alm_server_c_id];
        let alm_server_type = alm_server_data.c_jira_server_type;

        if (alm_server_type === "�대씪�곕뱶") {
            $("#select-project").text("�좏깮�섏� �딆쓬");
            $("#select-issuetype").text("�좏깮�섏� �딆쓬");
            $("#cloud_project_tree").show();
            $("#select-project-div").show();
            $("#select-issuetype-div").show();
            build_alm_server_jstree(selected_alm_server_c_id);
            let data = {};
            gojs.load(data);
        }
        else {
            mapping_data_load(selected_alm_server_c_id, alm_server_type);
        }
    }
}

function update_arms_state(state_c_id, state_category_mapping_id, state_name, state_contents) {

    return new Promise((resolve, reject) => {

        let data = {
            c_id : state_c_id,
            c_state_category_mapping_id : state_category_mapping_id,
        };

        if (state_contents) {
            data.c_contents = state_contents;
        }

        if (state_name) {
            data.c_title = state_name;
        }

        $.ajax({
            url: "/auth-user/api/arms/reqState/updateNode.do",
            type: "PUT",
            data: data,
            statusCode: {
                200: function (result) {
                    resolve(result);
                }
            },
            error: function (e) {
                jError("�곹깭 �섏젙 以� �ㅻ쪟媛� 諛쒖깮�섏��듬땲��.");
                reject(e);
            }
        });
    });
}

function remove_arms_state(state_c_id, state_name, state_id_to_change) {
    return new Promise((resolve, reject) => {

        let data = {
            c_id : state_c_id,
            stateIdToChange : state_id_to_change
        };

        $.ajax({
            url: "/auth-user/api/arms/reqState/removeNodeAndChangeState.do",
            type: "DELETE",
            data: data,
            statusCode: {
                200: function (data) {
                    jSuccess('"' + state_name + '"' + " �곹깭媛� ��젣�섏뿀�듬땲��.");
                    resolve(data);
                }
            },
            error: function (e) {
                jError("�곹깭 ��젣 以� �ㅻ쪟媛� 諛쒖깮�섏��듬땲��.");
                reject(e);
            }
        });
    });
}

function update_alm_status(issue_status_c_id, req_state_c_id) {
    return new Promise((resolve, reject) => {

        let data = {
            c_id : issue_status_c_id,
            c_req_state_mapping_link : req_state_c_id,
        };

        $.ajax({
            url: "/auth-user/api/arms/jiraIssueStatus/updateNode.do",
            type: "PUT",
            data: data,
            statusCode: {
                200: function (result) {
                    resolve(result);
                }
            },
            error: function (e) {
                jError("ALM �곹깭 �섏젙 以� �ㅻ쪟媛� 諛쒖깮�섏��듬땲��.");
                reject(e);
            }
        });
    });
}

function preset_btn_click() {
    $("#preset").off().click(function() {
        let server_id = selected_alm_server_id;
        if (!server_id) {
            alert("�좏깮�� �쒕쾭媛� �놁뒿�덈떎.");
            return;
        }

        let server_data = alm_server_list[server_id];
        if (!confirm(server_data.c_title + " �쒕쾭�� �꾨줈�앺듃蹂� �댁뒋�좏삎蹂� �댁뒋�곹깭 �꾨━�� 留ㅽ븨�� 吏꾪뻾�섏떆寃좎뒿�덇퉴? ")) {
            return;
        }

        let data = {
            c_id : server_id
        };

        $.ajax({
            url: "/auth-user/api/arms/jiraServer/preSetIssueStatusMapping.do",
            type: "POST",
            data: data,
            statusCode: {
                200: function () {
                    jSuccess(`${server_data.c_title} �꾨━�� �ㅼ젙 吏꾪뻾 以묒엯�덈떎. <br> �꾨줈�앺듃 �섏뿉 �곕씪 嫄몃━�� �쒓컙 李④� 諛쒖깮�� �� �덉뒿�덈떎.`);
                    build_alm_server_jstree(server_id);
                    init_data_load();
                }
            },
            error: function (e) {
                console.error(e);
                jError("�대씪�곕뱶 吏��� �꾨━�� �ㅼ젙 以� �ㅻ쪟媛� 諛쒖깮�섏��듬땲�� :: " + e);
            }
        });
    });
}