import { currDt } from "/js/utils/common.js";
import { requestGet, apiGet } from "/js/utils/restApi.js";
import { LayerIndex } from "/js/vworld/map-const.js";
import { _mapManager } from "./main-func.js";

Proj4js.defs["EPSG:2097"] = "+proj=tmerc +lat_0=38.0028295 +lon_0=127.000784 +k=1 +x_0=200000 +y_0=500000 +ellps=bessel +units=m +no_defs";
Proj4js.defs["EPSG:4004"] = "+proj=longlat +ellps=bessel +no_defs";
const epsg2097 = new Proj4js.Proj("EPSG:2097");
const epsg4004 = new Proj4js.Proj("EPSG:4004");

const _polylineOverlay = new ol.Overlay({ element: document.getElementById("polylineOverlay") });
export const _vmsOverlay = new ol.Overlay({ element: document.getElementById("vmsOverlay") });
export const _cctvOverlay = new ol.Overlay({ element: document.getElementById("cctvOverlay") });
const _overlay = new ol.Overlay({ element: document.getElementById("overlay") });
const _busOverlay = new ol.Overlay({ element: document.getElementById("busOverlay") });
const _bitOverlay = new ol.Overlay({ element: document.getElementById("bitOverlay") });
const _incdOrccOverlay = new ol.Overlay({ element: document.getElementById("incdOrccOverlay") });
const _overlayArr = [_overlay, _polylineOverlay, _vmsOverlay, _cctvOverlay, _busOverlay, _bitOverlay, _incdOrccOverlay];
/**
 * BIS Functions
 */
class TLineStation {
    constructor(stationId, dir, left, top, coordx, coordy, stationName) {
        this.stationId = stationId;
        this.dir = dir;
        this.left = left;
        this.top = top;
        this.coordx = coordx;
        this.coordy = coordy;
        this.stationName = stationName;
    }
}
class TLineBus {
    constructor(vehId, plateNo, stationId, eventCode, eventCodeName, coordx, coordy, busrouteName, stationName, collectDate) {
        this.vehId = vehId;
        this.plateNo = plateNo;
        this.stationId = stationId;
        this.eventCode = eventCode;
        this.coordx = coordx;
        this.coordy = coordy;
        this.busrouteName = busrouteName;
        this.stationName = stationName;
        this.collectDate = collectDate;
        this.eventCodeName = eventCodeName;
    }
}
const _bitImage = "/images/application_wall/BIT_0.png";
const _busImage = "/images/application_wall/BUS.png";
let _selectBusLineRouteId = ""; // 좌측 노선 메뉴에서 선택한 노선번호
let _selectBusLineStationArr = []; // 좌측 노선 메뉴에서 선택한 노선의 정류장 배열
let _selectBusLineBusArr = []; // 좌측 노선 메뉴에서 선택한 노선의 운행중인 버스 배열
let _selectBusLineBusMap = new Map(); // 좌측 노선 메뉴에서 선택하 노선의 운행중인 버스 맵
let _selectBusLineMapHtml = "";
let _timerSelectBusLineBus = null;
const requestSelectBusLineBus = (ABusRouteId) => {
    if (_timerSelectBusLineBus) window.clearTimeout(_timerSelectBusLineBus);
    _timerSelectBusLineBus = window.setTimeout(() => selectBusLineBus(ABusRouteId), 50 * 1000);
};

const _StationLayerIdx = LayerIndex.Station;
const _BitLayerIdx = LayerIndex.Bit2;
const _BusLayerIdx = LayerIndex.Bus;
const _PositionLayerIdx = LayerIndex.Position;
export function initBisMap() {
    _mapManager.showLayer(_StationLayerIdx, false);
    _mapManager.showLayer(_BitLayerIdx, false);
    _mapManager.showLayer(_BusLayerIdx, false);
    _mapManager.showLayer(_PositionLayerIdx, false);

    _mapManager.setLayerName(_StationLayerIdx, "정류장");
    _mapManager.setLayerName(_BusLayerIdx, "BUS");
    _mapManager.setLayerName(_BitLayerIdx, "BIT");

    _mapManager.setLayerImage(_StationLayerIdx, "/images/application_wall/station_");
    _mapManager.setLayerImage(_BusLayerIdx, "/images/application_wall/bus_");
    _mapManager.setLayerImage(_BitLayerIdx, "/images/application_wall/bit_");

    // _mapManager.setLayerTooltip(_StationLayerIdx, false);
    // _mapManager.setLayerTooltip(_BusLayerIdx, false);
    // _mapManager.setLayerTooltip(_BitLayerIdx, false);

    _mapManager.setOverlay(_overlayArr);
}
export function showBisMap() {
    showBisLayer(true);
}
// BIS 지도 화면 종료
export function hideBisMap() {
    clearBisMap();
    _overlayArr.forEach((el) => {
        el.setPosition(undefined);
    });
    showBisLayer(false); // BIS 지도 숨기기
    if (_timerSelectBusLineBus) window.clearTimeout(_timerSelectBusLineBus);
}
// BIS 지도 객체 초기화
function clearBisMap() {
    _mapManager.showLayer(_StationLayerIdx, false);
    _mapManager.showLayer(_BitLayerIdx, false);
    _mapManager.showLayer(_BusLayerIdx, false);

    _mapManager.removeLayerObject(_StationLayerIdx);
    _mapManager.removeLayerObject(_BitLayerIdx);
    _mapManager.removeLayerObject(_BusLayerIdx);
}
// 정보창 팝업 클리어
export function initLeftMenuClick() {
    _selectBusLineRouteId = "";
    _selectBusLineStationArr = [];
    _selectBusLineBusMap.clear();
    // BIT popup
    $("#bitOverlay").empty();
    _bitOverlay.setPosition(undefined);
    // BUS popup
    $("#busOverlay").empty();
    _busOverlay.setPosition(undefined);
    // VMS popup
    $("#vmsOverlay").empty();
    _vmsOverlay.setPosition(undefined);
    _mapManager.hideObjectPosition();
}

function showBisLayer(AShow) {
    _mapManager.showEventGroupLayer(AShow);
}

let _selectLeftMenu = 0; // 0: BIT, 1: BUS, 2: 노선
export function leftBitMenuClick() {
    _selectLeftMenu = 0;
    clearBisMap();
    fetchBitList("");
}
export function leftBusMenuClick() {
    _selectLeftMenu = 1;
    clearBisMap();
    fetchBusVehicleList("");
}
export function leftLineMenuClick() {
    _selectLeftMenu = 2;
    clearBisMap();
    fetchBusStationList("");
}
export function leftMenuSearchClick() {
    const searchVal = $("#busSearch").val();
    switch (_selectLeftMenu) {
        case 0: // BIT
            fetchBitList(searchVal);
            break;
        case 1: // BUS
            fetchBusVehicleList(searchVal);
            break;
        case 2: // LINE
            fetchBusStationList(searchVal);
            break;
    }
}

const apiUrl = "http://115.91.94.42:8999";
//검색버튼 이벤트(왼쪽의 리스트만 변경되므로 쿼리를 변경...)
function fetchBitList(searchVal) {
    requestGet("/api/bis/wall/bit-search/" + searchVal, recvBitList);
}
function recvBitList(jsonData) {
    let backgroundColor;
    let str = "";
    // 지도에 추가해주자.........
    jsonData.forEach((el, idx) => {
        if (idx % 2 == 0) backgroundColor = "#ffffff";
        else backgroundColor = "#ebebeb";
        str +=
            '<span style="background-color:' +
            backgroundColor +
            '"><a href="#" onclick="leftBitListClick(' +
            el.bitid +
            ",'" +
            el.bitname +
            "'," +
            el.coordx +
            "," +
            el.coordy +
            ",'" +
            el.wcommstatus +
            "')\" ><span>" +
            el.bitname +
            "</span></a></span>";
    });
    $("#busList").empty().html(str);
}

function fetchBusVehicleList(searchVal) {
    requestGet("/api/bis/wall/bus-vehicle-plate/" + searchVal, recvBusVehicleList);
}
function recvBusVehicleList(jsonData) {
    let backgroundColor;
    let str = "";
    jsonData.forEach((el, idx) => {
        if (idx % 2 == 0) backgroundColor = "#ffffff";
        else backgroundColor = "#ebebeb";
        str +=
            '<span style="background-color:' +
            backgroundColor +
            '"><a href="#" onclick="leftBusListClick(\'' +
            el.vehid +
            '\',true)" alt="' +
            el.plateno +
            '"><span>' +
            el.plateno +
            "</span></a></span>";
    });
    $("#busList").html(str);
}
function leftBusListClick(AVehId, AIsClick) {
    //console.log("leftBusListClick: ", AVehId, AIsClick);
    requestGet("/api/bis/wall/draw/bus-marker/" + AVehId, busPopupInfoBox);
}
window.leftBusListClick = leftBusListClick;

function busPopupInfoBox(jsonData) {
    //경기70바1048
    //console.log("busPopupInfoBox", jsonData.length, jsonData);
    initLeftMenuClick();
    if (jsonData.length == 0) {
        alertWarning("정보가 없습니다.");
        return;
    }
    const el = jsonData[0];
    const x = el.coordx;
    const y = el.coordy;
    //const url = "/images/application_wall/onBUS.png"; 지도아이콘
    let infoContent =
        "<div id=\"busVehicleInfo\" style=\"position:absolute;width:340px;height:310px;z-index:10;color:white;font-family:'RixSGo EB';font-weight:600;font-size:14px;background-image:url('/images/application_wall/bis/BUSPopUp.png')\">";
    infoContent += '<img id="busVehicleInfoClose" src="/images/application_wall/xbtn.png" alt="버스정보창 닫기" style="position:absolute;top:10px;right:15px;cursor:pointer" />';
    infoContent += '<p style="position:absolute;top:10px;left:100px;width:150px">' + el.plateno + "</p>";
    infoContent += '<p style="position:absolute;top:72px;left:30px;width:100px">' + el.busroutename + "</p>";
    infoContent += '<p style="position:absolute;top:72px;left:165px;width:80px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap">' + el.stationname + "</p>";
    infoContent += '<p style="position:absolute;top:72px;left:253px;width:80px">' + el.eventcode + "</p>";
    infoContent += '<p style="position:absolute;top:195px;left:16px;width:150px">' + el.collectdate + "</p>";
    infoContent += '<p style="position:absolute;top:195px;left:165px;width:80px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap">' + el.stationname + "</p>";
    infoContent += '<p style="position:absolute;top:195px;left:253px;width:80px">' + el.eventcode + "</p>";
    infoContent += "</div>";

    $("#busOverlay").html(infoContent);
    _busOverlay.setPosition([x, y]);

    //_mapManager.movePos( x, y );
    _mapManager.showObjectPosition(x, y, _busImage);

    $("#busVehicleInfoClose").on("click", function () {
        initLeftMenuClick();
    });
}

function fetchBusStationList(searchVal) {
    requestGet("/api/bis/wall/bus-routes/" + searchVal, recvBusStationList);
}
function recvBusStationList(jsonData) {
    let backgroundColor;
    let str = "";
    jsonData.forEach((el, idx) => {
        if (idx % 2 == 0) backgroundColor = "#ffffff";
        else backgroundColor = "#ebebeb";
        str +=
            '<span style="background-color:' +
            backgroundColor +
            '"><a href="#" onclick="selectBusLine(' +
            el.busrouteid +
            "," +
            el.busroutetype +
            ')" ><span><img src="/images/application_wall/busType_' +
            el.busroutetype +
            '.png" alt="버스유형" />&nbsp;&nbsp;' +
            el.busroutename +
            "</span></a></span>";
    });
    $("#busList").html(str);

    if (jsonData.length > 0) {
        // 리스트의 첫번째 노선 번호로 화면을 그린다.
        selectBusLine(jsonData[0].busrouteid, jsonData[0].busroutetype);
    }
}

// 좌측 노선 리스트에서 노선 정보 클릭
// 노선에 운행 중인 버스 정보 조회
// 노선의 정류장 정보 조회
// 노선의 폴리건 정보 조회(정보가 일치하지 않아 사용하지 않음)
async function selectBusLine(ABusRouteId, ABusType) {
    //console.log("selectBusLine: ", ABusRouteId);
    if (_selectBusLineRouteId != ABusRouteId) {
        _selectBusLineRouteId = ABusRouteId;
    }
    /**
     * 1. 선택한 노선의 정류장 정보를 조회한다.
     * 2. 선택하 노선의 경로 정보를 조회한다.(데이터가 정확하지 않아 사용하지 않기로 함)
     */
    console.time("***** selectBusLine: ");
    const station = apiGet("/api/bis/wall/draw/bus-station/" + ABusRouteId); // station
    //const route = apiGet("/api/bis/wall/draw/bus-route/" + ABusRouteId); // route
    Promise.all([station])
        .then((results) => Promise.all(results.map((r) => r.json())))
        .then((values) => {
            // 지도에 정류장 정보를 그린다.
            drawBusLineStation(values[0], ABusRouteId);
            //drawBusRoute(values[1], ABusRouteId);
        })
        .catch((err) => {
            console.error(`${currDt()}: Error in selectBusLine ${err}`);
        })
        .finally(() => console.timeEnd("***** selectBusLine: "));
}
window.selectBusLine = selectBusLine;

function drawBusLineStation(jsonData, ABusRouteId) {
    _mapManager.makeEventLayer(_StationLayerIdx, jsonData);
    _mapManager.showLayer(_StationLayerIdx, true);
    _mapManager.extentLayer(_StationLayerIdx);

    drawBusLineMap(jsonData); // 하단에 선한 노선의 노선도를 그린다.
    selectBusLineBus(ABusRouteId); // 정류장을 그린 후 노선에 운행 중인 버스 정보를 조회한다.
}

// 선택한 노선의 운행 중인 버스 정보를 조회한다.
async function selectBusLineBus(ABusRouteId) {
    console.time("***** selectBusLineBus: ");
    if (_selectBusLineRouteId != ABusRouteId) {
        _selectBusLineRouteId = ABusRouteId;
    }
    const vehicle = apiGet("/api/bis/wall/draw/bus-vehicle/" + ABusRouteId); // bus
    Promise.all([vehicle])
        .then((results) => Promise.all(results.map((r) => r.json())))
        .then((values) => {
            drawBusLineBus(values[0], ABusRouteId);
            requestSelectBusLineBus(ABusRouteId); // 타이머 호출하는 것임
        })
        .catch((err) => {
            console.error(`${currDt()}: Error in selectBusLineBus ${err}`);
        })
        .finally(() => console.timeEnd("***** selectBusLineBus: "));
}

//지도위 버스현위치
function drawBusLineBus(jsonData) {
    //var url = '/images/application_wall/onBUS.png';
    //console.log("drawBusLineBus: ", jsonData);

    _mapManager.makeEventLayer(_BusLayerIdx, jsonData);
    _mapManager.showLayer(_BusLayerIdx, true);

    _selectBusLineBusMap.clear();
    _selectBusLineBusArr = [];
    jsonData.forEach((el, idx) => {
        _selectBusLineBusArr.push(el);
        let busArr = _selectBusLineBusMap.get(el.stationid);
        if (!busArr) {
            busArr = new Array();
            _selectBusLineBusMap.set(el.stationid, busArr);
        }
        busArr.push(el);
    });
    //console.log(_selectBusLineBusMap);
    let busHtml = "";
    _selectBusLineStationArr.forEach((el, idx) => {
        const busArr = _selectBusLineBusMap.get(el.stationId);
        if (busArr) {
            busArr.forEach((bus, idx) => {
                busHtml +=
                    '<img src="/images/application_wall/BUS.png" style="z-index:30;position:absolute;left:' +
                    (el.left + 0) +
                    "px;top:" +
                    (el.top - 24) +
                    'px;cursor:pointer;z-index:40" onclick="busVehicleBottomEvent(' +
                    idx +
                    ',true)" title="' +
                    el.busrouteName +
                    '" />';
            });
        }
    });
    if (busHtml != "") {
        $("#busStationInfo").html(_selectBusLineMapHtml + busHtml);
    }
}

export function busVehicleBottomEvent(AOrder, busListClickEventId) {
    $("#busOverlay").empty();
    _busOverlay.setPosition(undefined);

    const busObj = _selectBusLineBusArr[AOrder];
    if (!busObj) {
        console.error("busVehicleBottomEvent: not found Bus order, ", AOrder);
        return;
    }
    let x = busObj.coordx + 0.0005;
    let y = busObj.coordy;
    let location = [x, y];

    let infoContent =
        "<div id=\"busVehicleInfo\" style=\"position:absolute;width:340px;height:310px;z-index:10;color:white;font-family:'RixSGo EB';font-weight:600;font-size:14px;background-image:url('/images/application_wall/bis/BUSPopUp.png')\">";
    infoContent += '<img id="busVehicleInfoClose" src="/images/application_wall/xbtn.png" alt="버스정보창 닫기" style="position:absolute;top:10px;right:15px;cursor:pointer" />';
    infoContent += '<p style="position:absolute;top:10px;left:100px;width:150px">' + busObj.plateno + "</p>";
    infoContent += '<p style="position:absolute;top:72px;left:30px;width:100px">' + busObj.busroutename + "</p>";
    infoContent += '<p style="position:absolute;top:72px;left:165px;width:80px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap">' + busObj.stationname + "</p>";
    infoContent += '<p style="position:absolute;top:72px;left:253px;width:80px">' + busObj.eventcodename + "</p>";
    infoContent += '<p style="position:absolute;top:195px;left:16px;width:150px">' + busObj.collectdate + "</p>";
    infoContent += '<p style="position:absolute;top:195px;left:165px;width:80px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap">' + busObj.stationname + "</p>";
    infoContent += '<p style="position:absolute;top:195px;left:253px;width:80px">' + busObj.eventcodename + "</p>";
    infoContent += "</div>";

    if (busListClickEventId) {
        // 하단 목록에서 버스를 클릭한 경우
        _mapManager.movePos(x, y);
    }
    $("#busOverlay").html(infoContent);
    _busOverlay.setPosition(location);

    infoContent += "</div>";

    $("#busVehicleInfoClose").on("click", function () {
        $("#busOverlay").empty();
        _busOverlay.setPosition(undefined);
    });
}
window.busVehicleBottomEvent = busVehicleBottomEvent;

// 좌측에서 선택한 노선의 정류장 맵을 하단 창에 그린다.
function drawBusLineMap(data) {
    $("#busStationInfo").empty();
    $("#busStationInfoLeft").empty();

    _selectBusLineStationArr = []; // 메모리에 선택한 노선의 정류장 맵을 저장한다.

    let str = "";
    let str2 = "";
    let busRouteFlg;

    let busrouteLength = commify(data[0].busroutelength);

    str2 += "<p style=\"position:absolute;top:56px;left:-75px;width:120px;color:white;font-size:15px;font-family:'RixSGo EB'\">" + data[0].busroutename + "</p>";
    str2 += "<p style=\"position:absolute;top:56px;left:170px;width:80px;color:white;font-size:15px;font-family:'RixSGo EB'\">" + busrouteLength + " km</p>";
    str2 +=
        '<p style="position:absolute;top:102px;left:-75px;color:white;font-size:15px;font-family:\'RixSGo EB\';width:150px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap" title="' +
        data[0].startstationname +
        '">' +
        data[0].startstationname +
        "</p>";
    str2 += "<p style=\"position:absolute;top:102px;left:170px;color:white;font-size:15px;font-family:'RixSGo EB'\">" + data.length + "</p>";
    str2 +=
        '<p style="position:absolute;top:146px;left:-75px;color:white;font-size:15px;font-family:\'RixSGo EB\';width:150px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;" title="' +
        data[0].endstationname +
        '">' +
        data[0].endstationname +
        "</p>";
    $("#busStationInfoLeft").append(str2);

    const stopCounts = 12;
    const stopWidth = 102;
    const heightSpan = 50;
    const startTop = 20;
    const startLeft = 45;
    let topPos;
    let leftPos;

    if (data.length < 2) {
        console.error("Bus Route Stop Count 0 or 1");
        return;
    }

    let idx = 0;
    topPos = startTop;
    leftPos = startLeft;
    //rightPos = startLeft + stopWidth * (stopCounts + 1);

    str += '<img src="/images/application_wall/BusLine_Start.png" style="position:absolute;left:32px;top:1px;z-index:20" />';
    str +=
        '<p style="position:absolute;top:' +
        (startTop + 20) +
        "px;left:" +
        (leftPos - 20) +
        'px;color:white;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;width:100px;text-align:center" title="' +
        data[0].stationname +
        '">' +
        data[0].stationname +
        "</p>";

    _selectBusLineStationArr.push(new TLineStation(data[0].stationid, 0, startLeft, startTop, data[0].coordx, data[0].coordy, data[0].stationname));

    //const maxMok = Math.floor(data.length / stopCounts);
    for (let ii = 1; ii < data.length; ii++) {
        idx = ii - 1;
        const stationName = data[ii].stationname;
        const remainVal = idx % stopCounts;
        const mok = Math.floor(idx / stopCounts);
        const dir = mok % 2;

        if (data[ii].turnseq >= data[ii].stationorder) {
            if (dir == 0) {
                busRouteFlg = "/images/application_wall/BusLine_UpStn.png";
            } else {
                busRouteFlg = "/images/application_wall/BusLine_UpStn2.png";
            }
        } else {
            if (dir == 0) {
                busRouteFlg = "/images/application_wall/BusLine_DnStn.png";
            } else {
                busRouteFlg = "/images/application_wall/BusLine_DnStn2.png";
            }
        }
        topPos = startTop + mok * heightSpan;
        if (dir == 0) {
            // 오른쪽 방향으로 그리기
            str += '<img src="/images/application_wall/BusLine1.png" style="position:absolute;left:' + leftPos + "px;top:" + topPos + 'px;z-index:10" />';
            leftPos = startLeft + stopWidth + stopWidth * remainVal;
            if (remainVal == stopCounts - 1 && ii != data.length - 1) {
                str += '<img src="/images/application_wall/BusLine1.png" style="position:absolute;left:' + leftPos + "px;top:" + topPos + 'px;z-index:10" />';
                str +=
                    '<img src="/images/application_wall/BusLine2.png" style="position:absolute;' +
                    "id=" +
                    ii +
                    ";left:" +
                    (leftPos + stopWidth - 11) +
                    "px;top:" +
                    (topPos + 7) +
                    'px;z-index:11" />';
            }
            if (remainVal == 0 && ii != data.length - 1) {
                str += '<img src="/images/application_wall/BusLine1.png" style="position:absolute;left:' + (leftPos - stopWidth) + "px;top:" + topPos + 'px;z-index:10" />';
            }
        } else {
            // 왼쪽 방향으로 그리기
            //leftPos = rightPos - stopWidth * ( remainVal + 1 );
            leftPos = startLeft + stopWidth * (stopCounts - remainVal);
            str += '<img src="/images/application_wall/BusLine1.png" style="position:absolute;left:' + leftPos + "px;top:" + topPos + 'px;z-index:10" />';
            if (remainVal == 0 && ii != data.length - 1) {
                str += '<img src="/images/application_wall/BusLine1.png" style="position:absolute;left:' + (leftPos - stopWidth) + "px;top:" + topPos + 'px;z-index:10" />';
            }
            if (remainVal == stopCounts - 1 && ii != data.length - 1) {
                str += '<img src="/images/application_wall/BusLine1.png" style="position:absolute;left:' + (leftPos - stopWidth) + "px;top:" + topPos + 'px;z-index:10" />';
                str +=
                    '<img src="/images/application_wall/BusLine2.png" style="position:absolute;' +
                    "id=" +
                    ii +
                    ";left:" +
                    startLeft +
                    "px;top:" +
                    (topPos + 7) +
                    'px;z-index:11" />';
            }
        }

        if (ii != data.length - 1) {
            str += '<img src="' + busRouteFlg + '" style="position:absolute;left:' + (leftPos - 20) + "px;top:" + (topPos - 13) + 'px;z-index:30" />';
        } else {
            str += '<img src="/images/application_wall/BusLine_End.png" style="position:absolute;left:' + (leftPos - 20) + "px;top:" + (topPos - 17) + 'px;z-index:30" />';
        }
        _selectBusLineStationArr.push(new TLineStation(data[ii].stationid, dir, leftPos, topPos, data[ii].coordx, data[ii].coordy, stationName));
        str +=
            '<p style="position:absolute;top:' +
            (topPos + 20) +
            "px;left:" +
            (leftPos - stopWidth / 2) +
            'px;color:white;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;width:100px;text-align:center" title="' +
            stationName +
            '">' +
            stationName +
            "</p>";
    }
    $("#busStationInfo").html(str);
    _selectBusLineMapHtml = str;
}

export function leftBitListClick(bitId, bitName, x, y, WLCOMMSTATUS) {
    //console.log("leftBitListClick: ", bitId, bitName, x, y, WLCOMMSTATUS);

    //_mapManager.movePos(x, y);
    //리스트 클릭 이벤트
    bitPopupInfoBox(bitId, bitName, x, y, WLCOMMSTATUS.slice(-1));
    fetchBitRouteInfo(bitId);

    _mapManager.showObjectPosition(x, y, _bitImage);
}
window.leftBitListClick = leftBitListClick;

function bitPopupInfoBox(bitId, bitName, x, y, WLCOMMSTATUS) {
    initLeftMenuClick();
    let bitStts;
    let commStts = WLCOMMSTATUS.slice(-1);
    if (commStts == "0") bitStts = "정상";
    else if (commStts == "1") bitStts = "이상";
    else if (commStts == "3") bitStts = "알수없음";

    let infoContent = '<div id="bitInfo" style="position:absolute;width:470px;height:330px;z-index:200;background-image:url(\'/images/application_wall/BITPop.png\')">';
    infoContent +=
        "<p style=\"color:white;font-family:'RixSGo EB';padding:10px 0 0 12px;width:420px;font-weight:600;font-size:15px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap\">BIT 명칭 : [" +
        bitId +
        "] " +
        bitName +
        "</p>";
    infoContent += '<img id="bitClose" src="/images/application_wall/xbtn.png" alt="BIT정보창 닫기" style="position:absolute;top:10px;right:15px;cursor:pointer" />';
    infoContent += "<p style=\"color:white;font-family:'RixSGo EB';padding-left:10px;font-weight:600;font-size:15px\">통신상태 : " + bitStts + "</p>";
    infoContent += '<div id="bitRouteInfo"></div>';
    infoContent += "</div>";

    $("#bitOverlay").html(infoContent);
    _bitOverlay.setPosition([x, y]);

    $("#bitClose").on("click", function () {
        initLeftMenuClick();
    });
}

function fetchBitRouteInfo(bitId) {
    requestGet("/api/bis/wall/bit-route/" + bitId, recvBitRouteInfo);
}
function recvBitRouteInfo(jsonData) {
    //console.log("recvBitRouteInfo: ", jsonData);
    let str = "";
    let leftSpan = 70;
    let topSpan = 0;
    jsonData.forEach((el, idx) => {
        str += '<ul style="height:20%;">';
        str += '<li style="float:left;width:10%">' + el.busroutename + "</li>";
        str += '<li style="float:left;width:10%;padding-left:10%">' + el.accptarrivaltime + "</li>";
        str += '<li style="float:left;width:60%;padding-left:5%">';

        let remainStopCntArr = el.remainstopcnt.split(",");
        let busOverPos = false;
        let busDownPos = false;
        let busSoonArrival = 0;

        for (let kk = 0; kk < remainStopCntArr.length; kk++) {
            if (remainStopCntArr[kk] <= 7) busDownPos = true;
            else busOverPos = true;

            if (remainStopCntArr[kk] <= 3) busSoonArrival = true;
        }

        //현재버스위치
        if (busDownPos == true) {
            str += '<img src="/images/application_wall/BIT_busLine.png" style="position:relative;top:-14px" alt="BIT정보" />';
            str += "</li>";
            str += "<li>";
            for (let jj = 0; jj < remainStopCntArr.length; jj++) {
                if (remainStopCntArr[jj] <= 7) str += '<img src="/images/application_wall/BIT_bus.png" alt="현재버스위치" class="bus' + idx + "_" + remainStopCntArr[jj] + '" />';
            }
            str += "</li>";
            topSpan += 40;
        } else if (busDownPos == false && busOverPos == true) {
            //현재 버스위치가 7정거장 이전인 경우
            str += "</li>";
            str += "<li>";
            str += '<span style="position:absolute;top:' + topSpan + 'px;left:150px" >' + el.laststopname + "</span>";
            str += "</li>";
            topSpan += 40;
        }

        str += "</ul>";
        if (busSoonArrival == true) {
            str += '<span style="position:absolute;top:197px;left:' + leftSpan + 'px;width:80px;text-align:center">[ ' + el.busroutename + " ]</span>";
            leftSpan += 70;
        }
    });

    $("#bitRouteInfo").html(str);
    // TODO: 5초 마다 다시 호출해야함.
}






function commify(n) {
    const reg = /(^[+-]?\d+)(\d{3})/; // 정규식
    n += ""; // 숫자를 문자열로 변환
    while (reg.test(n)) n = n.replace(reg, "$1" + "." + "$2");
    return n;
}

function drawBusRoute(jsonData, ABusRouteId) {
    if (jsonData.length == 0) {
        return;
    }
    // 노선 경로 정보가 정확하지 않기 때문에 그리지 않는다.
    return;
    let halfRoute = Math.round(jsonData[0].max_section / 2);
    let polylineUpPath = [];
    let polylineDwPath = [];
    jsonData.forEach((el, idx) => {
        let p = new Proj4js.Point(data[ii].coordx, data[ii].coordy);
        Proj4js.transform(epsg2097, epsg4004, p);
        const pos = [p.x, p.y];
        // if (el.sectionorder <= halfRoute) {
        //     polylineUpPath.push(new naver.maps.LatLng(p.y, p.x));
        // } else polylineDwPath.push(new naver.maps.LatLng(p.y, p.x));
    });
}
