<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>수집원별 가중치값 설정</title>
    <link rel="stylesheet" href="/static/css/reset.css">
    <link rel="stylesheet" href="/static/css/common.css">
    <link rel="stylesheet" href="/static/css/conf-traffic-weight.css">
    <script src="/static/js/jquery-1.10.2.min.js"></script>
    <script src="/static/js/common.js"></script>
</head>
<body>
<div class="container">
    <div class="wrap">
        <div class="top-bar">수집원별 가중치값 설정</div>
        <div class="body-wrap">
            <div class="title">교통정보 가공방식 설정</div>
            <div class="container-3">
                <div>교통정보 가공방식 : </div>
                <select id="conf_type" style="width: 300px; padding: 2px;">
                    <option value="0" th:selected="${type == 0}">0. 우선순위에 의한 가공 정보</option>
                    <option value="1" th:selected="${type == 1}">1. 수집원별 가중치에 의한 정보 가공</option>
                </select>
            </div>
            <div class="title">수집원에 대한 수집원별 가중치</div>
            <div class="container-1">
                <table class="conf-col-weightcode-table">
                    <colgroup>
                        <col width="2%">
                        <col width="10%">
                        <col width="15%">
                        <col width="15%">
                        <col width="15%">
                        <col width="15%">
                        <col width="15%">
                    </colgroup>
                    <thead>
                        <tr>
                            <th></th>
                            <th id="weightCode">가중치 코드</th>
                            <th id="gps">GPS</th>
                            <th id="utis">UTIS</th>
                            <th id="loc">지역센터</th>
                            <th id="dongbu">동부NTS</th>
                            <th id="dataResType">데이터소스유형</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr th:each="items:${list}" th:onclick="|rowClick(this, '${items.gpsCode}','${items.utisCode}','${items.locCode}','${items.dongbuCode}')|">
                            <td><input type="checkbox" style="display: none" th:value="${items.weightCode}" onchange="checkEvent(this, 'conf-col-weightcode-table')"></td>
                            <td th:text="${items.weightCode?: '-'}"></td>
                            <td th:class="${items.gpsCode == 0 ? 'gray' : ''}" th:text="${items.gpsCode == 0 ? '-': items.gps}"></td>
                            <td th:class="${items.utisCode == 0 ? 'gray' : ''}" th:text="${items.utisCode == 0 ? '-' : items.utis}"></td>
                            <td th:class="${items.locCode == 0 ? 'gray' : ''}" th:text="${items.locCode == 0 ? '-' : items.loc}"></td>
                            <td th:class="${items.dongbuCode == 0 ? 'gray' : ''}" th:text="${items.dongbuCode == 0 ? '-': items.dongbu}"></td>
                            <td th:text="${items.dataResType?: '-'}"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="title">수집원별 가중치 세부 정보</div>
            <div class="container-2">
                <div>
                    <label for="ip_weightCode">가중치 코드</label><input type="text" id="ip_weightCode" readonly>
                </div>
                <div>
                    <label for="ip_gps">GPS 수집 정보</label><input type="number" id="ip_gps" min="0" max="100">
                    <label for="ip_utis">UTIS 구간소통정보</label><input type="number" id="ip_utis" min="0" max="100">
                </div>
                <div>
                    <label for="ip_loc">지역센터 정보</label><input type="number" id="ip_loc" min="0" max="100">
                    <label for="ip_dongbu">동부 NTS</label><input type="number" id="ip_dongbu" min="0" max="100">
                </div>
                <div>
                    <label for="ip_dataResType">데이터소스 유형</label><input type="text" id="ip_dataResType">
                </div>
            </div>
            <div class="btn-box">
                <div class="save-btn" onclick="saveConfig()"><img src="/static/image/check-lg.svg" width="15" height="15" alt="설정 이미지">설정</div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
<script th:inline="javascript">
    const thArr = $('table thead tr th:not(:first)');
    const tbody = $('tbody');
    let _SearchData = /*[[${list}]]*/;
    let type = /*[[${type}]]*/;
    const columns = ['weightCode', 'gps', 'utis', 'loc', 'dongbu', 'dataResType'];
    const numberColumn = ['gps', 'utis', 'loc', 'dongbu'];
    // getTableData();

    /**
     * TODO Have Row Click After Event ??
     * Table Row Click
     * @param el this
     */
    function rowClick(el, gpsCode, utisCode, locCode, dongbuCode) {
        const selected = $('tr.on');
        if (selected[0] === el) return;
        $('tbody tr td:nth-child(1) input[type="checkbox"]:checked').prop('checked', false);
        $(el).children().eq(0).find('input[type="checkbox"]').prop('checked', true).trigger('change');
        const codeEnables  = {
            gps : gpsCode,
            utis : utisCode,
            loc : locCode,
            dongbu : dongbuCode,
        };
        $('.code0').removeClass('code0');

        columns.forEach((column, idx)=>{
            let text = $(el).children().eq((Number(idx) + 1)).text();
            const input = $('#ip_' + column);
            if (numberColumn.includes(column)) {
                if (isNaN(Number(text))) {
                    text = '';
                }
                const isHide = codeEnables[column] === '0';
                if (isHide) input.addClass('code0');
                input.prop('readonly', isHide);
            }
            input.val(text);
        });
    }


    /**
     * Api Call Table Info
     * @param data
     */
    function getTableData() {
        callApi('/api/conf/getTrafficWeightInfo', 'POST', null, callBackConfColweightcodeData, null);
    }

    /**
     * Api CallBack Table Info
     * @param res
     */
    function callBackConfColweightcodeData(res) {
        const sortArr = ['asc', 'desc'];
        sortArr.forEach((sort)=> {
            const sortEl = $('.'+ sort);
            if (sortEl.length) sortEl.toggleClass(sort)
        });

        _SearchData = res;
        drawTable(res);
    }

    /**
     * sorting method
     */
    thArr.on('click', function (e) {
        sortingData(_SearchData, drawTable, this, 'conf-col-weightcode-table');
    })

    function drawTable(data) {
        // const clickTr = $('tr.on');
        const checked = $('input[type="checkbox"]:checked');
        let checkId = "";
        if (checked.length) {
            checkId = checked.val();
        }
        tbody.empty();
        let str = "";
        if (data && data.length) {
            data.forEach((obj)=>{
                const codeEnables  = {
                    gps :    obj.gpsCode,
                    utis :   obj.utisCode,
                    loc :    obj.locCode,
                    dongbu : obj.dongbuCode,
                };
                str += `<tr onclick="rowClick(this, '${obj.gpsCode}', '${obj.utisCode}', '${obj.locCode}', '${obj.dongbuCode}')">
                           <td><input type="checkbox" value="${obj.weightCode}" style="display: none" onchange="checkEvent(this, 'conf-col-weightcode-table')"></td>`;
                columns.forEach((column)=>{
                    let className = "";
                    let value = obj[column];
                    if (numberColumn.includes(column) && codeEnables[column] === 0) {
                        className = 'gray';
                        value = '-';
                    }
                    str += `<td class="${className}">${value}</td>`;
                });
                str += '</tr>';
            })
        }
        tbody.html(str);
        if (checkId) {
            $('input[value="'+checkId + '"]').parent().parent().click();
        }
    }

    function saveConfig() {
        let updateData = {trafficWeightConfVo : null, codeValue : null};
        const rowData = getRowData();
        const codeVal = $('#conf_type').val();
        if (Number(type) === Number(codeVal) && !rowData) return alert('변경하신 데이터가 없습니다. 데이터 변경 후 설정 해주시기 바랍니다.');
        if (Number(type) !== Number(codeVal)) updateData.codeValue = codeVal;
        if (rowData) {
            let trafficWeightConfVo = {};
            let deffCnt = 0;
            let percent = 0;
            for (let key in rowData) {
                const input = $('#ip_' + key);
                const value = input.val();
                const inputData = value === '' ? null : value;
                trafficWeightConfVo[key] = inputData;
                if (rowData[key] !== inputData) {
                    deffCnt++;
                }

                if (!['weightCode', 'dataResType'].includes(key)) {
                    percent += Number(value);
                    trafficWeightConfVo[key] = Number(inputData);
                }
            }


            if (percent !== 100) {
                return alert('변경하신 가중치 합이 100 보다 크거나 작습니다.');
            }

            if (deffCnt > 0) {
                updateData.trafficWeightConfVo = trafficWeightConfVo;
            }
        }

        callApi("/api/conf/updateTrafficWeightInfo", "POST", updateData, callBackUpdateConfColweightcode, null);
    }

    /**
     * update CallBack Method
     * @param data
     */
    function callBackUpdateConfColweightcode(data) {
        if (data) {
            alert(data.msg);
            getTableData();
            getAnalysisType();
        }
    }

    function getAnalysisType() {
        callApi("/api/conf/getAnalysisType", "POST", null, (analysisType)=>{
            $('#conf_type').val(analysisType);
        }, null);
    }

    function getRowData() {
        let rowData = null;
        const selecteRow = $('tbody tr.on');
        if (selecteRow.length) {
            rowData = {};
            for (let ii = 1; ii < selecteRow.children().length; ii++) {
                let value = selecteRow.children().eq(ii).text();
                value = (value === '-' ? null : value);
                const key = columns[ii - 1];

                rowData[key] = value;
            }
        }
        return rowData;
    }
</script>