/**
 * 공통코드 관리 화면 스크립트
 */

let tableGroup;
let tableCode;
let currentSelectedGroup = null;

$(document).ready(function () {
    initGrid();
    bindEvents();
    loadGroupData();
});

function initGrid() {
    let commonOpts = {
        layout: "fitColumns",
        selectableRows: 1, // 단일 선택
        selectableRowsRangeMode: "click",
        height: "100%",
        columnDefaults: {
            headerTooltip: true,
            headerHozAlign: "center",
            hozAlign: "center"
        }
    };

    // 1. 좌측 그룹 그리드
    tableGroup = new Tabulator("#gridGroup", Object.assign({}, commonOpts, {
        columns: [
            { title: "No", field: "no", width: 60, formatter: "rownum", headerSort: false },
            { title: "그룹 ID", field: "grp_cd", width: 120 },
            { title: "그룹 명칭", field: "grp_nm", width: 150 },
            { title: "사용여부", field: "list_use", width: 80, formatter: ynFormatter },
            {
                title: "수정", width: 60, headerSort: false, formatter: editFormatter, cellClick: function (e, cell) {
                    editGroup(cell.getRow().getData().pid);
                }
            },
        ],
    }));

    tableGroup.on("rowClick", function (e, row) {
        let data = row.getData();
        currentSelectedGroup = data;

        // 우측 패널 UI 활성화
        $("#codePanelTitle").html(`상세 코드 <span style="font-size: 14px; color: #1a73e8; margin-left:10px; font-weight:normal;">[${data.grp_nm} (${data.grp_cd})]</span>`);
        $("#codeSearchInput").prop("disabled", false);
        $("#btnAddCode").prop("disabled", false).css({
            "background": "#3985EA",
            "color": "#fff",
            "border-color": "#3985EA"
        });

        loadCodeData(data.grp_cd);
    });

    // 2. 우측 상세 코드 그리드
    tableCode = new Tabulator("#gridCode", Object.assign({}, commonOpts, {
        columns: [
            { title: "정렬", field: "code_sort", width: 60 },
            { title: "코드 ID", field: "code_cd", width: 120 },
            { title: "코드 명칭", field: "code_nm", width: 150 },
            { title: "추가값", field: "code_val", width: 120 },
            { title: "사용여부", field: "list_use", width: 80, formatter: ynFormatter },
            {
                title: "수정", width: 60, headerSort: false, formatter: editFormatter, cellClick: function (e, cell) {
                    editCode(cell.getRow().getData().pid);
                }
            },
        ],
    }));
}

function ynFormatter(cell) {
    return cell.getValue() === 'y' ? '<span style="color:#3985EA; font-weight:600;">Y</span>' : '<span style="color:#ccc;">N</span>';
}

function editFormatter(cell) {
    return '<span class="grid-link-btn grid-link-edit" style="cursor:pointer; display:inline-block; border:1px solid #ccc; padding:2px 6px; border-radius:3px; font-size:12px; background:#fff;">수정</span>';
}

function bindEvents() {
    // 그룹 검색
    $("#groupSearchInput").on("keyup", function (e) {
        if (e.keyCode === 13) loadGroupData();
    });

    // 상세 코드 검색
    $("#codeSearchInput").on("keyup", function (e) {
        if (e.keyCode === 13 && currentSelectedGroup) {
            loadCodeData(currentSelectedGroup.grp_cd);
        }
    });

    // 창 닫힐 때 리로드용
    window.addEventListener("message", function (event) {
        if (event.data === 'reloadGroup') {
            loadGroupData();
        } else if (event.data === 'reloadCode' && currentSelectedGroup) {
            loadCodeData(currentSelectedGroup.grp_cd);
        }
    }, false);
}

// ==========================================
// API 로드
// ==========================================

window.loadGroupData = function () {
    let searchWd = $("#groupSearchInput").val();
    $.ajax({
        url: "/settings/code/getCodeGroupList.do",
        type: "POST",
        data: { searchWd: searchWd },
        success: function (res) {
            if (res.msgCode === '0') {
                tableGroup.setData(res.rows || []);
                if (!currentSelectedGroup) {
                    tableCode.setData([]);
                }
            } else {
                alert(res.msgDesc);
            }
        },
        error: function (e) {
            console.error(e);
            alert("그룹 조회 실패");
        }
    });
};

window.loadCodeData = function (grpCd) {
    let searchWd = $("#codeSearchInput").val();
    $.ajax({
        url: "/settings/code/getCodeList.do",
        type: "POST",
        data: { grpCd: grpCd, searchWd: searchWd },
        success: function (res) {
            if (res.msgCode === '0') {
                tableCode.setData(res.rows || []);
            } else {
                alert(res.msgDesc);
            }
        },
        error: function (e) {
            console.error(e);
            alert("상세 코드 조회 실패");
        }
    });
};

// ==========================================
// 팝업 호출
// ==========================================

window.addGroup = function () {
    let url = "/settings/code/codeGroupPop.do?mode=add";
    window.open(url, "codeGroupPop", "width=500, height=450, resizable=no, scrollbars=no, status=no;");
};

window.editGroup = function (pid) {
    let url = `/settings/code/codeGroupPop.do?mode=edit&pid=${pid}`;
    window.open(url, "codeGroupPop", "width=500, height=450, resizable=no, scrollbars=no, status=no;");
};

window.addCode = function () {
    if (!currentSelectedGroup) return;
    let url = `/settings/code/codePop.do?mode=add&grpCd=${currentSelectedGroup.grp_cd}&grpNm=${encodeURIComponent(currentSelectedGroup.grp_nm)}`;
    window.open(url, "codePop", "width=500, height=550, resizable=no, scrollbars=no, status=no;");
};

window.editCode = function (pid) {
    if (!currentSelectedGroup) return;
    let url = `/settings/code/codePop.do?mode=edit&pid=${pid}&grpCd=${currentSelectedGroup.grp_cd}&grpNm=${encodeURIComponent(currentSelectedGroup.grp_nm)}`;
    window.open(url, "codePop", "width=500, height=550, resizable=no, scrollbars=no, status=no;");
};
