import { TMapMngr, TFclt } from "/js/vworld/map-mngr.js";
import { LayerType, LayerIndex } from "/js/vworld/map-const.js";

let _mapManager = null;
let _selectFcltNmbr = null;
const _lyrIdx = LayerIndex.Crs;
const _cdUri  = '/api/database/code/cmmn-cd';
//우측 섹션 관련
let _managerData    = [];
let _managerTable   = null;
let _idArr          = [];
let ixrId           = null;
let ixrNm           = null;
let ixrXCrdn        = null;
let ixrYCrdn        = null;
let ixrType         = null;
let saveBtn         = null;
let cancleBtn       = null;
let addBtn          = null;
let delBtn          = null;
let editBtn         = null;
let sgnlIxrNmbr     = null;
let addNum          = 0;
let dvsn;
let _modalText;
let _modalSaveBtn;
let _modalCancelBtn;
let _modalXBtn;
let useEn;
let spotFetr;
let phasCnt;

const _updateColumns = {
    dvsn: 0,
    ixr_id: null,
    ixr_nm: null,
    ixr_type: 0,
    ixr_x_crdn: null,
    ixr_y_crdn: null,
    phas_cnt: 0,
    spot_fetr: null,
    sgnl_ixr_nmbr: 0,
    use_en: 1,
}
//공통
let commonUri = "/api/scrs/tb_sc_ixr_mngm";
const _pageName = '교차로 기본정보 관리';
const pageMsg = "교차로";
const inputArr = [
    (ixrId = {
        box      : null,
        option   : 240,
        disabled : true,
        label    : "교차로 ID",
        column   : "ixr_id",
        id       : true,
        max      : 10,
        must     : true,
    }),
    (ixrNm = {
        box      : null,
        option   : 350,
        disabled : false,
        label    : "교차로 명칭",
        column   : "ixr_nm",
        max      : 50,
        must     : true,
    }),
    (dvsn = {
        select   : true,
        box      : null,
        option   : 150,
        disabled : false,
        label    : "구분",
        must     : true,
        value    : 0,
        column   : "dvsn",
        display  : "cmmn_cd_kor_nm",
        max: null,
    }),
    (ixrType = {
        box      : null,
        select   : true,
        option   : 160,
        label    : "유형(차선)",
        disabled : false,
        must     : true,
        column   : "ixr_type",
        display  : "cmmn_cd_kor_nm",
        value    : 2,
    }),
    (spotFetr = {
        box      : null,
        select   : true,
        option   : 240,
        label    : "지점특성",
        disabled : false,
        must     : true,
        value    : 0,
        display  : "cmmn_cd_kor_nm",
        column   : "spot_fetr",
    }),
    (sgnlIxrNmbr = {
        box      : null,
        no       : true,
        option   : 120,
        label    : "신호교차로번호",
        disabled : false,
        must     : false,
        column   : "sgnl_ixr_nmbr",
        value    : 1,
        max      : 9999,
        min      : 1,
    }),
    (phasCnt = {
        box      : null,
        no       : true,
        option   : 80,
        label    : "현시수",
        disabled : false,
        must     : false,
        column   : "phas_cnt",
        value    : 1,
        max      : 9,
        min      : 1,
    }),
    (ixrXCrdn = {
        box      : null,
        option   : 150,
        label    : "X좌표",
        disabled : false,
        must     : true,
        value    : "0.0000000",
        method: function(e){
            crdnChanges(e, 3);
        },
        column: "ixr_x_crdn",
        max: 11,
    }),
    (ixrYCrdn = {
        box      : null,
        option   : 150,
        disabled : false,
        label    : "Y좌표",
        must     : true,
        value    : "0.0000000",
        method: function(e){
            crdnChanges(e, 2);
        },
        column: "ixr_y_crdn",
        max: 10,
    }),
    (useEn = {
        box      : null,
        select   : true,
        option   : 150,
        disabled : false,
        label    : "사용여부",
        must     : true,
        value    : 1,
        column   : "use_en",
        display  : "cmmn_cd_kor_nm",
        max: 10,
    }),
];

const btnArr = [
    (editBtn = {
        class: "edit-btn",
        box: null,
        option: 80,
        visible: true,
        disabled: true,
        dbdsb: false,
        edit: {
            click: {
                visible: false,
                disabled: false,
            },
            cancle: {
                visible: true,
                disabled: false,
            },
        },
        add: {
            click: {
                visible: false,
                disabled: false,
            },
            selected: {
                visible: true,
                disabled: false,
            },
            unSelected: {
                visible: true,
                disabled: true,
            },
        },
        addvsb: false,
        icon: "edit",
        text: "편집",
        method: function () {
            editEvent();
        },
    }),
    (cancleBtn = {
        class: "cancle-btn",
        box: null,
        option: 80,
        visible: false,
        disabled: false,
        dbdsb: false,
        edit: {
            click: {
                visible: true,
                disabled: false,
            },
            cancle: {
                visible: false,
                disabled: false,
            },
        },
        add: {
            click: {
                visible: true,
                disabled: false,
            },
            selected: {
                visible: false,
                disabled: false,
            },
            unSelected: {
                visible: false,
                disabled: false,
            },
        },
        addvsb: true,
        icon: "close",
        text: "취소",
    }),
    (addBtn = {
        class: "add-btn",
        box: null,
        option: 80,
        disabled: false,
        visible: true,
        edit: {
            click: {
                visible: true,
                disabled: true,
            },
            cancle: {
                visible: true,
                disabled: false,
            },
        },
        add: {
            click: {
                visible: true,
                disabled: true,
            },
            selected: {
                visible: true,
                disabled: false,
            },
            unSelected: {
                visible: true,
                disabled: false,
            },
        },
        dbdsb: false,
        adddsb: true,
        icon: "plus",
        text: "추가",
        method: function () {
            addEvent();
        },
    }),
    (delBtn = {
        class: "del-btn",
        box: null,
        option: 80,
        disabled: true,
        visible: true,
        edit: {
            click: {
                visible: true,
                disabled: true,
            },
            cancle: {
                visible: true,
                disabled: false,
            },
        },
        add: {
            click: {
                visible: true,
                disabled: true,
            },
            selected: {
                visible: true,
                disabled: false,
            },
            unSelected: {
                visible: true,
                disabled: true,
            },
        },
        dbdsb: false,
        adddsb: true,
        icon: "minus",
        text: "삭제",
        method: function () {
            delEvent();
        },
    }),
    (saveBtn = {
        class: "save-btn",
        box: null,
        option: 80,
        disabled: true,
        dbdsb: true,
        edit: {
            click: {
                visible: true,
                disabled: false,
            },
            cancle: {
                visible: true,
                disabled: true,
            },
        },
        add: {
            click: {
                visible: true,
                disabled: false,
            },
            selected: {
                visible: true,
                disabled: true,
            },
            unSelected: {
                visible: true,
                disabled: true,
            },
        },
        adddsb: false,
        visible: true,
        icon: "save",
        text: "저장",
    }),
];

$(() => {

    $("body").append(modalDiv);
    $(".modal-title").prepend($("<div>교차로 ID</div>"));
    $(".modal-background").css("display",'none');
    $(".modal-content").append($("<div class='modal-content-title'>")
        .html("교차로 ID를 입력하십시오."),$("<div class='modal-text'>"));

    _modalText      = new dxTxt($('.modal-text'), 'cmra_id', 10, '교차로 ID', 250, null, null, false, null);
    _modalSaveBtn   = new dxBtn($('.modal-save-Btn'),  '적용', 'check', 'outlined', null, null, false, true);
    _modalCancelBtn = new dxBtn($('.modal-cancle-Btn'),'취소', 'close', 'outlined', null, null, false, true);
    _modalXBtn      = new dxBtn($('.modal-cancle'), null, 'close', 'text', null, null, false, true);
    _modalText.onEnterKey(modalSaveEvent);
    _modalSaveBtn.onClick(modalSaveEvent);
    _modalCancelBtn.onClick(modalCloseEvent);
    _modalXBtn.onClick(modalCloseEvent);
    const closeBtn = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', null, null, false, true);
    closeBtn.onClick(()=>window.close());

    inputArr.map((item) => {
        if (item.select) {
            item.box = new dxSelect($("." + item.column), 'outlined', item.option, 27, item.display, 'cmmn_cd', true, item.column, item.label);
        }
        else if (item.no) {
            item.box = new dxNumber($("." + item.column), 'outlined', item.option, 27, item.min, item.max, true, null, item.column, null, true);
        }
        else {
            item.box = new dxTxt($("." + item.column), item.column, item.max, item.label, item.option, 27, null, true, null); 
            if (item.method) {
                item.box.onValueChanged(item.method);
            }
        }
    });
   
    btnArr.map((item) => {
        item.box = $("." + item.class)
            .dxButton({
                icon: item.icon,
                width: item.option,
                text: item.text,
                visible: item.visible,
                disabled: item.disabled,
                focusStateEnabled: false,
                stylingMode: "outlined",
                onClick() {
                    if (item.method) {
                        item.method();
                    }
                },
            })
            .dxButton("instance");
    });

    // 시설물 정보를 읽어 온다.
    getData(commonUri + '/list', _managerData);

    // 지도객체 생성
    doMap();

    updateIcon();

    //소통정보 이력분석 테이블
    _managerTable = $(".manager-table")
        .width("100%")
        .height("100%")
        .dxDataGrid({
            dataSource: _managerData[0],
            allowColumnReordering: true,
            showColumnLines: true,
            showBorders: true,
            allowColumnResizing: true,
            rowAlternationEnabled: true,
            focusedRowEnabled: true,
            columnAutoWidth: true,
            noDataText: "표출할 정보가 없습니다.",
            selection: {
                mode: "single",
            },
            keyExpr: "ixr_id",

            headerFilter: {
                visible: true,
            },
            scrolling: {
                mode: "virtual",
            },
            columns: [
                {
                    dataField: "ixr_id",
                    caption: "교차로 ID",
                    alignment: "center",
                    sortOrder : 'asc',
                    sortIndex : 1,
                },
                {
                    dataField: "ixr_nm",
                    caption: "교차로 명칭",
                    alignment: "center",
                    cellTemplate(c, e) {
                        return alignTemplate(c, e, 'left');
                    },
                },
                {
                    dataField: "ixr_type",
                    caption: "교차로 유형",
                    alignment: "center",
                    lookup : {
                        dataSource  : null,
                        valueExpr   : 'cmmn_cd',
                        displayExpr : 'cmmn_cd_kor_nm',
                    }
                },
                {
                    dataField: "spot_fetr",
                    caption: "지점 특성",
                    alignment: "center",
                    lookup : {
                        dataSource  : null,
                        valueExpr   : 'cmmn_cd',
                        displayExpr : 'cmmn_cd_kor_nm',
                    }
                },
                {
                    dataField: "sgnl_ixr_nmbr",
                    caption: "신호교차로번호",
                    alignment: "center",
                },
                {
                    dataField: "ixr_x_crdn",
                    caption: "X 좌표",
                    alignment: "center",
                },
                {
                    dataField: "ixr_y_crdn",
                    caption: "Y 좌표",
                    alignment: "center",
                },
                {
                    dataField: "phas_cnt",
                    caption: "현시",
                    alignment: "center",
                },
                {
                    dataField: "dvsn",
                    caption: "구분",
                    alignment: "center",
                    lookup : {
                        dataSource  : null,
                        valueExpr   : 'cmmn_cd',
                        displayExpr : 'cmmn_cd_kor_nm',
                    }
                },
                {
                    dataField: "use_en",
                    caption: "사용 유무",
                    alignment: "center",
                    lookup : {
                        dataSource : [],
                        valueExpr   : 'cmmn_cd',
                        displayExpr : 'cmmn_cd_kor_nm',
                    }
                },
            ],
            onRowDblClick(e) {
                _selectFcltNmbr = e.data.ixr_id;
                selectFcltObject(_selectFcltNmbr);
                inputArr.map((item) => {
                    item.box.setValue(e.data[item.column]);
                    console.log(e.data[item.column]);
                });

                btnArr.map((item) => {
                    item.box.option("disabled", item.dbdsb);
                });
            },
        })
        .dxDataGrid("instance");

    fetchCdData();
});


function modalSaveEvent(){
    const idArr = getIdArr();
    const ixrIdVal = _modalText.getValue();
    const label = _modalText.label;
    if (_modalText.isNull()) {
        return alertWarning(label + "를 입력해주세요.", null, _modalText);
    }
    else if (idArr.includes(ixrIdVal)) {
        return alertWarning(label + " : " + ixrIdVal + "<br>이미 사용중인 " + label + "입니다.", null, _modalText);
    }
    else if (_modalText.getByte() > _modalText.max){
        return alertWarning(label + "를 "+ _modalText.max +"바이트 이내로 입력해주세요.", null, _modalText);
    }
    else  {
        modalCloseEvent();
        eventOn();
        boxInit(true);
        let center = _mapManager.getCenter();
        cancleBtn.box.off("click");
        cancleBtn.box.on("click", () => addCancel());
        ixrXCrdn.box.setValue(center[0].toFixed(7));
        ixrYCrdn.box.setValue(center[1].toFixed(7));
        addFcltObject(ixrIdVal);
        _selectFcltNmbr = ixrIdVal;
        ixrId.box.setValue(ixrIdVal);
        
        btnArr.map((item) => {
            item.box.option("visible", item.add.click.visible);
            item.box.option("disabled", item.add.click.disabled);
        });
        saveBtn.box.off('click');
        saveBtn.box.on('click', () => saveEvent('add'));
    }
}
function modalCloseEvent(){
    modalDiv.css('display', 'none');
    _modalText.setValue(null);
}
function fetchCdData(){
    getDataAsync(_cdUri + '/DVSN', recvCdData, [dvsn.box, 8]);
    getDataAsync(_cdUri + '/USEEN', recvCdData, [useEn.box, 9]);
    getDataAsync(_cdUri + '/IXRTYPE', recvCdData, [ixrType.box, 2]);
    getDataAsync(_cdUri + '/SFETR', recvCdData, [spotFetr.box, 3]);
};

function recvCdData(jsonData, args){
    const box = args[0];
    const idx = args[1];
    if (box) {
        box.setDataSource(jsonData);
    }
    if (jsonData.length > 0 && idx !== 3) {
        jsonData.map( (item) => {
            if (item.cmmn_cd) item.cmmn_cd = Number(item.cmmn_cd);
        })
    }
    _managerTable.option('columns['+ idx + '].lookup.dataSource', jsonData);
    
}

function editEvent() {
    editFcltObject(_selectFcltNmbr, true);
    cancleBtn.box.off("click");
    cancleBtn.box.on("click", () => editCancel());

    eventOn();

    btnArr.map((item) => {
        item.box.option("visible", item.edit.click.visible);
        item.box.option("disabled", item.edit.click.disabled);
    });

    saveBtn.box.off('click');
    saveBtn.box.on('click', () => saveEvent('edit'));
}

function editCancel() {
    updateIcon();
    eventCancel();
    boxPull();
    buttonReset("edit", "cancle");
}
function getIdArr(){
    let idArr = [];
    if (_managerData[0].length > 0) {
        _managerData[0].map((obj)=>{
            if(obj.ixr_id)idArr.push(obj.ixr_id);
        })
    }
    return idArr;
}
function saveEvent(type) {
    _idArr = getIdArr();
    for (let input of inputArr) {
        const box   = input.box;
        const value = box.getValue();
        const max   = input.max;
        const label = input.label;
        const empty = nullChecker(value) === "";
        if (empty) {
            if (input.must) {
                return  alertWarning( "필수 항목을 입력해주세요. [ " + label +" ]", null, box);
            }
        }
        else {
            if (max && getByteLength(value) > max) {
                return alertWarning( max + " 바이트 이내로 입력해주세요. [ " + label +" ]", null, box);
            }
            if (input.expr && !input.expr.test(value)) {
                return alertWarning("IP 형식에 맞게 입력해주세요. [ " + label +" ]", null, box);
            }
            if (input.port && isNaN(value)) {
                return alertWarning("PORT 형식에 맞게 입력해주세요. [ " + label + " ]", null, box);
            }
            if (input.id && _idArr.includes(value) && type === "add") {
                    return alertWarning( "교차로 ID : " + value + "<br>이미 사용중인 교차로 ID 입니다.", null, box);
            }
        }
    }
    let updateData = {..._updateColumns};

    if (type === 'edit') {
        // 수정모드일 경우에는....
        const rowData = _managerTable.getSelectedRowsData()[0];
        for (let key in updateData) {
            updateData[key] = rowData[key];
        }
        const idVal = ixrId.box.getValue();
        if (_idArr.includes(idVal) && idVal !== rowData.ixr_id){
            return alertWarning( "교차로 ID : " + idVal + "<br>이미 사용중인 교차로 ID 입니다.", null, ixrId.box);
        }
    }

    inputArr.map((item) => {
        if (item.column) {
            updateData[item.column] = item.box.getValue();
        }
    });
    console.log(updateData);
    const ixrIdVal = updateData.ixr_id
    let result = postInsertUpdate("/api/scrs/tb_sc_ixr_mngm/" + ixrIdVal, updateData);
    if (result > 0) {
        insResultMsg(pageMsg);
        _managerData = refresh(_managerTable, _managerData, commonUri + '/list');
        _managerTable.clearSelection();
        _managerTable.refresh().done(function () {
            _managerTable.selectRows(ixrIdVal, true).done(()=>{
                _managerTable.option("focusedRowKey", ixrIdVal);
                boxPull();
                buttonReset("add", "selected");
                updateIcon();
                eventCancel();
            });
        });
    }
}

function delEvent(){
    const ixrIdVal = _managerTable.getSelectedRowsData()[0].ixr_id;
    confirmMessage(pageMsg
        + " ID : "
        + ixrIdVal
        + "<br>선택하신 " + pageMsg + " 정보를 삭제하시겠습니까?").done((yes)=>{
        if (yes === true) {
            const result = deleteData('/api/scrs/tb_sc_ixr_mngm', ixrIdVal);
            if (result > 0) {
                delResultMsg(pageMsg);
                boxInit();
                buttonReset("add", "unSelected");
                _managerTable.option("focusedRowKey", null);
                _managerData = refresh(_managerTable, _managerData, commonUri + '/list');
                deleteFcltObject(ixrIdVal);
            }
        }
    });
}

function addCancel() {
    updateIcon();
    eventCancel();

    if (_managerTable.getSelectedRowsData().length > 0) {
        boxPull();
        buttonReset("add", "selected");
        return;
    }

    boxInit();
    buttonReset("add", "unSelected");
}

function addEvent() {
    modalDiv.css('display', 'flex');
    _modalText.focus();
}

function boxPull() {
    let selectedRow = _managerTable.getSelectedRowsData()[0];
    inputArr.map((item) => {
        item.box.setValue(selectedRow[item.column]);
    });
}

function boxInit(type) {
    inputArr.map((item) => {
        if (nullChecker(item.value) !== "" && type) return item.box.setValue(item.value);
        item.box.setValue(null)
    });
}

function buttonReset(eventName, option) {
    btnArr.map((item) => {
        item.box.option("visible", item[eventName][option].visible);
        item.box.option("disabled", item[eventName][option].disabled);
    });
}

function eventCancel() {
    dsblOffBtn(_managerTable);

    inputArr.map((item) => {
        item.box.setReadOnly(true);
    });

    if(_managerTable.getSelectedRowsData().length > 0){
        _selectFcltNmbr = _managerTable.getSelectedRowsData()[0].ixr_id;
        selectFcltObject(_selectFcltNmbr);
    }
}

function eventOn() {
    dsblOnBtn(_managerTable);

    inputArr.map((item) => {
        item.box.setReadOnly(item.disabled);
    });
}

/**
 * 제어기 신규 ID 조회
 */
function getNewNmbr() {
    let newId = [];
    getData(commonUri + "/new-id", newId);
    _selectFcltNmbr = newId[0].new_id;
    return _selectFcltNmbr;
}
/**
 * 지도 인터페이스 함수........
 */
function doMap() {
    _mapManager = new TMapMngr("traf-hs-map", "tooltip");
    _mapManager.setEditMode(_lyrIdx, true);
    _mapManager.showLayer(_lyrIdx, true);
    _mapManager.showFcltObjectText(_lyrIdx, true);
    _mapManager.onFcltDragEndFunc = onFcltDragEndFunc; // 객체(시설물) 편집시 객체 이동후 좌표 반환
    _mapManager.onMouseClickFunc = onMouseClickFunc; // 객체 마우스 클릭 이벤트 반환
    fetchMapIconBar($('.map-bar'), _mapManager, _lyrIdx, _pageName);
}
function onFcltDragEndFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    if (ANmbr === _selectFcltNmbr) {
        ixrXCrdn.box.setValue(ACoordX.toFixed(7));
        ixrYCrdn.box.setValue(ACoordY.toFixed(7));
    }
    console.log(`onFcltDragEndFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}`);
}
function onMouseClickFunc(ALyrIdx, ALyrName, ANmbr, ACoordX, ACoordY, X, Y) {
    if (ALyrIdx != _lyrIdx) {
        return;
    }
    console.log(`onMouseClickFunc, ${ALyrIdx}, ${ALyrName}, ${ANmbr}, ${ACoordX}, ${ACoordY}, ${X}, ${Y}`);
    const obj = _mapManager.findLayerObject(ALyrIdx, ANmbr);
    if (!obj) {
        return;
    }
}

/**
 * 지도에 시설물 객체 정보를 그린다.
 */
function updateIcon() {
    // 기존 객체를 모두 삭제한다.
    _mapManager.removeLayerObject(_lyrIdx);

    if (_managerData[0] && _managerData[0].length > 0) {
        // 시설물 객체를 지도에 그린다.
        const objs = new Array();
        _managerData[0].forEach((obj) => {
            const item = new TFclt(obj.ixr_id, obj.ixr_nm, obj.ixr_x_crdn, obj.ixr_y_crdn);
            objs.push(item);
        });
        _mapManager.initFcltObject(_lyrIdx, objs);
    }

}
function selectFcltObject(ANmbr) {
    _mapManager.selectLayerObject(_lyrIdx, ANmbr);
}
function editFcltObject(ANmbr, AIsEdit) {
    _mapManager.editFcltObject(_lyrIdx, ANmbr, AIsEdit, AIsEdit ? "1" : "0");
}
function deleteFcltObject(ANmbr) {
    _mapManager.deleteFcltObject(_lyrIdx, ANmbr);
    _selectFcltNmbr = null;
}
function addFcltObject(ANmbr) {
    _mapManager.createFcltObject(_lyrIdx, ANmbr, "New", "New", "1" /*아이콘색결정,시설물유형_N.png*/ /*, x_crdn, y_crdn*/);
}
