import { TMapMngr } from "/js/vworld/map-mngr.js";
import { LayerType, LayerIndex, EditLinkColor } from "/js/vworld/map-const.js";
import { apiGet } from "/js/utils/restApi.js";
let _nodeTableList     = null;
let _ifscTableList     = null;
let _selectSectionList = null;
let _mapManager        = null;
let _lyrType           = LayerType.IFSC;
let _lyrIdx            = LayerIndex.Ifsc1;
const _pageName        = '구간 선택';
const mapParmas        = window.opener.getParams();
const _mapLevel        = mapParmas.LinkLevel;
const _mapMultiSelect  = mapParmas.MultiSelect;
const _linkInfo        = mapParmas.LinkInfo;
const trafficMap       = window.opener.getTrafficMap();
const sectNm           = _mapLevel === 1? '링크' : '정보제공구간'
class TSelObj {
    constructor(ID, COORDX, COORDY) {
        this.id = ID;
        this.coordX = COORDX;
        this.coordY = COORDY;
    }
}
const _selObjMap = new Map();
$(() => {
    $('.map-level').text(_mapLevel);
    _selectSectionList = $('.select-section-table')
        .width('100%')
        .height('100%')
        .dxDataGrid({
        dataSource: null,
        allowColumnReordering: true,
        showColumnLines: true,
        allowColumnResizing: true,
        showBorders: true,
        rowAlternationEnabled: true,
        columnAutoWidth: true,
        keyExpr               : 'id',
        focusedRowEnabled     : true,
        editing               : {
            confirmDelete : false,
        },
        selection             : {
            mode : "single",
        },
        columns: [
            {
                dataField : 'link_color',
                caption   : '-',
                alignment : "center",
                cssClass  : 'no-padding',
                visible   : true,
                cellTemplate(c,e){
                    c.css('background-color', EditLinkColor[e.displayValue]);
                }
            },
            {
                dataField : "id",
                caption   : "구간 ID",
                cssClass  : 'no-padding',
                alignment : "center",
            },
            {
                dataField : "coordX",
                caption   : "좌표 X",
                cssClass  : 'no-padding',
                alignment : "center",
            },
            {
                dataField : "coordY",
                caption   : "좌표 Y",
                cssClass  : 'no-padding',
                alignment : "center",
            },
        ],
        onRowDblClick(row){
            _mapManager.selectPos(row.data.coordX, row.data.coordY);
        }
    })
    .dxDataGrid('instance');
        $('.select-remove').dxButton({
            stylingMode: 'outlined',
            type: 'normal',
            icon: 'remove',
            text: '선택 삭제',
            width: '110',
            onClick() {
                deleteRow();
            },
        });
    
        $('.select-section-btn').dxButton({
            stylingMode: 'outlined',
            type: 'normal',
            icon: 'check',
            text: '구간 선택',
            width: '110',
            onClick() {
                insertData();
            },
        });
    
        _nodeTableList = $('<div>')
            .width('100%')
            .height('100%')
            .dxDataGrid({
                dataSource              : null,
                allowColumnReordering   : true,
                showColumnLines         : true,
                allowColumnResizing     : true,
                showBorders             : true,
                rowAlternationEnabled   : true,
                columnAutoWidth         : true,
                focusedRowEnabled       : true,
                keyExpr                 : 'node_id',
                scrolling: {
                    mode: 'virtual', 
                }, 
                selection: {
                    mode: 'single',
                },
                export:{
                    enabled: true,
                    texts: {
                        exportAll:"엑셀 파일",
                    },
                },
                filterRow: {
                    visible: true,
                    applyFilter: "auto",
                    showOperationChooser:false,
                },
                headerFilter: {
                    visible: true,
                },
                grouping: {
                    autoExpandAll: true,
                },
                groupPanel: {
                    visible: true,
                    emptyPanelText: '그룹 지을 항목을 여기에 끌어다 놓으세요',
                },
                columns: [
                    {
                        dataField : 'node_id',
                        caption   : 'ID',
                        alignment : 'center',
                        dataType  : 'string',
                        width     : 100,
                        sortIndex : 0,
                        sortOrder : 'asc',
                    },
                    {
                        dataField: 'node_type_desc',
                        caption: '유형',
                        alignment: 'center',
                        cellTemplate(c, e) {
                            return c.css('text-align', 'left').text(nullChecker(e.displayValue));
                        },
                    },
                    {
                        dataField: 'node_name',
                        caption: '명칭',
                        alignment: 'center',
                        cellTemplate(c, e) {
                            return c.css('text-align', 'left').text(nullChecker(e.displayValue));
                        },
                    },
                    {
                        dataField: 'turn_p_desc',
                        caption: '회전제한',
                        alignment: 'center',
                    },
                    {
                        dataField: 'rmrk',
                        caption: '비고',
                        alignment: 'center',
                    },
                    {
                        dataField: 'x_crdn',
                        caption: 'x좌표',
                        alignment: 'center',
                    },
                    {
                        dataField: 'y_crdn',
                        caption: 'y좌표',
                        alignment: 'center',
                    },
                ],
                onExporting(e){
                    gridExcellExporting(e, '노드 링크 목록');
                },
                onRowDblClick(row){
                    nodeTalbleListDblClick(row.data);
                }
        });
    
        _ifscTableList = $('<div>')
            .width('100%')
            .height('100%')
            .dxDataGrid({
                dataSource              : null,
                allowColumnReordering   : true,
                showColumnLines         : true,
                allowColumnResizing     : true,
                showBorders             : true,
                rowAlternationEnabled   : true,
                columnAutoWidth         : true,
                focusedRowEnabled       : true,
                keyExpr                 : 'id',
                selection: {
                    mode: 'single',
                },
                filterRow: {
                    visible: true,
                    applyFilter: "auto",
                    showOperationChooser:false,
                },
                scrolling: {
                    mode: 'virtual', 
                }, 
                headerFilter: {
                    visible: true,
                },
                grouping: {
                    autoExpandAll: true,
                },
                groupPanel: {
                    visible: true,
                    emptyPanelText: '그룹 지을 항목을 여기에 끌어다 놓으세요',
                },
                export:{
                    enabled: true,
                    texts: {
                        exportAll:"엑셀 파일",
                    },
                },
                columns: [
                    {
                        dataField : "id",
                        caption   : "ID",
                        alignment : "center",
                        dataType  : 'string',
                        width     : 100,
                        sortIndex : 0,
                        sortOrder : "asc",
                        cssClass  : 'no-padding',
                    },
                    {
                        dataField : "name",
                        caption   : "명칭",
                        alignment : "center",
                        cssClass  : 'no-padding',
                        cellTemplate(c, e) {
                            return c.css("text-align", "left").text(nullChecker(e.displayValue));
                        },
                    },
                    {
                        dataField : "strt_nm",
                        caption   : "시점명",
                        alignment : "center",
                        cssClass  : 'no-padding',
                        cellTemplate(c, e) {
                            return c.css("text-align", "left").text(nullChecker(e.displayValue));
                        },
                    },
                    {
                        dataField : "end_nm",
                        caption   : "종점명",
                        alignment : "center",
                        cssClass  : 'no-padding',
                        cellTemplate(c, e) {
                            return c.css("text-align", "left").text(nullChecker(e.displayValue));
                        },
                    },
                ],
                onExporting(e){
                    gridExcellExporting(e, '정보제공구간 목록');
            },
            onRowDblClick(e) {
                ifscTableListDblClick(e.data);
            },
        });
    
        $('.link-tabs')
            .width('100%')
            .height('100%')
            .dxTabPanel({
                dataSource: [
                    {
                        id: 1,
                        name: '노드',
                        page: _nodeTableList,
                    },
                    {
                        id: 2,
                        name: sectNm,
                        page: _ifscTableList,
                    },
                ],
                selectIndex: 0,
                loop: false,
                animationEnabled: true,
                swipeEnabled: false,
                itemTitleTemplate: function (e) {
                    return $('<div>' + e.name + '</div>');
                },
                itemTemplate: function (e) {
                    return e.page;
                },
                onSelectionChanged(e) {
                    $('.selected-index').text(e.component.option('selectedIndex') + 1);
                },
            })
            .dxTabPanel('instance');
    
            doMap();
    });
    
    /**
     * 지도
     */
     function doMap() {
        if (_mapLevel === 1) {
            _lyrType = LayerType.LINK;
            _lyrIdx = LayerIndex.Link1;
        } else if (_mapLevel == 2) {
            _lyrType = LayerType.IFSC;
            _lyrIdx = LayerIndex.Ifsc1;
        }
    
        _mapManager = new TMapMngr("map", "tooltip");
        _mapManager.onSelectObjFunc = onSelectObjFunc; // 객체 선택 이벤트 반환
    
        _mapManager.setLayerVisible(_lyrIdx, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
        _mapManager.setEditMode(_lyrIdx, true);
        _mapManager.setSelectMode(true);
        _mapManager.setZoom(15);
    
        fetchBaseData();
        fetchMapIconBar($('.map-bar'), _mapManager, _lyrIdx, _pageName);
    };
    
    let _selCnt = 1;
    function onSelectObjFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY, X, Y) {
        let dataSource = _selectSectionList.option('dataSource');
        if (ALyrIdx != _lyrIdx) {
            return;
        }
        let selObj = _selObjMap.get(ANmbr);
        if (!selObj) {
            selObj = new TSelObj(ANmbr, ACoordX.toFixed(8), ACoordY.toFixed(8));
        }
        else {
            // 기존 데이터의 x,y 좌표만 업데이트 수행
            const rowIdx = _selectSectionList.getRowIndexByKey(ANmbr);
            dataSource[rowIdx].coordX = ACoordX.toFixed(8);
            dataSource[rowIdx].coordY = ACoordY.toFixed(8);
            _selectSectionList.option('dataSource', dataSource);
            selObj = new TSelObj(ANmbr, ACoordX.toFixed(8), ACoordY.toFixed(8));
            _selObjMap.set(ANmbr, selObj);
            return;
        }
    
        if (!dataSource) {
            _selectSectionList.option('columns[0].visible', true);
            _selectSectionList.option('dataSource', []);
            dataSource = [];
            _selCnt = 1;
        };
    
        if (!_mapMultiSelect) {
            console.log("DDDD");
            // 하나만 선택 되어야 한다. 기존 선택된게 있으면 삭제
            _selObjMap.forEach((obj) => {
                _mapManager.updateEditLink(_lyrIdx, obj.id, 0, false);
            });
            _selObjMap.clear();
            selObj.link_color = 1;
        }
        else {
            selObj.link_color = _selCnt++ % EditLinkColor.length;
        }    
        
        _selObjMap.set(ANmbr, selObj);
        _mapManager.updateEditLink(_lyrIdx, ANmbr, selObj.link_color, true);
        dataSource = Array.from(_selObjMap.values());
        _selectSectionList.option('dataSource', dataSource);
    };
    
    function fetchBaseData() {
        console.time("***** fetchBaseData: ");
        let data;
        let vrtx;
        if (_mapLevel !== 1 && _mapLevel !== 2) {
            alertWarning("링크/정보제공구간 중 선택 하여야 합니다.");
            return;
        }
        const node = [...trafficMap.get('node')];
        if (_mapLevel === 1) {
            data = [...trafficMap.get('link')]; // 링크정보 요청
            vrtx = trafficMap.get('link1');
        } else if (_mapLevel == 2) {
            data = [...trafficMap.get('ifsc')]; // 정보제공구간정보 요청
            vrtx = trafficMap.get('ifsc2');
        }
        _mapManager.makeLayer(LayerIndex.Node, node);
        _mapManager.makeTrafficObject(_lyrType, data);
        _mapManager.makeLayer(_lyrIdx, vrtx);
        const linkData = [];
        if(_mapLevel === 1){
            data.map((obj)=>{
                const item = {...obj};
                if(item.link_id) item.id = item.link_id;
                if(item.road_name) item.name = item.road_name;
                if(item.from_node) item.strt_nm = item.from_node;
                if(item.to_node) item.end_nm = item.to_node;
                linkData.push(item);
            });
        } else if(_mapLevel === 2){
            data.map((obj)=>{
                const item = {...obj};
                if(item.ifsc_id) item.id = item.ifsc_id;
                if(item.ifsc_nm) item.name = item.ifsc_nm;
                linkData.push(item);
            });
        }
        _nodeTableList.dxDataGrid("instance").option("dataSource", node);
        _ifscTableList.dxDataGrid("instance").option("dataSource", linkData);
    }
    
    
    function deleteRow(){
        const keys = _selectSectionList.getSelectedRowKeys();
        if(keys.length === 0) return;
        _mapManager.updateEditLink(_lyrIdx, keys[0], 0, false);
        _selObjMap.delete(keys[0]);
        _selectSectionList.deleteRow(_selectSectionList.getRowIndexByKey(keys[0]));
        _selectSectionList.saveEditData();
        _selectSectionList.option('focusedRowIndex', -1);
    }
    
    function nodeTalbleListDblClick(nodeObj){
        _mapManager.selectPos(nodeObj.x_crdn, nodeObj.y_crdn);
    }
    
    function ifscTableListDblClick(rowData){
        const nodeObj = _mapManager.findLayerObject(LayerIndex.Node, rowData.t_node_id);
        if (nodeObj) {
            _mapManager.selectPos(nodeObj.xCrdn, nodeObj.yCrdn);
        }
    }
    
    function insertData(){
        const dataSource = _selectSectionList.option('dataSource');
        if (_selObjMap.size === 0) return alertWarning('선택된 데이터가 없습니다.');
        window.opener.inserLinkText(dataSource);
        window.close();
    }
    
    