<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");

if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    sleep(1);
    header("Location:" . $WebSite . "login/login_form.php");
    exit;
}

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
$title_message = '단가 대량 업로드';
?>

<title> <?=$title_message?> </title>
</head>
<body>
<div class="container-fluid">
    <div class="card-header">
        <h6>
            <?=$title_message?>
            &nbsp;&nbsp;
            <button type="button" class="btn btn-dark btn-sm" id="savegridBtn">
                <i class="bi bi-check-square-fill"></i> 일괄등록 실행
            </button>
            &nbsp;&nbsp;&nbsp;
            <button type="button" class="btn btn-dark btn-sm" onclick="self.close();">
                <i class="bi bi-x-lg"></i> 창닫기
            </button>
            &nbsp;
        </h6>
    </div>

    <form name="regform" id="regform" method="post">
        <input type="hidden" id="tablename" name="tablename" value="KDunitprice">
        <input type="hidden" id="col1" name="col1[]">
        <input type="hidden" id="col2" name="col2[]">
        <input type="hidden" id="col3" name="col3[]">
        <input type="hidden" id="col4" name="col4[]">
        <input type="hidden" id="col5" name="col5[]">
        <input type="hidden" id="col6" name="col6[]">

        <div class="card mt-2 mb-2">
            <div class="card-body">
                <div class="input-group p-2 mb-2">
                    <span style="margin-left:20px;font-size:20px;color:blue;">
                        ※ 해당 셀 엑셀 내용을 복사 후 붙여넣기 (품목코드, 품목명, 품목구분, 규격, 단위, 단가)
                    </span>
                </div>
                <div class="d-flex mt-2 mb-2">
                    <div id="grid" style="width:100%;"></div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
$(document).ready(function() {
    var loader = document.getElementById('loadingOverlay');
    if (loader) loader.style.display = 'none';

    const data = [];
    const rowNum = 1000;
    for (let i = 0; i < rowNum; i++) {
        data.push({
            col1: '', col2: '', col3: '', col4: '', col5: '', col6: ''
        });
    }

    class CustomTextEditor {
        constructor(props) {
            const el = document.createElement('input');
            const { maxLength } = props.columnInfo.editor.options;
            el.type = 'text';
            el.maxLength = maxLength;
            el.value = String(props.value);
            this.el = el;
        }
        getElement() { return this.el; }
        getValue() { return this.el.value; }
        mounted() { this.el.select(); }
    }

    const grid = new tui.Grid({
        el: document.getElementById('grid'),
        data: data,
        bodyHeight: 600,
        columns: [
            { header: '품목코드', name: 'col1', width: 120, editor: { type: CustomTextEditor, options: { maxLength: 50 } }, align: 'center' },
            { header: '품목명', name: 'col2', width: 200, editor: { type: CustomTextEditor, options: { maxLength: 100 } }, align: 'center' },
            { header: '품목구분', name: 'col3', width: 100, editor: { type: CustomTextEditor, options: { maxLength: 20 } }, align: 'center' },
            { header: '규격', name: 'col4', width: 100, editor: { type: CustomTextEditor, options: { maxLength: 50 } }, align: 'center' },
            { header: '단위', name: 'col5', width: 80, editor: { type: CustomTextEditor, options: { maxLength: 10 } }, align: 'center' },
            { header: '단가', name: 'col6', width: 120, editor: { type: CustomTextEditor, options: { maxLength: 20 } }, align: 'right' }
        ],
        columnOptions: { resizable: true }
    });

    tui.Grid.applyTheme('default', {
        cell: {
            normal: { background: '#fff', border: '#ccc', showVerticalBorder: true },
            header: { background: '#eee', border: '#ccc', showVerticalBorder: true },
            editable: { background: '#fbfbfb' },
            focused: { border: '#418ed4' }
        }
    });

    function swapcommatopipe(str) {
        return str.replace(/,/g, '|');
    }

    function savegrid() {
        const col1 = [], col2 = [], col3 = [], col4 = [], col5 = [], col6 = [];
        const maxCount = grid.getRowCount();
        for (let i = 0; i < maxCount; i++) {
            const v1 = grid.getValue(i, 'col1');
            if (v1 !== null && v1 !== '') {
                col1.push(swapcommatopipe(grid.getValue(i, 'col1')));
                col2.push(swapcommatopipe(grid.getValue(i, 'col2')));
                col3.push(swapcommatopipe(grid.getValue(i, 'col3')));
                col4.push(swapcommatopipe(grid.getValue(i, 'col4')));
                col5.push(swapcommatopipe(grid.getValue(i, 'col5')));
                col6.push(swapcommatopipe(grid.getValue(i, 'col6')));
            }
        }
        $('#col1').val(col1);
        $('#col2').val(col2);
        $('#col3').val(col3);
        $('#col4').val(col4);
        $('#col5').val(col5);
        $('#col6').val(col6);

        $.ajax({
            url: "upload.php",
            type: "post",
            data: $("#regform").serialize(),
            dataType: "json",
            success: function(data) {
                Swal.fire('완료', '데이터가 성공적으로 등록되었습니다.', 'success');
            },
            error: function(jqxhr, status, error) {
                console.log(jqxhr, status, error);
            }
        });
    }

    $("#savegridBtn").click(function() {
        savegrid();
    });
});
</script>
</body>
</html>
