<!DOCTYPE html>
<html lang="ko"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layouts/layout}"
>

<head></head>

<!-- Begin Page Content -->
<div layout:fragment="content" class="container-fluid">

    <!-- Page Heading -->
    <h1 class="h3 mb-2 text-gray-800">category </h1>
    <p class="mb-4"> 버튼을 눌러 카테고리 등록</p>



    <div class="row">

        <div class="col-xl-12">
            <a href="#" class="btn btn-info btn-icon-split" data-toggle="modal" data-target="#myModal" >

                                        <span class="icon text-white-50">
                                            <i class="fas fa-info-circle"></i>
                                        </span>
                <span class="text">카테고리 생성</span>
            </a>
        </div>
    </div>

    <!-- 카테고리 Modal -->
    <div class="modal fade "  id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel">category 등록</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>

                </div>
                <div class="modal-body">


                    <div class="row">
                        <div class="col-8">
                            <h2>Category List </h2>
                            <ul id="categoryList" class="list-group border border-info">
                                <li class="list-group-item d-flex justify-content-between align-items-center" role="button">
                                    <span class="list-element" contenteditable="true" data-value="1"> A list item</span>
                                    <span class="badge badge-danger badge-pill remove-element" role="button" >삭제</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="row m-2 text-right">
                        <div class="col-8">
                            <a id="btn_addCategory" href="#" class="btn btn-primary btn-icon-split">
                                <span class="icon text-white-50">
                                    <i class="fas fa-plus"></i>
                                </span>
                            </a>
                            <a id="btn_save" href="#" class="btn btn-success btn-icon-split">
                                <span class="icon text-white-50">
                                    <i class="fas fa-save"></i>
                                </span>
                            </a>
                        </div>
                    </div>



                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">닫기</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let deletedList =[];

        function init(){
            dragInit();
            $(document).on("click","#btn_addCategory",function (){clickAddCategory();})
            $(document).on("click","#btn_save",function (){clickSave();})
            $(document).on("dblclick",".list-element",function(){ dblclickCategoryList(this);})
            $(document).on("keydown",".list-element",function (event){
                if (event.keyCode == 13) $("#btn_addCategory").focus()
            })
            $(document).on("click",".remove-element",function(){ clickRemoveElement(this);})
            $('#myModal').on('shown.bs.modal', function () { initCategoryList(); })
        }
        function initCategoryList(){
            $("#categoryList").empty();
            deletedList = [];
            $.ajax({
                type: 'get'
                , url: '/store-service/category'
                , success: function (ajaxData, status, request) {
                    console.log(ajaxData)

                    $(ajaxData.data).each(function (index,element) {
                        $("#categoryList").append("<li class=\"list-group-item d-flex justify-content-between align-items-center\" role=\"button\">\n" +
                            "                                    <span class=\"list-element\" contenteditable=\"true\"  data-id=\""+element.categoryId+"\" >"+element.name+"</span>\n" +
                            "                                    <span class=\"badge badge-danger badge-pill remove-element \" role=\"button\" >삭제</span>\n" +
                            "                                </li>");

                    });


                }
            });

        }

        function dragInit(){
            $( "#categoryList" ).sortable({
                revert: true,
                revertDuration: 150
            });
        }

        function clickAddCategory(){
            $("#categoryList").append("<li class=\"list-group-item d-flex justify-content-between align-items-center\" role=\"button\">\n" +
                "                                    <span class=\"list-element\" contenteditable=\"true\" > A list item</span>\n" +
                "                                    <span class=\"badge badge-danger badge-pill remove-element \" role=\"button\" >삭제</span>\n" +
                "                                </li>");

        }
        function clickSave(){
            let categoryArr =[];
            let order = 1;
            $("#categoryList li .list-element").each(function (index,element) {
                let category = {
                    categoryId : $(element).attr('data-id'),
                    name : $(element).text(),
                    order : order++
                }
                categoryArr.push(category)
            });


            let data = {
                storeId : "1",
                categoryList: categoryArr,
                deletedList: deletedList
            }

            console.log(data)

            $.ajax({
                type: 'put'
                , async: true
                , url: '/store-service/category'
                , data: JSON.stringify(data)
                ,dataType : "text"
                , beforeSend: function(xhr) {
                    xhr.setRequestHeader("Content-type","application/json; charset=utf-8");
                }
                , success: function (ajaxData, status, request) {
                    alert("저장 성공");
                }
                , error: function(request, status, err) {
                    alert("저장 실패");
                }
                , complete: function(request, status) { }
            });
            $("#myModal").modal('toggle');
        }

        function dblclickCategoryList(ele) {
            $(ele).focus();

            const newRange = document.createRange();
            newRange.setStart(ele, 1);
            newRange.setEnd(ele, 1);

            const selection = document.getSelection();
            selection.removeAllRanges();
            selection.addRange(newRange);
        }
        function clickRemoveElement(item){

            let category = {
                categoryId : $(item).parent().children(".list-element").attr('data-id'),
                name : $(item).parent().children(".list-element").text(),
                order:""
            }
            deletedList.push(category)
            $(item).parent().remove();
        }



    </script>
</div>


</html>