<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>시나리오코드</title>
    <%@ include file="/WEB-INF/jsp/adm/include/topLinkTag.jsp" %>
</head>

<script>
    $(document).ready(function () {
            //내가사용할수있는 서비스그룹조회
            getOprService();

            //데이터테이블
            PagingDataTable();

            //리스트더블클릭
            $('#listTable tbody').on('dblclick', 'tr', function () {
                // $('#listTable tbody').on('dblclick', function () {
                var data = $('#listTable').DataTable().row(this).data();

                // $("#reg_edit_modal").modal("show");
                // $("#modifyCommonCodeModal").show();

                // $("#reg_edit_modal").show();
                // createDim();

                $("#setCustCode").val(data.custCode);
                $("#setServiceGroupName").val(data.serviceGroupName);
                $("#setServiceGroup").val(data.serviceGroup);
                $("#setOprMngCode").val(data.oprMngCode);
                $("#setMajorCode").val(data.majorCode);
                $("#setMinorCode").val(data.minorCode);
                $("#setCodeName").val(data.codeName);
                $("#setAttribute1").val(data.attribute1);
                $("#setAttribute2").val(data.attribute2);
                $("#setAttribute3").val(data.attribute3);
            });

            // $("#reg_edit_modal a.close").on('click', function () {
            //     $("#reg_edit_modal").hide();
            //     removeDim();
            // })

            // 데이터테이블 AJAX 리로드
            $('#btnSearchOpr').on('click', function () {
                fnCustSearchBtn();
            });

            //엔터입력
            $("#Content").on("keyup", function (key) {
                if (key.keyCode == 13) {
                    fnCustSearchBtn();
                }
            });

            //신규모달
            $('#btn_reg_modal').on('click', function () {
                $('#serviceInfo').reset();
                $('#serviceGroupModal').val('ALL').niceSelect('update');
            });

            // 신규 공통 코드 저장
            $('#btnSaveCust').on('click', function () {
                fncCreateCustInfo();
            });

            //수정모달
            $('#btnEditCust').on('click', function () {
                fncUpdateCommonCode();
            });

            //수정모달 삭제 버튼
            $('#btnDelCust').on('click', function () {
                fncDeleteCommonCode();
            });

        // $('#listTable').on('page.dt', function(){
        //     // var info = table.page.info();
        //     // console.log( 'Showing page: '+info.page+' of '+info.pages );
        //     // console.log( 'Showing page: ' );
        //     modalUi();
        // });

        }
    );

    function fncUpdateCommonCode() {
        var json = {};
        var custCode = $("#setCustCode").val();
        var serviceGroupName = $("#setServiceGroupName").val();
        var serviceGroup = $("#setServiceGroup").val();
        var oprMngCode = $("#setCustCode").val() + "_RCP_" + $("#setServiceGroup").val();
        var majorCode = $("#setMajorCode").val();
        var minorCode = $("#setMinorCode").val();
        var codeName = $("#setCodeName").val();
        var attribute1 = $("#setAttribute1").val();
        var attribute2 = $("#setAttribute2").val();
        var attribute3 = $("#setAttribute3").val();

        json.custCode = custCode;
        json.serviceGroupName = serviceGroupName;
        json.serviceGroup = serviceGroup;
        json.oprMngCode = oprMngCode;
        json.majorCode = majorCode;
        json.minorCode = minorCode;
        json.codeName = codeName;
        json.attribute1 = attribute1;
        json.attribute2 = attribute2;
        json.attribute3 = attribute3;
        // console.log(JSON.stringify(json));

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/oprmngcode/update'/>",
            data: JSON.stringify(json),
            // success: function (data) {
            //     return swalAlert('success', '저장');
            // }
        }).complete(function (data) {
            if (data.status == 200) {
                $.utils.success('정상적으로 저장되었습니다.');
                removeDim();
                $('#reg_edit_modal a.close').trigger('click');
                fnCustSearchBtn();
                //document.location.href = "<c:url value='/admin/common/system/oprmngcode/manage.do'/>";
            }
            if (data.status == 400) {
                $.utils.warning("실패하였습니다..");
                // $.utils.success('정상적으로 저장되었습니다.');
            }
            if (data.status == 404) {
                $.utils.warning("변경 사항이 없습니다.");
            }

        });
    }

    function fncDeleteCommonCode(){
        var json = {};
        var majorCode = $("#setMajorCode").val();
        var custCode = $("#setCustCode").val();
        var serviceGroup = $("#setServiceGroup").val();
        var minorCode = $("#setMinorCode").val();

        json.custCode = custCode;
        json.serviceGroup = serviceGroup;
        json.majorCode = majorCode;
        json.minorCode = minorCode;

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/oprmngcode/delete'/>",
            data: JSON.stringify(json),
        }).complete(function (data) {
            if (data.status == 200) {
                $.utils.success('정상적으로 삭제되었습니다.');
                $('#reg_edit_modal a.close').trigger('click');
                fnCustSearchBtn();
            }
            if (data.status == 400) {
                $.utils.warning("실패하였습니다..");
            }
        });
    }


    //내 서비스그룹 조회
    function getOprService() {
        var html = '<option value="' + "ALL" + '">' + "선택" + '</option>';
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/adm/menu/oprmng'/>"
                // + "?serviceType=S"
            ,
            success: function (data) {
                data.forEach(function (e, f) {
                    html += '<option value="' + e.serviceGroup + '">' + e.serviceGroupName + '</option>';
                });
            }
        })

        $('#serviceGroup').html(html);
        $('#serviceGroup').niceSelect('update');
        $('#serviceGroupModal').html(html);
        $('#serviceGroupModal').niceSelect('update');

    };

    // 신규 공통 코드 저장
    function fncCreateCustInfo() {
        /*if ($("#codeTypeModal option:selected").val() == "C_CD"){
            getOprServiceCommon();
        }*/
        var json = {};
        json.custCode = $("#insertCustCode").val();
        json.serviceGroup = $("#serviceGroupModal option:selected").val();
        json.major = $('#insertMajorCode').val();
        json.minor = $('#insertMinorCode').val();
        json.codeName = $('#insertCodeName').val();
        json.attribute1 = $('#insertAttribute1').val();
        json.attribute2 = $('#insertAttribute2').val();
        json.attribute3 = $('#insertAttribute3').val();
        // console.log(JSON.stringify(json));

        if (json.serviceGroup == 'ALL') {
            $.utils.warning("시나리오그룹을 선택해주세요.");
            // $.utils.success('정상적으로 저장되었습니다.');
            // alert('시나리오그룹을 선택해주세요');
        } else if (json.major.trim() == '') {
            $.utils.warning("대분류는 필수 항목입니다.");
            // alert('대분류는 필수 항목입니다.');
        } else if (json.minor.trim() == '') {
            $.utils.warning("중분류는 필수 항목입니다.");
            // alert('중분류는 필수 항목입니다.');
        } else {
            $.utils.success('정상적으로 등록되었습니다.');
            insertCommonCode(json);
        }
    }

    // 권한 신규등록
    function insertCommonCode(json) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/oprmngcode/insert'/>",
            data: JSON.stringify(json),
            // success: function (data) {
            //     return swalAlert('success', '저장');
            // }
        }).complete(function (data) {
            if (data.status == 200) {
                $('#reg_modal a.close').trigger('click');
                fnCustSearchBtn()
            }
            if (data.status == 400) {
                $.utils.warning("이미 존재하는 코드입니다.");
                // $.utils.success('정상적으로 저장되었습니다.');
            }
        });
    }

    function updateCommonCode(json) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/oprmngcode/update'/>",
            data: JSON.stringify(json),
        }).complete(function (data) {
            if (data.status == 200) {
                $('#reg_modal a.close').trigger('click');
                fnCustSearchBtn()
            }
            if (data.status == 400) {
                $.utils.warning("이미 존재하는 코드입니다.");
                // $.utils.success('정상적으로 저장되었습니다.');
            }
        });
    }

    function viewPage(rowData) {
        document.location.href = "<c:url value='/admin/common/system/oprmngcode/view'/>", +"?custCode=" + rowData.custCode;
    }

    var PagingDataTable = function () {
        // console.log("log - " + JSON.stringify({"page": "0", "size": "10"}));
        var paging = JSON.stringify({'page': 0, 'size': 10})
        $('#listTable').DataTable(
            {
                ajax: {
                    url: "<c:url value='/admin/common/system/oprmngcode/list'/>",
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    dataType: "JSON",
                    async: false,
                    data: function (data) {
                        var json = {};
                        if (data) {
                            json.page = data.start / data.length;
                            json.size = 10;
                            json.serviceGroup = $("#serviceGroup option:selected").val();
                            json.codeText = $('#codeText').val();
                            json.codeType = $("#codeType option:selected").val();
                        } else {
                            json = JSON.stringify({'page': 0, 'size': 10});
                        }
                        return JSON.stringify(json);
                    }
                    ,
                    dataFilter: function (data) {
                        var jsons = jQuery.parseJSON(data);
                        var json = {};
                        json.recordsTotal = jsons.getTotal;
                        json.recordsFiltered = jsons.getTotal;
                        json.data = jsons.getList;
                        // console.log(json);
                        return JSON.stringify(json);
                    }
                },
                columns: [
                    {data: "custCode"},
                    {data: "serviceGroupName"},
                    {data: "serviceGroup"},
                    {data: "oprMngCode"},
                    {data: "majorCode"},
                    {data: "minorCode"},
                    {data: "codeName"},
                    {data: "attribute1"},
                    {data: "attribute2"},
                    {data: "attribute3"}
                ],
                order: [0, "asc"],
                scrollX: false,
                scrollY: false,
                autoWidth: false,
                searching: false,
                bProcessing: false,
                sProcessing: false,
                bServerSide: true,
                sDom: '<"row view-filter"<"col-sm-12"<"pull-left"><"pull-right"><"clearfix">>>t<"row view-pager"<"col-sm-12"<"text-center"pi>>>',
                // pagingType: "first_last_numbers"

                createdRow: function (row, data, index) {
                    //
                    // if the second column cell is blank apply special formatting
                    //
                        console.dir(row);
                        $(row).addClass('modalLoad').attr('rel','reg_edit_modal');
                }
                ,
                columnDefs: [
                    {
                        targets: 0,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        },
                    },
                    {
                        targets: 1,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 2,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 3,
                        orderable: false,
                        render: function (data) {
                            // console.log("-- - -" + data)
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },

                    {
                        targets: 4,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 5,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 6,
                        orderable: false,
                        // visible: false,
                        // searchable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 7,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 8,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 9,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            // console.log($(this).parents("tr"));
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    }
                ],

                "drawCallback": function () {
                    modalUi();
                }
            }
        )
        // modalUi();
    };

    function fnCustSearchBtn() {
        $('#listTable').DataTable().ajax.reload();
        // modalUi();
    };

</script>


<body>
<h1>ICOMSYS ADMIN</h1>
<div class="skip_navigation">
    <ul>
        <li>
            <a href="#Content" class="go_content">본문 바로가기</a>
        </li>
        <li>
            <a href="#Gnb">메뉴 바로가기</a>
        </li>
    </ul>
</div>

<header id="header">
    <%@ include file="/WEB-INF/jsp/adm/include/header.jsp" %>
</header>
<c:import url="/adm/menu/getLnbMenu.do"/>

<section id="Content" class="system_management">
    <div class="location">
        <ul>
            <li class="home"><a href="#">HOME</a></li>
            <li><a href="#">BOT 공통 관리</a></li>
            <li><a href="#">공통 코드 관리</a></li>
        </ul>
    </div>

    <div class="sub_cont menu06_01_03">
        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">공통 코드 조회</h2>
                </div>
                <div class="fr">
                    <div class="btn_wrap fl">
                        <a href="#" id="btnSearchOpr" class="btn">조회</a>
                    </div>
                </div>
            </div>
            <div class="tbl">
                <table class="search block">
                    <colgroup>
                        <col width="140px">
                        <col width="25%">
                        <col width="140px">
                        <col width="25%">
                        <col width="140px">
                        <col width="25%">
                    </colgroup>
                    <tbody>
                    <tr>
                        <th class="tl">시나리오그룹</th>
                        <td>
                            <div class="sel_box">
                                <select id="serviceGroup" class="wide">
                                    <option value="ALL">선택</option>
                                </select>
                            </div>
                        </td>
                        <th class="tl">분류</th>
                        <td>
                            <div class="sel_box">
                                <select id="codeType" class="wide">
                                    <option value="ALL">분류 선택</option>
                                    <option value="major">대분류</option>
                                    <option value="minor">중분류</option>
                                </select>

                            </div>
                        </td>
                        <th class="tl">코드명</th>
                        <td>
                            <div class="ipt_box listen">
                                <input type="text" placeholder="검색어를 입력하세요" id="codeText" name="typeText">
                            </div>
                        </td>
                    </tr>

                    </tbody>
                </table>
            </div>
        </div>
        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">공통 코드 리스트</h2>
                </div>
                <div class="btn_wrap fr">
                    <%--                    <a href="#" class="btn grey" id="btnDelCust">삭제</a>--%>
                    <a href="#" rel="reg_modal" id="btn_reg_modal" class="btn line modalLoad">등록</a>
                </div>
            </div>


            <div class="tbl">
                <form id="custListForm">
                    <table id="listTable" class="">
                        <colgroup>
                            <col width="15%">
                            <col width="15%">
                            <col width="15%">
                            <col width="15%">
                            <col width="15%">
                            <col width="auto">
                        </colgroup>
                        <thead>
                        <tr>
                            <th>고객사</th>
                            <th>시나리오그룹명</th>
                            <th>서비스코드</th>
                            <th>시나리오그룹코드</th>
                            <th>대분류</th>
                            <th>중분류</th>
                            <th>설명</th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </form>
            </div>
        </div>
    </div>
</section>
<div class="modal" id="reg_modal">
    <div class="modal_header">
        <h3>공통 코드 신규등록</h3>
    </div>
    <div class="modal_body">
        <div class="modal_cont">
            <form id="serviceInfo">

                <dl>
                    <dt><h4><em class="important">시나리오그룹</em></h4></dt>
                    <dd>
                        <div class="sel_box">
                            <select id="serviceGroupModal" name="serviceGroupModal" class="wide">
                                <option value="ALL">선택</option>
                            </select>
                        </div>
                    </dd>
                </dl>

                <dl>
                    <dt><h4><em class="important">대분류</em></h4></dt>
                    <dd>
                        <div class="ipt_box">
                            <input type="text" id="insertMajorCode" name="majorCode" placeholder="대분류를 입력하세요.">
                            <input type="hidden" id="insertCustCode">
                        </div>
                    </dd>
                </dl>
                <dl>
                    <dt><h4><em class="important">중분류</em></h4></dt>
                    <dd>
                        <div class="ipt_box">
                            <input type="text" id="insertMinorCode" name="minorCode" placeholder="중분류를 입력하세요.">
                        </div>
                    </dd>
                </dl>

                <dl class="">
                    <dt><h4><em class="">속성1</em></h4></dt>
                    <dd>
                        <input type="text" id="insertAttribute1"></input>
                    </dd>
                </dl>
                <dl class="">
                    <dt><h4><em class="">속성2</em></h4></dt>
                    <dd>
                        <input type="text" id="insertAttribute2"></input>
                    </dd>
                </dl>
                <dl class="">
                    <dt><h4><em class="">속성3</em></h4></dt>
                    <dd>
                        <input type="text" id="insertAttribute3"></input>
                    </dd>
                </dl>
                <dl class="">
                    <dt><h4><em class="">설명</em></h4></dt>
                    <dd>
                        <textarea name="codeName" id="insertCodeName"></textarea>
                    </dd>
                </dl>
            </form>
        </div>
    </div>
    <div class="modal_footer">
        <div class="btn_wrap fr">
            <a href="#" class="btn" id="btnSaveCust">저장</a>
        </div>
    </div>
    <div class="modal_controller">
        <a href="#" class="close">close</a>
    </div>
</div>
<!--  modal :: 공통 코드 등록 팝업 end -->

<!--  modal :: 공통 코드 수정 팝업  -->
<%--<div class="modal open" id="reg_edit_modal">--%>
<div class="modal" id="reg_edit_modal">
    <div class="modal_header">
        <h3>공통 코드 수정</h3>
    </div>
    <div class="modal_body">
        <div class="modal_cont">
            <form id="editServiceInfo">

                <dl>
                    <dt><h4><em class="">시나리오그룹명</em></h4></dt>
                    <dd>
                        <div class="ipt_box">
                            <input type="text" id="setServiceGroupName" value="" readonly>
                            <input type="hidden" id="setServiceGroup" value="" readonly>
                            <input type="hidden" id="setCustCode" value="" readonly>
                        </div>
                    </dd>
                </dl>

                <dl>
                    <%--                    <dt><h4><em class="important">대분류</em></h4></dt>--%>
                    <dt><h4><em class="">대분류</em></h4></dt>
                    <dd>
                        <div class="ipt_box">
                            <input type="text" id="setMajorCode" name="setMajorCode" value="0" readonly>
                        </div>
                    </dd>
                </dl>

                <dl>
                    <dt><h4><em class="">중분류</em></h4></dt>
                    <dd>
                        <div class="ipt_box">
                            <input type="text" id="setMinorCode" name="minorCode" value="" readonly>
                        </div>
                    </dd>
                </dl>


                <dl>
                    <dt><h4><em class="">속성1</em></h4></dt>
                    <dd>
                        <input type="text" id="setAttribute1"></input>
                    </dd>
                </dl>
                <dl>
                    <dt><h4><em class="">속성2</em></h4></dt>
                    <dd>
                        <input type="text" id="setAttribute2"></input>
                    </dd>
                </dl>
                <dl>
                    <dt><h4><em class="">속성3</em></h4></dt>
                    <dd>
                        <input type="text" id="setAttribute3"></input>
                    </dd>
                </dl>

                <dl>
                    <dt><h4><em class="">설명</em></h4></dt>
                    <dd>
                        <textarea id="setCodeName" name="codeName"></textarea>
                    </dd>
                </dl>

            </form>
        </div>
    </div>
    <div class="modal_footer">
        <div class="btn_wrap fr">
            <a href="#" id="btnDelCust" class="btn grey">삭제</a>
            <a href="#" id="btnEditCust" class="btn">저장</a>
        </div>
    </div>
    <div class="modal_controller">
        <a href="#" class="close">close</a>
    </div>
</div>
<!--  modal :: 공통 코드 수정 팝업 end -->

</body>
</html>
