<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/include/tags.jspf"%>

<section class="content-header">
    <tg:menuInfoTag />
</section>

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box box-success">
                <div class="box-header">
                    <h3 class="box-title"><i class='material-icons' style='font-size:16px;'>play_arrow</i>&nbsp;&nbsp;검색조건</h3>
                </div>
                <div class="box-body">
                    <div class="row">
                        <div class="col-md-4 col-xs-12" style="margin-bottom: 10px;">
                            <div class="input-group">
                                <span class="input-group-addon">제품명</span>
                                <input type="text" id="prodNmLike" class="form-control" placeholder="제품명 입력" maxlength="50">
                            </div>
                        </div>
                        <div class="col-md-4 col-xs-12" style="margin-bottom: 10px;">
                            <div class="input-group">
                                <span class="input-group-addon">제형</span>
                                <select id="prodTyLike" class="form-control selectpicker">
                                    <option value="">전체</option>
                                    <c:forEach var="prodTy" items="${prodTyList}">
                                        <option value="${prodTy.cdDtlId}">${prodTy.cdDtlNm}</option>
                                    </c:forEach>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4 col-xs-12" style="margin-bottom: 10px;">
                            <div class="input-group">
                                <span class="input-group-addon">사용여부</span>
                                <select id="recStLike" name="recStLike" class="form-control selectpicker">
                                    <option value="" selected>전체</option>
                                    <option value="Y">사용</option>
                                    <option value="N">사용안함</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="box-footer">
                    <div class="btn-group pull-right">
                        <button type="button" class="btn btn-outline-primary" id="searchBtn">검색</button>
                        <button type="button" class="btn btn-outline-primary" id="resetBtn">리셋</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="box box-primary">
                <div class="box-body">
                    <table id="datatable" class="table table-bordered table-striped" style="width:100%; table-layout:fixed;"></table>
                </div>
                <div class="box-footer">
                    <div class="btn-group pull-right">
                        <button type="button" class="btn btn-outline-primary" onclick="showInsertModal()">등록</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade func-modal" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 id="func-modal-title"></h2>
                </div>
                <div class="modal-body">
                    <form id="funcForm" name="funcForm" class="form-horizontal" enctype="multipart/form-data" method="post">
                        <input type="hidden" name="prodId" />
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">제품코드<span>*</span></label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <input type="text" name="prodCd" class="form-control col-md-7 col-sm-7 col-xs-12" placeholder="제품코드를 입력해주세요." maxlength="50">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">제품명<span>*</span></label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <input type="text" name="prodNm" class="form-control col-md-7 col-sm-7 col-xs-12" placeholder="제품명을 입력해주세요." maxlength="50">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">제품분류<span>*</span></label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <select name="prodTy" class="form-control col-md-7 col-sm-7 col-xs-12 selectpicker">
                                    <option value="">전체</option>
                                    <c:forEach var="prodTy" items="${prodTyList}">
                                        <option value="${prodTy.cdDtlId}">${prodTy.cdDtlNm}</option>
                                    </c:forEach>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">제품용량<span>*</span></label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <input type="text" name="prodCpcty" class="form-control col-md-7 col-sm-7 col-xs-12" placeholder="제품용량을 입력해주세요.(ml)" maxlength="50">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">제품단가<span>*</span></label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <input type="text" name="prodPrc" class="form-control col-md-7 col-sm-7 col-xs-12" placeholder="제품단가를 입력해주세요.(원)" maxlength="50">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">제품상태</label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <select name="prodSt" class="form-control col-md-7 col-sm-7 col-xs-12 selectpicker">
                                    <option value="Y" selected>정상판매</option>
                                    <option value="O">품절</option>
                                    <option value="N">판매중단</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">진열여부</label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <select name="showSt" class="form-control col-md-7 col-sm-7 col-xs-12 selectpicker">
                                    <option value="Y" selected>진열</option>
                                    <option value="N">미진열</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">사용여부</label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <select name="recSt" class="form-control col-md-7 col-sm-7 col-xs-12 selectpicker">
                                    <option value="Y" selected>사용</option>
                                    <option value="N">사용안함</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">피부타입</label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <textarea name="skTy" class="form-control col-md-7 col-sm-7 col-xs-12" rows="2" placeholder="바우만타입을 입력해주세요."></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">성분</label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <textarea name="prodIrdnt" class="form-control col-md-7 col-sm-7 col-xs-12" rows="5" placeholder="전성분을 입력해주세요."></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">설명</label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <textarea name="prodDtl" class="form-control col-md-7 col-sm-7 col-xs-12" rows="5" placeholder="제품을 설명해주세요."></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">해시태그</label>
                            <div class="col-md-8 col-sm-8 col-xs-12">
                                <input type="text" name="prodHashtag" class="form-control col-md-7 col-sm-7 col-xs-12" placeholder="#건성 #수분필요" maxlength="50">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12">제품이미지<span>*</span></label>
                            <div class="col-md-8 col-sm-8 col-xs-12 filebox">
                                <input type="text" class="upload-name form-control" value="파일선택" disabled="disabled">
                                <label for="uploadFile">업로드</label>
                                <input type="file" id="uploadFile" name="uploadFile" class="upload-hidden" accept="image/*" onchange="fileCheck(this)">
                            </div>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary" onclick="save()">저장</button>
                    <button type="button" class="btn btn-outline-primary" data-dismiss="modal">닫기</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade detail-modal" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>제품정보 상세보기</h2>
                </div>
                <div class="modal-body">
                    <form id="detailForm" name="detailForm" class="form-horizontal form-label-left">
                        <table class="board_write">
                            <tbody>
                                <tr class="column-resize-height">
                                    <td rowspan="7"><div id="prodImage" style="width: auto; height: 205px;"></div></td>
                                </tr>
                                <tr class="column-resize-height">
                                    <th>제품코드</th>
                                    <td colspan="3"><div id="prodCd"></div></td>
                                </tr>
                                <tr class="column-resize-height">
                                    <th>제품명</th>
                                    <td colspan="3"><div id="prodNm"></div></td>
                                </tr>
                                <tr>
                                    <th>제품분류</th>
                                    <td><div id="prodTyNm"></div></td>
                                    <th>사용여부</th>
                                    <td><div id="recSt"></div></td>
                                </tr>
                                <tr>
                                    <th>제품용량</th>
                                    <td><div id="prodCpcty"></div></td>
                                    <th>제품가격</th>
                                    <td><div id="prodPrc"></div></td>
                                </tr>
                                <tr class="column-resize-height">
                                    <th>성분</th>
                                    <td colspan="3" style="text-align: left;"><div id="prodIrdnt"></div></td>
                                </tr>
                                <tr>
                                    <th>제품상태</th>
                                    <td><div id="prodStNm"></div></td>
                                    <th>진열여부</th>
                                    <td><div id="showSt"></div></td>
                                </tr>
                            </tbody>
                        </table>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary" data-dismiss="modal">닫기</button>
                </div>
            </div>
        </div>
    </div>
</section>

<script>

    var datatable;
    $(document).ready(function() {

        var fileTarget = $('.filebox .upload-hidden');
        fileTarget.on('change', function () {
            if(window.FileReader){
                var filename = $(this)[0].files[0].name;
            } else {
                var filename = $(this).val().split('/').pop().split('\\').pop();
            }
            $(this).siblings('.upload-name').val(filename);
        });

        datatable = $("#datatable").DataTable({
            "searching": false
            ,"paging": true
            ,"bPaginate": true
            ,"responsive": true
            ,"language": lang_kor
            ,"ajax" : {
                "url" : "<c:url value='/system/prod/list.json' />"
                ,"method" : "post"
                ,"data" : function(d) {
                    d.prodNmLike = $('#prodNmLike').val(),
                    d.prodTyLike = $('#prodTyLike').val(),
                    d.recSt = $('#recStLike').val()
                }
            },"processing": true
            ,"serverSide": true
            ,"order": [4, 'desc']
            ,"columns": [
                { "name" : "PROD_TY_NM", "title" : "제형", "data" : "prodTyNm", "className" : "dt-head-center"},
                { "name" : "PROD_NM", "title" : "제품명", "data" : "prodNm", "className" : "dt-head-center"},
                { "render" :
                        function (data, type, row) {
                            var html = "";
                            if(row["recSt"] == 'Y'){ html += "사용"; }
                            if(row["recSt"] == 'N'){ html += "사용안함"; }
                            return html;
                        },
                    "className": "dt-head-center", "title": "사용 여부"
                },
                { "name" : "REG_NM", "title" : "등록인", "data" : "regNm", "className" : "dt-head-center dt-body-left"},
                { "name" : "REG_DT", "title" : "등록일시", "data" : "regDt", "className" : "dt-head-center dt-body-center", "render" :
                        function (data, type, row) {
                            return new Date(row["regDt"]).format("yyyy-MM-dd HH:mm:ss");
                        }
                },
                { "render" :
                        function (data, type, row) {
                            var html = "";
                            html += "<button type='button' class='btn btn-sm btn-outline-primary' onclick='showUpdateModal(\""+row["prodId"]+"\")'>수정</button>&nbsp;";
                            html += "<button type='button' class='btn btn-sm btn-outline-primary' onclick='detailModal(\""+row["prodId"]+"\")'>상세</button>";
                            return html;
                        },
                    "className": "dt-head-center", "title":"기능", "orderable" : false
                }
            ]
            ,"scrollX": "100%"
            ,"columnDefs": [
                {"targets": [0], width:"100px"}
                ,{"targets": [1], width:"200px"}
                ,{"targets": [2], width:"100px"}
                ,{"targets": [3], width:"100px"}
                ,{"targets": [4], width:"150px"}
                ,{"targets": [5], width:"100px"}
            ]
        });
    });

    $("#searchBtn").click(function() {
        datatable.ajax.reload();
    });

    $("#resetBtn").click(function() {
        $("#prodNmLike").val("");
        $("#prodTyLike").val("");
        $("#prodTyLike").selectpicker("refresh");
        $("#recStLike").val("");
        $("#recStLike").selectpicker("refresh");
        datatable.ajax.reload();
    });

    function showInsertModal() {
        var form = document.funcForm;
        form.prodId.value = "";
        form.prodCd.value = "";
        form.prodNm.value = "";
        form.prodTy.value = "";
        $('[name=prodTy]').selectpicker("refresh");
        form.prodCpcty.value = "";
        form.prodPrc.value = "";
        form.prodSt.value = "";
        $('[name=prodSt]').selectpicker("refresh");
        form.showSt.value = "";
        $('[name=showSt]').selectpicker("refresh");
        form.recSt.value = "";
        $('[name=recSt]').selectpicker("refresh");
        form.skTy.value = "";
        form.prodIrdnt.value = "";
        form.prodDtl.value = "";
        form.prodHashtag.value = "";
        form.uploadFile.value = "";
        $('.upload-name').val('파일선택');

        $("#func-modal-title").html("등록");
        $('.func-modal').modal("show");
    }

    function showUpdateModal(prodId) {
        $('.upload-name').val("파일선택");

        $.ajax({
            url : "<c:url value='/system/prod/detail.json' /> ",
            type : "POST",
            data : {
                "prodId" : prodId
            },
            dataType : "json",
            success : function(res){
                if(res.result == "success"){
                    var form = document.funcForm;
                    var data = res.data;
                    form.prodId.value = data.prodId;
                    form.prodCd.value = data.prodCd;
                    form.prodNm.value = data.prodNm;
                    form.prodTy.value = data.prodTy;
                    $('[name=prodTy]').selectpicker("refresh");
                    form.prodCpcty.value = data.prodCpcty;
                    form.prodPrc.value = data.prodPrc;
                    form.prodSt.value = data.prodSt;
                    $('[name=prodSt]').selectpicker("refresh");
                    form.showSt.value = data.showSt;
                    $('[name=showSt]').selectpicker("refresh");
                    form.recSt.value = data.recSt;
                    $('[name=recSt]').selectpicker("refresh");
                    form.skTy.value = data.skTy;
                    form.prodIrdnt.value = data.prodIrdnt;
                    form.prodDtl.value = data.prodDtl;
                    form.prodHashtag.value = data.prodHashtag;

                    if(data.imageDir != null && data.prodImage != null) {
                        $('.upload-name').val(data.prodImage);
                    }

                    $("#func-modal-title").html("수정");
                    $('.func-modal').modal("show");
                }else {
                    alert(res.message);
                }
            }
        })
    }

    function detailModal(prodId) {
        $.ajax({
            url : "<c:url value='/system/prod/detail.json' /> ",
            type : "POST",
            data : {
                "prodId" : prodId
            },
            dataType : "json",
            success : function(res){
                if(res.result == "success"){
                    let data = res.data;
                    $('#prodId').html(data.prodId);
                    $('#prodCd').html(data.prodCd);
                    $('#prodNm').html(data.prodNm);
                    $('#prodTyNm').html(data.prodTyNm);
                    if(data.recSt == "Y") {
                        $('#recSt').html("사용");
                    } else {
                        $('#recSt').html("사용안함");
                    }
                    $('#prodCpcty').html(data.prodCpcty+"ml");
                    $('#prodPrc').html(data.prodPrc+"원");
                    $('#prodIrdnt').html(data.prodIrdnt);
                    $('#prodStNm').html(data.prodStNm);
                    if(data.showSt == "Y") {
                        $('#showSt').html("진열");
                    } else {
                        $('#showSt').html("미진열");
                    }

                    $('#prodImage').html("<img src=/clfd/image/"+data.imageDir+"_"+data.prodImage+" style='object-fit: contain;'>");

                    $('div.detail-modal').modal("show");
                } else {
                    alert(res.message);
                }
            }
        })
    }

    function save() {
        let form = document.funcForm;
        if(form.prodNm.value == "") {
            alert("제품명을 입력해주세요.");
            form.prodNm.focus();
        } else if(form.prodTy.value == "") {
            alert("제형을 선택해주세요.");
            form.prodTy.focus();
        } else if($('.upload-name').val() == "파일선택"){
            alert("제품이미지를 업로드해주세요.");
        } else if(form.prodId.value == "") {
            if(confirm("해당 제품을 등록하시겠습니까?")){
                let funcForm = $('#funcForm')[0];
                let data = new FormData(funcForm);
                $.ajax({
                    url: "<c:url value='/system/prod/insert.json' />",
                    type: "POST",
                    enctype: "multipart/form-data",
                    data: data,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if(res.result == "success"){
                            alert("등록되었습니다.");
                            $('.func-modal').modal("hide");
                            datatable.ajax.reload();
                        } else {
                            alert(res.message);
                        }
                    }
                })
            }
        } else {
            if(confirm("해당 제품을 수정하시겠습니까?")){
                let funcForm = $('#funcForm')[0];
                let data = new FormData(funcForm);
                $.ajax({
                    url: "<c:url value='/system/prod/update.json' />",
                    type: "POST",
                    enctype: "multipart/form-data",
                    data: data,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if(res.result == "success"){
                            alert("수정되었습니다.");
                            $('.func-modal').modal("hide");
                            datatable.ajax.reload();
                        } else {
                            alert(res.message);
                        }
                    }
                })
            }
        }
    }

    function fileCheck(obj){
        if(!/\.(jpeg|jpg|png|gif|bmp)$/i.test(obj.value)){
            alert('이미지 파일만 업로드 가능합니다.');
            $('.upload-name').val('파일선택');
            obj.value = '';
            obj.focus();
        }
    }

</script>
