import { _mapManager, _cctvMap, _vmsMap, camCtrl, vmsMessageCtrl, createVideoDiv, createMessageDiv, dragEvent, setVmsInterval, _sttsMap } from "./main-func.js";
import { LayerIndex, LayerType } from "/js/vworld/map-const.js";

// TODO:
// 시스템 자동 돌발
// {
//     "link_id": 2060021400,
//     "detc_dt": "20161101130000",
//     "clct_sped_avrg": 4,
//     "estm_sped_avrg": 36,
//     "real_yn": "N",
//     "road_name": "성남대로",
//     "from_node": "낙생교",
//     "to_node": "동막교사거리",
//     "x_crdn": 127.10890132,
//     "y_crdn": 37.3435949,
//     "real_desc": null
// }
const _search_url    = "./main-map-pop-up.html";
const _search_option = "width=500,height=400,left=700,top=280";
let _mapToggleCheck  = null;
const stateTemplate = function (container, options) {
    const trueImage = $('<img src="/images/op/icon/true.png" width="20px" height="20px" style="display: block; margin: 0 auto;" alt="정상">');
    const falseImage = $('<img src="/images/op/icon/false.png" width="20px" height="20px" style="display: block; margin: 0 auto;" alt="상태 이상">');
    let result = options.value === "정상" ? trueImage : falseImage;
    result.appendTo(container);
};


//$(() => {
//메인화면 큰틀
const drawer = $("#drawer").dxDrawer({
    opened: true,
    position: "left",
    closeOnOutsideClick: false,
    template() {
        const div = $("<div>").addClass("left-section");
        div.css({width: "calc(100% - 5px)", height : "100%"});
        let procBox = $("<div>").addClass("process-tab-box");
        let fcltBox = $("<div>").addClass("facility-tab-box");
        div.append(procBox, $("<div class='mid-border b1 dx-theme-border-color' draggable='true'>"),fcltBox);
        const container = $('<div class="left-container">');
        container.append(div, $('<div class="right-border b3 dx-theme-border-color" draggable="true"></div>'));
        return container;
    },
}).dxDrawer("instance");

    sectionResize($('.right-border'), $("#drawer"), 
                $('#drawer .dx-drawer-panel-content'),
                $('#drawer .dx-drawer-content'), $('.left-container'),
                ()=>{_mapManager.updateSize(); }, 'width');
    sectionResize($('.mid-border'), $('.left-container'), $('.process-tab-box'), $('.facility-tab-box'), null, null, 'height');
//좌측 화면 프로세스 테이블
const _gridUnitSttsList = $("<div id='processTable'>")
    .width("100%")
    .height("calc(100% - 42px)")
    .dxDataGrid({
        dataSource: null,
        allowColumnReordering: true,
        allowColumnResizing: true,
        showColumnLines: true,
        showBorders: true,
        rowAlternationEnabled: true,
        noDataText: "표출할 정보가 없습니다.",
        columnAutoWidth: true,
        loadPanel:{
            showIndicator: false,
            showPane : false,
        },
        sorting :{
            mode: 'none'
        }
        ,
        columns: [
            {
                dataField: "syst_nm",
                caption: "명칭",
                alignment: "center",
                cssClass: "p-5",
                cellTemplate(cont, opt) {
                    cont.css("text-align", "left");
                    return cont.text(opt.displayValue);
                },
            },
            {
                dataField: "syst_stts_desc",
                caption: "상태",
                cssClass: "p-5",
                alignment: "center",
                cellTemplate: stateTemplate,
            },
        ],
    });

//좌측 화면 시설물 테이블
const _gridFcltSttsList = $("<div id='facilityTable'>")
    .width("100%")
    .height("calc(100% - 45px)")
    .dxDataGrid({
        dataSource: null,
        keyExpr: "fclt_id",
        allowColumnReordering: true,
        showColumnLines: true,
        //allowColumnResizing: true,
        showBorders: true,
        rowAlternationEnabled: true,
        focusedRowEnabled: true,
        columnAutoWidth: true,
        noDataText: "표출할 정보가 없습니다.",
        paging: {
            enabled: true,
            pageSize: 1000,
        },
        loadPanel:{
            showIndicator: false,
            showPane : false,
        },
        groupPanel: {
            visible: false,
            emptyPanelText: "그룹 지을 항목을 여기에 끌어다 놓으세요",
        },
        selection: {
            mode: "single",
        },
        scrolling: {
            mode: "standard",
        },
        headerFilter: {
            visible: true,
        },
        columns: [
            {
                dataField: "fclt_type",
                caption: "유형",
                groupIndex: 0,
                allowResizing : false,
                width : 0,
                cssClass: "p-5",
                groupCellTemplate(c, e){
                    if (e.displayValue === 'CCAM') {
                        c.text('유형 : 교차로 카메라');
                    }
                    else if (e.displayValue === 'SIG') {
                        c.text('유형 : 신호제어기');
                    }
                    else  {
                        c.text('유형 : '  + e.displayValue);
                    }
                    return c;
                }
            },
            {
                dataField: "fclt_id",
                cssClass: "p-5",
                alignment: "center",
                sortIndex: 0,
                sortOrder: "asc",
                allowResizing : true,
                width: 90,
                caption: "ID",
            },
            {
                dataField: "fclt_nm",
                caption: "위치",
                cssClass: "p-5",
                width: 90,
                allowResizing : true,
                alignment: "center",
                cellTemplate(c, e) {
                    alignTemplate(c, e, 'left')
                },
            },
            {
                dataField: "stts_desc",
                caption: "상태",
                alignment: "center",
                cssClass: "p-5",
                allowResizing : false,
                width: 80,
                cellTemplate: stateTemplate,
            },
        ],
        onRowDblClick(row) {
            moveMapFclt(row.data);
        },
        onContextMenuPreparing: function (e) {
            if (e.row.rowType === "data" ) {
                const fcltNmbr = e.row.data.fclt_nmbr;

                if (e.row.data.fclt_type === 'CCTV'){
                    const cctvObj = _mapManager.findLayerObject(LayerIndex.Cctv, Number(fcltNmbr));
                    e.items = [{
                        text: "카메라영상",
                        onItemClick: function (e) {
                            if(cctvObj){
                                if(!_cctvMap.get(cctvObj.ID)){
                                    _cctvMap.set(cctvObj.ID, new Map());
                                }

                                let src = cctvObj.strmHttpAddr;
                                camCtrl(_cctvMap, createVideoDiv, cctvObj, src, event.clientX, event.clientY);
                            }
                        }
                    }];
                }
                else if (e.row.data.fclt_type === 'VMS'){
                    const vmsObj = _mapManager.findLayerObject(LayerIndex.Vms, Number(fcltNmbr));
                    e.items = [
                        {
                            text: "카메라영상",
                            onItemClick: function () {
                                if(vmsObj){
                                    if(!_cctvMap.get(vmsObj.ID)){
                                        _cctvMap.set(vmsObj.ID, new Map());
                                    }
                                    let src = vmsObj.strmSesnNm;
                                    camCtrl(_cctvMap, createVideoDiv, vmsObj, src, event.clientX, event.clientY);
                                }
                            }
                        },
                        {
                            text: "표출메시지",
                            onItemClick: function () {
                                if(vmsObj){
                                    if(!_vmsMap.get(vmsObj.ID)){
                                        _vmsMap.set(vmsObj.ID, new Map());
                                    }

                                    if(!_vmsMap.get(vmsObj.ID).get('div')){
                                        vmsMessageCtrl(vmsObj, event.clientX, event.clientY);
                                    }
                                  
                                }
                            }
                        },
                    ];
                }
            }
        }
    });

//좌측 테이블 상단 바
//프로세스 테이블 토글
const processBar = $('<div class="serve-title dx-nav-item color dx-theme-accent-as-border-color dx-theme-accent-as-text-color bar title-div"><div style="min-width:120px;">프로세스 상태 정보</div><div id="process-bar-button"></div></div>');
processBar.on("click", function () {
    $("#processTable").toggle(400, function () {
        let result = ternaryOperator($("#process-bar-button")[0].ariaLabel, "chevronup", "chevrondown");
        $("#process-bar-button").dxButton("instance").option("icon", result);
        $(".process-tab-box").toggleClass("proc-toggle");
        $(".facility-tab-box").toggleClass("fclt-toggle");
    });
});

//시설물 테이블 토글
const facilityBar = $('<div class="serve-title dx-nav-item color dx-theme-accent-as-border-color dx-theme-accent-as-text-color bar title-div"><div style="min-width:105px;">시설물 상태 정보</div><div id="facility-bar-button"></div></div>');
$(".left-section .process-tab-box").append(processBar, _gridUnitSttsList);
$(".left-section .facility-tab-box").append(facilityBar, _gridFcltSttsList);

facilityBar.on("click", function () {
    $("#facilityTable").toggle(400, function () {
        let result = ternaryOperator($("#facility-bar-button")[0].ariaLabel, "chevronup", "chevrondown");
        $("#facility-bar-button").dxButton("instance").option("icon", result);
    });
});

//토글 버튼
$("#process-bar-button, #facility-bar-button").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "chevronup",
    hint: "보이기/감추기",
});

//우측 화면
const mapDrawer = $("#mapDrawer")
    .dxDrawer({
        opened: true,
        position: "bottom",
        closeOnOutsideClick: false,
        template(c) {
            const list = $(`<div class="bottom-container" style="width:100%; height:240px;">
                                <div class="top-border b1 dx-theme-border-color" draggable="true"></div>
                                <div class="bottom-box" style="width:100%;height:calc(100% - 5px); display:flex; flex-direction:row;">
                                    <div id="tabs" style="width:calc(100% - 410px); height:100%;"></div>
                                    <div class="drag-border b3 dx-theme-border-color" draggable="true"></div>
                                    <div class="facility-box">
                                        <div>
                                            <div class="serve-title dx-nav-item color dx-theme-accent-as-text-color bar dx-theme-accent-as-border-color" style="min-width:120px;">
                                                시설물 현황
                                            </div>
                                            <div id="facility-state"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>`);
            c.append(list)
            return c;
        },
    })
    .dxDrawer("instance");
    sectionResize($('.drag-border'), $('.bottom-box'), $('#tabs'), $('.facility-box'), null, null, 'width');
   
    sectionResize($('.top-border'), 
                $('#mapDrawer'), 
                $('#mapDrawer .dx-drawer-content'), 
                $('#mapDrawer .dx-drawer-panel-content'), 
                $('.bottom-container'),
                ()=>_mapManager.updateSize(), 'height');

//맵 상단 버튼들
$("#side-button").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "chevrondoubleleft",
    hint: "보이기/감추기",
    onClick(e) {
        drawer.toggle();
        let iconState = e.component.option("icon") === "chevrondoubleleft" ? "chevrondoubleright" : "chevrondoubleleft";
        e.component.option("icon", iconState);
        _mapManager.updateSize();
    },
});

$("#bottom-button").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "chevrondown",
    hint: "보이기/감추기",
    onClick(e) {
        mapDrawer.toggle();
        let iconState = e.component.option("icon") === "chevrondown" ? "chevronup" : "chevrondown";
        e.component.option("icon", iconState);
        _mapManager.updateSize();
    },
});

// 지도 화면 저장
$("#save").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "download",
    hint: "저장",
    onClick() {
        _mapManager.saveImage("main", "image-download");
    },
});

// 표준영역으로 이동
$("#map-button").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "globe",
    hint: "표준 영역",
    onClick() {
        _mapManager.stdExtent();
    },
});

// 지도 확대
$("#zoom-in").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "plus",
    hint: "확대",
    onClick() {
        _mapManager.zoomIn();
    },
});

// 지도축소
$("#zoom-out").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "minus",
    hint: "축소",
    onClick(e) {
        _mapManager.zoomOut();
    },
});

// 새로고침

$("#refresh").dxButton({
    stylingMode: "text",
    type: "normal",
    icon: "refresh",
    hint: "새로고침",
    onClick() {
        // TODO: 데이터도 다시 조회한다.(나중에 추가해야함.....)
        _mapManager.refreshMap();
        _mapManager.updateSize();
        refreshInfo();
    },
});

function refreshInfo() {
    getDataAsync('/api/common/stts/total', recvSttsTot);
    getDataAsync('/api/common/stts/process/its', updateUnitStts);
    getDataAsync('/api/manage/main/traffic/link', recvTraffic, LayerType.LINK);
    getDataAsync('/api/manage/main/traffic/ifsc', recvTraffic, LayerType.IFSC);
    getDataAsync('/api/manage/main/traffic/road', recvTraffic, LayerType.ROAD);
    getDataAsync('/api/manage/main/syst-opr/miss-link-traf', updateMissLinkTraf);
    getDataAsync('/api/manage/main/syst-opr/repeat-congest', updateRepeatCongest);
    getDataAsync('/api/manage/main/syst-opr/incd-ocrr', recvOcrr);
    getDataAsync('/api/manage/main/syst-opr/auto-incd', updateAutoIncd);
}

function recvSttsTot(jsonData) {
    jsonData.fclt_list.forEach((el) => {
        let lyrInfo = null;
        const stts = _sttsMap.get(el.fclt_type);
        if (!stts) {
            return;
        }
        let toNumber = false;
        if (el.fclt_type === "CCTV") {
            lyrInfo = _mapManager.getLayer(LayerIndex.Cctv);
            toNumber = true;
        } else if (el.fclt_type === "VMS") {
            lyrInfo = _mapManager.getLayer(LayerIndex.Vms);
            toNumber = true;
        } else if (el.fclt_type === "VDS") {
            lyrInfo = _mapManager.getLayer(LayerIndex.Vds);
            toNumber = true;
        } 
        else if (el.fclt_type === "DSRC") {
            lyrInfo = _mapManager.getLayer(LayerIndex.Dsrc);
            toNumber = true;
        }
        else if (el.fclt_type === "SIG") {
            lyrInfo = _mapManager.getLayer(LayerIndex.Sig);
            toNumber = true;
        }
        else if (el.fclt_type === "CCAM") {
            lyrInfo = _mapManager.getLayer(LayerIndex.CCam);
        }

        if (lyrInfo) {
            stts.total = el.total_cnt;
            stts.normal = el.normal_cnt;
            stts.error = el.error_cnt;
            stts.collect = el.col_err_cnt;
            stts.objLists = el.fclt_objs;
            el.fclt_objs.forEach((obj) => {
                const fclt = lyrInfo.findObject(toNumber ? Number(obj.fclt_nmbr) : obj.fclt_nmbr);
                if (fclt) {
                    fclt.updateStts(obj.stts_cd, obj.updt_dt);
                } else {
                    console.warn(`fetchFcltStts: Not Found Object, ${obj.fclt_type}, ${obj.fclt_nmbr}, ${obj.fclt_id}`);
                }
            });
        } else {
            console.error(currDt(), " Unknown Fclt Type: ", el.fclt_type);
        }
    });
    updateFcltStts(_sttsMap);
}
function recvOcrr(jsonData) {
    _mapManager.makeLayer(LayerIndex.Incd, jsonData); // 레이어 생성
    updateIncdData(jsonData);
}
function recvTraffic(jsonData, type) {
    _mapManager.updateTrafficObject(type, jsonData);
}
// 지도 객체 선택
$("#selected").dxCheckBox({
    value : false,
    text  : '선택',
    onValueChanged(e) {
        _mapManager.setSelectMode(!e.value);
    },
}).dxCheckBox('instance');

//위성 지도 보이기 감추기
_mapToggleCheck = $('#map-toggle').dxCheckBox({
    value : true,
    text  : '위성지도',
    onValueChanged(e){
        _mapManager.toggleBaseMap(e.value);
    }
}).dxCheckBox('instance');

//소통정보 보기/숨기기
$('#chk-traffic-info').dxCheckBox({
    value : true,
    text  : '소통정보',
    onValueChanged(e){
        _mapManager.showTrafficLayer(e.value);
    }
}).dxCheckBox('instance');


//소통정보 툴팁 보기/숨기기
$('#chk-traffic-tool-tip').dxCheckBox({
    value : false,
    text  : '소통정보툴팁',
    onValueChanged(e){
        _mapManager.showTrafficTooltip(e.value);
    }
}).dxCheckBox('instance');

//돌발정보 보기/숨기기
$('#chk-incident-info').dxCheckBox({
    value : true,
    text  : '돌발정보',
    onValueChanged(e){
        _mapManager.showIncidentLayer(e.value);
    }
}).dxCheckBox('instance');

//시설물 셀렉트 박스
const selectTitle = $(".text_ul_wrap > a");
$("<div class='select_icon'></div>").insertAfter(selectTitle);

$(".text_ul_wrap > a, .select_icon").click(function () {
    $(".ul_select_style").toggleClass("active");
    $(".select_icon").toggleClass("active");
});

$(".ul_select_style > li").on("click", function () {
    const isShow = !$(this).children().is(":checked");
    let lyrName = $(this).children().val();
    _mapManager.showFacilityLayer(lyrName, isShow);

    $(this).children().prop("checked", !$(this).children().is(":checked"));
    const selectBoxArr = $(".select-box-class");
    let text = "";
    for (let ii = 0; ii < selectBoxArr.length; ii++) {
        if (selectBoxArr.eq(ii).is(":checked")) {
            text += selectBoxArr.eq(ii).parent().text() + ", ";
        }
    }
    if (text == "") {
        text = "시설물 레이어 표출 선택";
    }
    let index = text.lastIndexOf(",");
    if (index !== -1) text = text.slice(0, -2);
    selectTitle.text(text);
});

hoverClass('.ul_select_style li');

$('.ul_select_style > li > input').on('click', function(ev){
    event.stopPropagation();
    const isShow = $(this).is(":checked");
    const lyrName = $(this).val();
    _mapManager.showFacilityLayer(lyrName, isShow);

    $(this).children().prop("checked", !$(this).children().is(":checked"));
    const selectBoxArr = $(".select-box-class");
    let text = "";
    for (let ii = 0; ii < selectBoxArr.length; ii++) {
        if (selectBoxArr.eq(ii).is(":checked")) {
            text += selectBoxArr.eq(ii).parent().text() + ", ";
        }
    }
    if (text == "") {
        text = "시설물 레이어 표출 선택";
    }
    let index = text.lastIndexOf(",");
    if (index !== -1) text = text.slice(0, -2);
    selectTitle.text(text);
})

$("body").click(function (e) {
    if ($(".ul_select_style").hasClass("active") && !$(".text_ul_wrap").has(e.target).length) {
        $(".ul_select_style").removeClass("active");
        $(".select_icon").removeClass("active");
    }
});

let _searchPopup = null;
$("#search-map").dxCheckBox({
    text  : '지도검색',
    value : false,
    onValueChanged(e) {
        if (e.value) _searchPopup = window.open(_search_url, "지도 검색", _search_option);
        else if (_searchPopup !== null) _searchPopup.close();
    }
}).dxCheckBox('instance');
        

//돌발상황정보
const _gridIncdDataList = $("<div id='incidentTable'>")
    .width("100%")
    .height("100%")
    .dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : "표출할 정보가 없습니다.",
        focusedRowEnabled       : true,
        keyExpr                 : ['incd_ocrr_id', 'rgst_dt'],
        headerFilter: {
            visible: true,
        },
        loadPanel:{
            showIndicator: false,
            showPane : false,
        },
        selection: {
            mode: "single",
        },
        scrolling: {
            mode: "virtual",
        },
        columns: [
            {
                dataField: "incd_ocrr_id",
                caption: "ID",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "rgst_dt",
                caption: "등록 일시",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_strt_dt",
                caption: "시작 일시",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_end_prar_dt",
                caption: "종료 예정 일시",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_type_clsf_desc",
                caption: "돌발상황 유형 분류",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_type_desc",
                caption: "돌발상황 유형 세부 분류",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
            {
                dataField: "incd_titl",
                caption: "돌발상황 제목",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
            {
                dataField: "incd_expl",
                caption: "상황 설명",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_prgr_step_desc",
                caption: "진행 단계",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_orgn_desc",
                caption: "동발상황 구분",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "ocrr_lctn_nm",
                caption: "발생 위치 설명",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
            {
                dataField: "incd_cnfm_mthd_desc",
                caption: "돌발상황 확인 방법",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_sern_desc",
                caption: "심각도",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "link_id",
                caption: "구간 ID",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "cmtr_grad_desc",
                caption: "소통 등급",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "x_crdn",
                caption: "X좌표",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "y_crdn",
                caption: "Y좌표",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "ifmr_nm",
                caption: "제보자",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_ocrr_lane",
                caption: "발생 차로",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_clsr_lane",
                caption: "차단 차로",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "dely_lngt",
                caption: "지체 길이",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_lngt",
                caption: "돌발상황 길이",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "smlt_vhcl_unum",
                caption: "소형 차량 대수",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "mdlt_vhcl_unum",
                caption: "중대형 차량 대수",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "injr_pnum",
                caption: "부상자",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "ftlt_pnum",
                caption: "사망자",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "wthr_desc",
                caption: "기상 상태",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "resp_lvl_cd",
                caption: "대응수준",
                alignment: "center",
                cssClass : 'p-5',
            },
            // {
            //     dataField: "utis_cnct_yn",
            //     caption: "UTIS연계여부",
            //     alignment: "center",
            //     cssClass : 'p-5',
            // },
            {
                dataField: "trub_vhcl_yn",
                caption: "고장차량여부",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "falt_yn",
                caption: "낙하물여부",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "frwt_yn",
                caption: "화재위험물여부",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "trvl_lmnt_type",
                caption: "통행제한유형",
                alignment: "center",
                cssClass : 'p-5',
            },
            // {
            //     dataField: "vms_dspl_yn",
            //     caption: "VMS 표출여부",
            //     alignment: "center",
            //     cssClass : 'p-5',
            // },
        ],
        onRowDblClick(row) {
            moveMapIncd(row.data);
        },
    });
//반복정체구간
const _gridRepeatCongestList = $("<div id='repeatCongestTable'>")
    .width("100%")
    .height("100%")
    .dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : "표출할 정보가 없습니다.",
        focusedRowEnabled       : true,
        keyExpr                 : 'ifsc_id',
        loadPanel:{
            showIndicator: false,
            showPane : false,
        },
        headerFilter: {
            visible: true,
        },
        selection: {
            mode: "single",
        },
        scrolling: {
            mode: "virtual",
        },
        columns: [
            {
                dataField: "ifsc_id",
                caption: "정보제공구간 ID",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "ifsc_nm",
                caption: "명칭",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c,e){
                    c.css('text-align','left');
                    c.text(e.displayValue)
                }
            },
            {
                dataField: "drct_cd_desc",
                caption: "방향",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "strt_nm",
                caption: "시점명",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "end_nm",
                caption: "종점명",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "avrg_sped",
                caption: "평균 속도",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "avrg_trvl_hh",
                caption: "평균 통행 시간",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "prcn_dt",
                caption: "가공일시",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "sped",
                caption: "속도",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "trvl_hh",
                caption: "통행 시간",
                alignment: "center",
                cssClass : 'p-5',
            },
        ],
        onRowDblClick(row) {
            selectGisData(2, row.data.ifsc_id);
        },
    });
//소통정보 결측구간
const _gridMissLinkTrafList = $("<div id='missTrafficTable'>")
    .width("100%")
    .height("100%")
    .dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : "표출할 정보가 없습니다.",
        focusedRowEnabled       : true,
        keyExpr                 : ['link_id', 'prcn_dt'],
        loadPanel:{
            showIndicator: false,
            showPane : false,
        },
        headerFilter: {
            visible: true,
        },
        selection: {
            mode: "single",
        },
        scrolling: {
            mode: "virtual",
        },
        columns: [
            {
                dataField: "link_id",
                caption: "링크 ID",
                alignment: "center",
                width: 120,
                cssClass : 'p-5',
            },
            {
                dataField: "prcn_dt",
                caption: "최종가공시각",
                width: 150,
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "f_node_nm",
                caption: "시작노드",
                alignment: "center",
                width: 200,
                cssClass : 'p-5',
                cellTemplate(cont, opt) {
                    cont.css("text-align", "left");
                    return cont.text(opt.displayValue);
                },
            },
            {
                dataField: "t_node_nm",
                caption: "종료노드",
                alignment: "center",
                width: 200,
                cssClass : 'p-5',
                cellTemplate(cont, opt) {
                    cont.css("text-align", "left");
                    return cont.text(opt.displayValue);
                },
            },
            {
                dataField: "prcn_sorc_desc",
                caption: "보정소스",
                alignment: "center",
                width: 140,
                cssClass : 'p-5',
            },
            {
                dataField: "adjs_sorc_desc",
                caption: "가공소스",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "lanes",
                caption: "차로수",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "road_name",
                caption: "도로명",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "link_leng",
                caption: "연장(m)",
                alignment: "center",
                cssClass : 'p-5',
            },

            {
                dataField: "cmtr_grad_desc",
                caption: "소통 등급",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(cont, opt) {
                    cont.css("text-align", "left");
                    return cont.text(opt.displayValue);
                },
            },
        ],
        onRowDblClick(row) {
            selectGisData(1, row.data.link_id);
        },
    });

//시스템 자동돌발
const _gridAutoIncdList = $("<div id='autoIncidentTable'>")
    .width("100%")
    .height("100%")
    .dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : "표출할 정보가 없습니다.",
        focusedRowEnabled       : true,
        keyExpr                 : ['link_id', 'detc_dt'],
        loadPanel:{
            showIndicator: false,
            showPane : false,
        },
        headerFilter: {
            visible: true,
        },
        selection: {
            mode: "single",
        },
        scrolling: {
            mode: "virtual",
        },
        columns: [
            {
                dataField: "link_id",
                caption: "링크 ID",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "detc_dt",
                caption  : "검지 일시",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "clct_sped_avrg",
                caption: "수집 평균속도",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "estm_sped_avrg",
                caption: "예측 평균속도",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "road_name",
                caption: "도로명",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
            {
                dataField: "from_node",
                caption: "시점명",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
            {
                dataField: "to_node",
                caption: "종점명",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
        ],
        onRowDblClick(row) {
            selectGisData(1, row.data.link_id);
        },
    });
//하단 탭
$("#tabs")
    .dxTabPanel({
        dataSource: [
            {
                id: 1,
                name: "돌발상황정보",
                table: _gridIncdDataList,
            },
            {
                id: 2,
                name: "반복정체구간",
                table: _gridRepeatCongestList,
            },
            {
                id: 3,
                name: "소통정보 결측구간",
                table: _gridMissLinkTrafList,
            },
            // {
            //     id: 4,
            //     name: "시스템 자동돌발",
            //     table: _gridAutoIncdList,
            // },
        ],
        selectIndex: 0,
        loop: false,
        animationEnabled: true,
        swipeEnabled: false,
        itemTitleTemplate: function (e) {
            return $('<div style="height:29px; line-height:29px;">' + e.name + "</div>");
        },
        itemTemplate: function (e) {
            return e.table;
        },
    })
    .dxTabPanel("instance");

//시설물 현황 테이블
let _gridFcltSttsBoard = $("#facility-state").width('100%').height('calc(100% - 40px)').dxDataGrid({
    dataSource: null,
    allowColumnReordering: true,
    allowColumnResizing: true,
    showColumnLines: true,
    showBorders: true,
    rowAlternationEnabled: true,
    columnAutoWidth: true,
    noDataText: "표출할 정보가 없습니다.",
    loadPanel:{
        showIndicator: false,
        showPane : false,
    },
    sorting :{
        mode: 'none'
    },
    columns: [
        {
            dataField: "type",
            caption: "시설물",
            alignment: "center",
            cssClass : 'p-5',
            width: 95,
        },
        {
            dataField: "total",
            caption: "전체",
            alignment: "center",
            cssClass : 'p-5',
            width: 70,
        },
        {
            dataField: "normal",
            caption: "정상",
            alignment: "center",
            cssClass : 'p-5',
            width: 70,
        },
        {
            dataField: "error",
            caption: "통신이상",
            width: 80,
            alignment: "center",
            cssClass : 'p-5',
            cellTemplate(container, options) {
                let style = "";
                if (options.data.error > 0) {
                    style = 'style = "color:red;"';
                }
                return $('<div ' + style + '>' + options.data.error + "</div>");
            },
        },
        {
            dataField: "collect",
            caption: "수집이상",
            width: 80,
            alignment: "center",
            cssClass : 'p-5',
            cellTemplate(container, options) {
                let style = "";
                if (options.data.collect > 0) {
                    style = 'style = "color : red;"';
                }
                let result = nullChecker(options.data.collect);
                return $("<div " + style + ">" + result + "</div>");
            },
        },
    ],
});

export function updateUnitStts(jsonData) {
    _gridUnitSttsList.dxDataGrid("instance").option("dataSource", jsonData);
}
export function updateIncdData(jsonData) {
    //console.log("updateIncdData: ", jsonData);
    jsonData.forEach((item) => {
        if (item.rgst_dt) item.rgst_dt = getParseDateTime(item.rgst_dt);
        if (item.incd_strt_dt) item.incd_strt_dt = getParseDateTime(item.incd_strt_dt);
        if (item.incd_end_prar_dt) item.incd_end_prar_dt = getParseDateTime(item.incd_end_prar_dt);
    });
    _gridIncdDataList.dxDataGrid("instance").option("dataSource", jsonData);
}
export function updateAutoIncd(jsonData) {
    //console.log("updateAutoIncd: ", jsonData);
    jsonData.forEach((item) => {
        if (item.detc_dt) item.detc_dt = getParseDateTime(item.detc_dt);
    });
    _gridAutoIncdList.dxDataGrid("instance").option("dataSource", jsonData);
}
export function updateFcltStts(sttsMap) {
    const fcltSttsArr = new Array();
    sttsMap.forEach((obj) => {
        if (obj.type !== "BIT") {
            Array.prototype.push.apply(fcltSttsArr, obj.objLists);
        }
    });
    const sttsArray = Array.from(sttsMap.values());
    _gridFcltSttsBoard.dxDataGrid("instance").option("dataSource", sttsArray);
    _gridFcltSttsList.dxDataGrid("instance").option("dataSource", fcltSttsArr);
}
export function updateMissLinkTraf(jsonData) {
    jsonData.forEach((item) => {
        if (item.prcn_dt) item.prcn_dt = getParseDateTime(item.prcn_dt);
        item.f_node_nm = "[" + item.f_node_id + "] " + item.f_node_nm;
        item.t_node_nm = "[" + item.t_node_id + "] " + item.t_node_nm;
    });
    _gridMissLinkTrafList.dxDataGrid("instance").option("dataSource", jsonData);
}
export function updateRepeatCongest(jsonData) {
    jsonData.forEach((item) => {
        if (item.prcn_dt) item.prcn_dt = getParseDateTime(item.prcn_dt);
    });
    _gridRepeatCongestList.dxDataGrid("instance").option("dataSource", jsonData);
}

/**
 * 지도검색에서 호출하는 함수
 */
window.selectGisData = function (AType, AId) {
    let fNodeId = null;
    if (AType === 0) {
        fNodeId = AId;
    } else if (AType === 1) {
        //링크 조회
        const link = _mapManager.findLinkObject(AId);
        if (link) fNodeId = link.fNodeId;
    } else if (AType === 2) {
        //정보제공구간 조회
        const ifsc = _mapManager.findIfscObject(AId);
        if (ifsc) fNodeId = ifsc.fNodeId;
    } else if (AType === 3) {
        //도로 조회
        const road = _mapManager.findRoadObject(AId);
        if (road) fNodeId = road.fNodeId;
    }
    const node = _mapManager.findLayerObject(LayerIndex.Node, fNodeId);
    if (node) {
        moveMapPos(node.xCrdn, node.yCrdn);
    }
};

function moveMapFclt(AFcltObj) {
    if (AFcltObj) {
        moveMapPos(AFcltObj.x_crdn, AFcltObj.y_crdn);
    }
}
function moveMapIncd(AIncdObj) {
    if (AIncdObj) {
        moveMapPos(AIncdObj.x_crdn, AIncdObj.y_crdn);
    }
}
function moveMapPos(ALat, ALng) {
    _mapManager.selectPos(ALat, ALng);
}

const themeSwitch = $('.switch').dxSwitch({
    visible: true,
    onValueChanged(e){
        if (e.value){
            if (window.$cssHref) {
                let color = window.$cssHref.substring(32, window.$cssHref.length - 12);
                color = color.substring(0, color.indexOf('.'));
                window.$cssHref = '/libs/dx-21.2.6/css/dx.material.' + color + '.light.compact.css';
            }
            else {
                window.$cssHref = '/libs/dx-21.2.6/css/dx.material.blue.light.compact.css';
            }
        }
        else {
            if (window.$cssHref) {
                let color = window.$cssHref.substring(32, window.$cssHref.length - 12);
                color = color.substring(0, color.indexOf('.'));
                window.$cssHref = '/libs/dx-21.2.6/css/dx.material.' + color + '.dark.compact.css';
            }
            else {
                window.$cssHref = '/libs/dx-21.2.6/css/dx.material.blue.dark.compact.css';
            }
        }
        $('.main-css').prop('href', window.$cssHref);
        setValue(_mapToggleCheck, !e.value);
    }
}).dxSwitch('instance');

$('.log-out').hover(function(){
    $(this).addClass('dx-button dx-state-hover');
},function(){
    $(this).removeClass('dx-button dx-state-hover');
})
$('.theme-btn').hover(function(){
    $('dd').addClass('dx-menu-item-expanded dx-state-hover');
    $('.theme-btn > li').css('display','flex');
    $(this).css('height', '232px');
},function(){
    $('dd').removeClass('dx-menu-item-expanded dx-state-hover');
    $('.theme-btn > li').css('display','none');
    $(this).css('height', '60px')
})

$('.theme-btn > li').hover(function(){
    //const bgColor = $('.dx-menu-item-expanded.dx-state-hover').css('background-color');
    $(this).addClass('dx-menu-item dx-state-hover');
},function(){
    $(this).removeClass('dx-menu-item dx-state-hover');
})

const themeArr = [
    {
        id     : '1',
        name  : 'Blue Dark',
        theme : 'dx.material.blue.dark.compact.css',
        type  : 'blue',
    },
    {
        id     : '2',
        name  : 'Blue Light',
        theme : 'dx.material.blue.light.compact.css',
        type  : 'blue',
    },
    {
        id     : '3',
        name  : 'Lime Dark',
        theme : 'dx.material.lime.dark.compact.css',
        type  : 'orange',
    },
    {
        id     : '4',
        name  : 'Lime Light',
        theme : 'dx.material.lime.light.compact.css',
        type  : 'orange',
    },
    {
        id     : '5',
        name  : 'Orange Dark',
        theme : 'dx.material.orange.dark.compact.css',
        type  : 'orange',
    },{
        id     : '6',
        name  : 'Orange Light',
        theme : 'dx.material.orange.light.compact.css',
        type  : 'orange',
    },{
        id     : '7',
        name  : 'Purple Dark',
        theme : 'dx.material.purple.dark.compact.css',
        type  : 'purple ',
    },{
        id     : '8',
        name  : 'Purple Light',
        theme : 'dx.material.purple.light.compact.css',
        type  : 'purple ',
    },{
        id    : '9',
        name  : 'Teal Dark',
        theme : 'dx.material.teal.dark.compact.css',
        type  : 'green',
    },{
        id    : '10',
        name  : 'Teal Light',
        theme : 'dx.material.teal.light.compact.css',
        type  : 'green',
    },]

$('.theme-btn > li').on('click',function(){
    const typeText = getValue(themeSwitch) ? ' Light' : ' Dark';
    const textName = $(this).children().eq(1).text() + typeText;
    themeArr.map((obj)=>{
        if (obj.name === textName) {
            window.$cssHref = '/libs/dx-21.2.6/css/' + obj.theme;
            $('.main-css').prop('href', window.$cssHref);
            const _mapToggleCheck = $('#map-toggle').dxCheckBox('instance');
            if (obj.theme.indexOf('light') > -1) {
                setValue(_mapToggleCheck, false);
            }
            else {
                setValue(_mapToggleCheck, true);
            }
            window.$type = obj.type;
            $('.theme-btn > li').css('display','none');
            $('.theme-btn').css('height', '60px');
        }
    })
})