let url = $("#apiUrl").val();
let flag = "insert";
let tempApiData;
let isButtonDisabled = false;

var ReqEvent = {

    // 시나리오 그룹 매핑
    reqGetOpr: function () {
        commonUtil.doActionGet({
            "url": commonUtil.getContextPath() + "/adm/menu/oprmng?menuval=rcpconversationapiNodemanage",
            "callBack": ResEvent.resGetOpr
        })
    },

    // 데이터 저장
    reqInsertData: function (serializeArray) {
        commonUtil.doAction({
            "url": commonUtil.getContextPath() + "/admin/rcp/conversation/insertApiNode",
            "data": {
                textContents: JSON.stringify(serializeArray)
                , seq: $("#apiSeq").val()
                , custCode: $('#serviceGroup option:selected').attr("custCode")
                , serviceGroup: $("#serviceGroup option:selected").val()
                , nodeName: $("#APINodeName").val()
            },
            "callBack": ResEvent.resInsertData
        });
    },

    // 데이터 수정
    reqUpdateData: function (serializeArray) {
        commonUtil.doAction({
            "url": commonUtil.getContextPath() + "/admin/rcp/conversation/updateApiNode",
            "data": {
                textContents: JSON.stringify(serializeArray)
                , seq: $("#apiSeq").val()
                , custCode: $('#serviceGroup option:selected').attr("custCode")
                , serviceGroup: $("#serviceGroup option:selected").val()
                , nodeName: $("#APINodeName").val()
            },
            "callBack": ResEvent.resUpdateData
        });
    },

    // API 노드 단건 조회
    reqGetApiNode: function (seq) {
        commonUtil.doAction({
            "url": commonUtil.getContextPath() + "/admin/rcp/conversation/selectApiNode",
            "data":
                {
                    seq: seq
                },
            "callBack": ResEvent.resGetApiNodeList
        })
    }

};

var ResEvent = {

    resGetOpr: function (data) {
        let serviceGroup = $("#apiServiceGroup").val();
        if (data.length == 0) {
            alert("조회 가능한 시나리오 그룹이 없습니다.");
        } else {
            data.forEach(function (e) {
                if (serviceGroup === e.serviceGroup) {
                    $('#serviceGroup').append("<option value=" + e.serviceGroup + " custCode=" + e.custCode + " selected>" + e.serviceGroupName + "</option>");
                } else {
                    $('#serviceGroup').append("<option value=" + e.serviceGroup + " custCode=" + e.custCode + ">" + e.serviceGroupName + "</option>");
                }
            });
            $("#serviceGroup").prop("disabled", true)
            $('#serviceGroup').niceSelect('update');
        }
    },

    resInsertData: function (data) {
        let url = commonUtil.getContextPath()+"/admin/rcp/conversation/apiNodeEdit/manage.do?seq="+data;
        $.utils.successAndElse("정상적으로 저장되었습니다.", () => {
            $.utils.redirect(url);
        }, () => {
            $.utils.redirect(url);
        });
    },

    resUpdateData: function (data) {
        // swal("Success", "수정되었습니다.", "success").then(function () {
        //     location.reload();
        // })
        $.utils.successAndElse("수정되었습니다.", () => {
            location.reload();
        }, () => {
            location.reload();
        });

    },

    resGetApiNodeList: function (data) {
        tempApiData = data;
        
        let json = JSON.parse(data.apiData[0].textContents)
        let group = data.apiDataInfo[0].oprMngCode;
        let splitGroup = group.split("_");
        $("#APINodeName").val(data.apiDataInfo[0].nodeName);
        $("#urlSelect").val(json.urlType).niceSelect("update");
        $("#APINodeUrl").val(json.URL);
        $("#serviceGroup").val(splitGroup[2]);

        let headerHtml = "";
        if(json.header.length == 0) {
            headerHtml += `<tr>
                            <td><div class='ipt_box'><input type='text' placeholder='key' name='header[0][key]' value=''></div></td>
                            <td><div class='ipt_box'><input type='text' placeholder='value' name='header[0][value]' value=''></div></td>
                            <td><div class='ipt_box'><input type='text' placeholder='Description' name='header[0][desc]' value=''></div></td>
                        </tr>`
        } else {
            for (let i = 0; i < json.header.length; i++) {
                if (json.header[i] == null) {
                    continue;
                }
                if (i == 0) {
                    headerHtml += `<tr>
                                    <td><div class='ipt_box'><input type='text' placeholder='key' name='header[${i}][key]' value='${json.header[i].key}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='value' name='header[${i}][value]' value='${json.header[i].value}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='Description' name='header[${i}][desc]' value='${$.utils.isEmpty(json.header[i].desc)}'></div></td>
                                </tr>`
                } else {
                    headerHtml += `<tr>
                                    <td><div class='ipt_box'><input type='text' placeholder='key' name='header[${i}][key]' value='${json.header[i].key}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='value' name='header[${i}][value]' value='${json.header[i].value}'></div></td>
                                    <td><div class='ipt_box type-flex'><input type='text' placeholder='Description' name='header[${i}][desc]' value='${$.utils.isEmpty(json.header[i].desc)}'><a href='#' class='btn grey createTrInputDel'>-</a></div></td>
                                </tr>`
                }
            }
        }
        $("#headerTable tbody").empty().append(headerHtml);

        let paramHtml = "";
        if (json.param.length == 0) {
            paramHtml += `<tr>
                            <td><div class='ipt_box'><input type='text' placeholder='key' name='param[0][key]' value=''></div></td>
                            <td><div class='ipt_box'><input type='text' placeholder='value' name='param[0][value]' value=''></div></td>
                            <td><div class='ipt_box'><input type='text' placeholder='Description' name='param[0][desc]' value=''></div></td>
                        </tr>`
        } else {
            for (let i = 0; i < json.param.length; i++) {
                if (json.param[i] == null) {
                    continue;
                }
                if (i == 0) {
                    paramHtml += `<tr>
                                    <td><div class='ipt_box'><input type='text' placeholder='key' name='param[${i}][key]' value='${json.param[i].key}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='value' name='param[${i}][value]' value='${json.param[i].value}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='Description' name='param[${i}][desc]' value='${$.utils.isEmpty(json.param[i].desc)}'></div></td>
                                </tr>`
                } else {
                    paramHtml += `<tr>
                                    <td><div class='ipt_box'><input type='text' placeholder='key' name='param[${i}][key]' value='${json.param[i].key}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='value' name='param[${i}][value]' value='${json.param[i].value}'></div></td>
                                    <td><div class='ipt_box type-flex'><input type='text' placeholder='Description' name='param[${i}][desc]' value='${$.utils.isEmpty(json.param[i].desc)}'><a href='#' class='btn grey createTrInputDel'>-</a></div></td>
                                </tr>`
                }
            }
        }
        $("#paramTable tbody").empty().append(paramHtml);

        if (json.urlType === "POST") {
            let bodyHtml = "<tr>";
            bodyHtml += "<td><div class='ipt_box'><textarea id='apIBody' name='body' placeholder='body' cols='30' rows='10'>" + json.body + "</textarea></div></td>";
            bodyHtml += "</tr>";
            $("#bodyTable tbody").empty().append(bodyHtml);
            $("#apiPostBodyContents").show();
        }

        let reqHtml = "";
        if (json.request.length == 0) {
            reqHtml += `<tr>
                            <td colspan='2'><div class='ipt_box'><input type='text' placeholder='value' name='request[0][value]' value=''></div></td>
                            <td><div class='ipt_box'><input type='text' placeholder='Description' name='request[0][desc]' value=''></div></td>
                        </tr>`
        } else {
            for (let i = 0; i < json.request.length; i++) {
                if (json.request[i] == null) {
                    continue;
                }
                if (i == 0) {
                    reqHtml += `<tr>
                                    <td colspan='2'><div class='ipt_box'><input type='text' placeholder='value' name='request[${i}][value]' value='${json.request[i].value}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='Description' name='request[${i}][desc]' value='${$.utils.isEmpty(json.request[i].desc)}'></div></td>
                                </tr>`
                } else {
                    reqHtml += `<tr>
                                    <td colspan='2'><div class='ipt_box'><input type='text' placeholder='value' name='request[${i}][value]' value='${json.request[i].value}'></div></td>
                                    <td><div class='ipt_box type-flex'><input type='text' placeholder='Description' name='request[${i}][desc]' value='${$.utils.isEmpty(json.request[i].desc)}'><a href='#' class='btn grey createTrInputDel'>-</a></div></td>
                                </tr>`
                }
            }
        }
        $("#reqTable tbody").empty().append(reqHtml);

        let resHtml = "";
        if (json.response.length == 0) {
            resHtml += `<tr>
                            <td><div class='ipt_box'><input type='text' placeholder='key' name='response[0][key]' value=''></div></td>
                            <td><div class='ipt_box'><input type='text' placeholder='value' name='response[0][value]' value=''></div></td>
                            <td><div class='ipt_box'><input type='text' placeholder='Description' name='response[0][desc]' value=''></div></td>
                        </tr>`
        } else {
            for (let i = 0; i < json.response.length; i++) {
                if (json.response[i] == null) {
                    continue;
                }
                if (i == 0) {
                    resHtml += `<tr>
                                    <td><div class='ipt_box'><input type='text' placeholder='key' name='response[${i}][key]' value='${json.response[i].key}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='value' name='response[${i}][value]' value='${json.response[i].value}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='Description' name='response[${i}][desc]' value='${$.utils.isEmpty(json.response[i].desc)}'></div></td>
                                </tr>`
                } else {
                    resHtml += `<tr>
                                    <td><div class='ipt_box'><input type='text' placeholder='key' name='response[${i}][key]' value='${json.response[i].key}'></div></td>
                                    <td><div class='ipt_box'><input type='text' placeholder='value' name='response[${i}][value]' value='${json.response[i].value}'></div></td>
                                    <td><div class='ipt_box type-flex'><input type='text' placeholder='Description' name='response[[${i}][desc]' value='${$.utils.isEmpty(json.response[i].desc)}'><a href='#' class='btn grey createTrInputDel'>-</a></div></td>
                                </tr>`
                }
            }
        }

        $("#resTable tbody").empty().append(resHtml);
        tempApiData = $('form#apiDataForm').serializeObject();

        let header = tempApiData.header.filter(data => {
            return data !== undefined && !$.utils.isBlank(data.key);
        })
        tempApiData.header = header;
        let param = tempApiData.param.filter(data => {
            return data !== undefined && !$.utils.isBlank(data.key);
        })
        tempApiData.param = param;

        let request = tempApiData.request.filter(data => {
            return data !== undefined && !$.utils.isBlank(data.value);
        })
        tempApiData.request = request;

        let response = tempApiData.response.filter(data => {
            return data !== undefined && !$.utils.isBlank(data.key);
        })
        tempApiData.response = response;

        ReqEvent.reqGetOpr();
        ViewEvent.insertRow();
        ViewEvent.btnEvent();
        ViewEvent.checkPermissionPolicy();
    },

};

var ViewEvent = {
    btnEvent: function () {
        $("#btnSave").click(function () {
            let serializeArray = $('form#apiDataForm').serializeObject();

            if ($.utils.isBlank($('#APINodeName').val())) {
                swal("Fail", "API Node명을 입력해주세요.", "warning")
                return;
            }
            if ($.utils.isBlank($("#APINodeUrl").val())) {
                swal("Fail", "API URL을 입력해주세요.", "warning")
                return;
            }

            let header = serializeArray.header.filter(data => {
                return data !== undefined && !$.utils.isBlank(data.key);
            })
            serializeArray.header = header;

            let param = serializeArray.param.filter(data => {
                return data !== undefined && !$.utils.isBlank(data.key);
            })
            serializeArray.param = param;

            let request = serializeArray.request.filter(data => {
                return data !== undefined && !$.utils.isBlank(data.value);
            })
            serializeArray.request = request;

            let response = serializeArray.response.filter(data => {
                return data !== undefined && !$.utils.isBlank(data.key);
            })
            serializeArray.response = response;

            if (flag === "insert" && isButtonDisabled === false) {
                isButtonDisabled = true;
                ReqEvent.reqInsertData(serializeArray);
            } else if(flag === "update" && isButtonDisabled === false) {
                if (JSON.stringify(serializeArray) == JSON.stringify(tempApiData)) {
                    swal("Fail", "수정된 데이터가 없습니다.", "warning")
                    return;
                }
                isButtonDisabled = true;
                ReqEvent.reqUpdateData(serializeArray);
            } else {

            }
        });

        $("#btnCancel").click(function () {
            var serializeArray = $('form#apiDataForm').serializeObject();

            if (JSON.stringify(serializeArray) == JSON.stringify(tempApiData)) {
                let url = commonUtil.getContextPath() + "/admin/rcp/conversation/apiNode/manage.do";
                $.utils.redirect(url);
            } else {
                let message;
                if (!checkPermissionPolicy("rcpconversationapiNodemanageFull")) {
                    message = "API노드관리 화면으로 이동하시겠습니까?"
                } else {
                    message = "확인을 누르시면 기존에 작업한 내용은 저장되지 않습니다. \n API노드관리 화면으로 이동하시겠습니까?"
                }

                swal("취소요청", message, "warning", {
                    buttons: ["취소", "확인"],
                }).then(function (willDelete) {
                    if (willDelete) {
                        let url = commonUtil.getContextPath() + "/admin/rcp/conversation/apiNode/manage.do";
                        $.utils.redirect(url);
                    } else {
                        swal("Success", "취소되었습니다.", {
                            icon: "error",
                            buttons: "확인"
                        });
                    }
                });
            }

            // todo style.css에 추가해야한다고 말해야됨
            $(".swal-text").css("text-align", "center")
        });

        $("#urlSelect").change(function () {
            $("#bodyTable textarea").val("");
            if ($(this).val() === 'GET') {
                $("#apiPostBodyContents").hide();
            } else {
                $("#apiPostBodyContents").show();
            }
        });

        $('.createTrInputDel').on('click', function (e) {
            e.preventDefault();
            $(this).parents('tr').remove();
        })

        $("#apiBody").on("keydown", function (e) {
            let tabSize = 4; // 공백 대체 크기 (4칸)
            if(e.keyCode === 9) {
                let start = this.selectionStart;
                let end = this.selectionEnd;
                let value = $(this).val();
                let textBeforeCursor = value.substring(0, start); // 커서 이전 텍스트
                let textAfterCursor = value.substring(end); // 커서 이후 텍스트
                let tabSpaces = " ".repeat(tabSize); // 탭 대체 공백 문자열
                let replacedText = textBeforeCursor + tabSpaces + textAfterCursor; // 대체된 텍스트
                this.value = replacedText; // 입력 필드에 대체된 텍스트 설정
                this.selectionStart = start + tabSize; // 커서 위치 이동
                this.selectionEnd = start + tabSize; // 커서 위치 이동
                e.preventDefault();
            }
        });
    },

    checkPermissionPolicy: function () {
        if (!checkPermissionPolicy("rcpconversationapiNodemanageFull")) {
            $("input, textarea").attr("readonly", true);
            $("#serviceGroup").attr("disabled", "disabled");
            $('#urlSelect').prop('disabled', true).niceSelect('update');
            $("#btnSave, .createTrInputAdd, .createTrInputDel").hide();
        }
    },


    insertRow: function () {

        let headerCnt = $("#headerTable tr").length;
        let paramCnt = $("#paramTable tr").length;
        let requestCnt = $("#reqTable tr").length;
        let responseCnt = $("#resTable tr").length;
        $('.createTrInputWrapper').each(function () {
            const thisAddedBtn = $(this).find('.createTrInputAdd');
            const thisAppendArea = $(this).find('.createTrInput');
            thisAddedBtn.on('click', function (e) {
                e.preventDefault();
                if ($(this).hasClass("api-header")) {
                    const copyHeader = '<tr><td><div class="ipt_box">' +
                        '<input type="text" placeholder="key" name="header[' + headerCnt + '][key]">' +
                        '</div></td><td><div class="ipt_box">' +
                        '<input type="text" placeholder="value" name="header[' + headerCnt + '][value]">' +
                        '</div></td><td><div class="ipt_box type-flex">' +
                        '<input type="text" placeholder="Description" name="header[' + headerCnt + '][desc]">' +
                        '<a href="#" class="btn grey createTrInputDel">-</a></div></td></tr>'
                    thisAppendArea.append(copyHeader);
                    headerCnt++;
                } else if ($(this).hasClass("api-param")) {
                    const copyParam = '<tr><td><div class="ipt_box">' +
                        '<input type="text" placeholder="key" name="param[' + paramCnt + '][key]">' +
                        '</div></td><td><div class="ipt_box">' +
                        '<input type="text" placeholder="value" name="param[' + paramCnt + '][value]">' +
                        '</div></td><td><div class="ipt_box type-flex">' +
                        '<input type="text" placeholder="Description" name="param[' + paramCnt + '][desc]">' +
                        '<a href="#" class="btn grey createTrInputDel">-</a></div></td></tr>'
                    thisAppendArea.append(copyParam);
                    paramCnt++;
                } else if ($(this).hasClass("api-request")) {
                    const copyRequest = '<tr><td colspan="2"><div class="ipt_box">' +
                        '<input type="text" placeholder="value" name="request[' + requestCnt + '][value]">' +
                        '</div></td><td><div class="ipt_box type-flex">' +
                        '<input type="text" placeholder="Description" name="request[' + requestCnt + '][desc]">' +
                        '<a href="#" class="btn grey createTrInputDel">-</a></div></td></tr>'
                    thisAppendArea.append(copyRequest);
                    requestCnt++;
                } else if ($(this).hasClass("api-response")) {
                    const copyResponse = '<tr><td><div class="ipt_box">' +
                        '<input type="text" placeholder="key" name="response[' + responseCnt + '][key]">' +
                        '</div></td><td><div class="ipt_box">' +
                        '<input type="text" placeholder="value" name="response[' + responseCnt + '][value]">' +
                        '</div></td><td><div class="ipt_box type-flex">' +
                        '<input type="text" placeholder="Description" name="response[' + responseCnt + '][desc]">' +
                        '<a href="#" class="btn grey createTrInputDel">-</a></div></td></tr>'
                    thisAppendArea.append(copyResponse);
                    responseCnt++;
                }

                $('.createTrInputDel').on('click', function (e) {
                    e.preventDefault();
                    $(this).parents('tr').remove();
                })
            })
        });
    },

    urlSelect: function (url) {
        if (url === 'GET') {
            $("#apiPostBodyContents").hide();
            $("#urlSelect").val(url).niceSelect('update');
        } else if (url === "POST") {
            $("#apiPostBodyContents").show();
            // select 값 매칭 시 .niceSelect('update') 해줘야함
            $("#urlSelect").val(url).niceSelect('update');
        } else {
            $("#apiPostBodyContents").hide();
            $("#urlSelect").val("GET").niceSelect('update');
        }
    },

    handleChange: function (field, value) {
        currentNode[field] = value;
    },
};

$(document).ready(function () {
    // 버튼 이벤트 실행


    if ($.utils.isBlank($("#apiSeq").val())) { // 생성
        ViewEvent.insertRow();
        ViewEvent.btnEvent();
        ViewEvent.urlSelect();
        ReqEvent.reqGetOpr();
        $("#apiNodeTitle").text("API Node 생성");
        flag = "insert";
    } else { // 수정
        ReqEvent.reqGetApiNode($("#apiSeq").val());
        $("#apiNodeTitle").text("API Node 편집");
        flag = "update";
    }
});

