@page
@model PCBang.DetailsModel
@using Microsoft.AspNetCore.Http
@using JtkMainServer.Managers
@using Microsoft.AspNetCore.Hosting
@using Newtonsoft.Json.Linq
@using System.IO
@{
    var place = ViewData["Place"] as ApiModels.Place;

    ViewData["Title"] = place.Name;
    ViewData["LoggedInUserId"] = HttpContext.Session.GetString("LoggedInUserId");
    ViewData["LoggedIn"] = ViewData["LoggedInUserId"] != null;

    var env = ViewData["env"] as IHostingEnvironment;

    if (string.IsNullOrWhiteSpace(place.PcMap)) {
        place.PcMap = "{}";
    }

    var farePerHour = PlaceManager.GetFarePerHour(place.Id);

}

<style>
    table {
        display: flex;
        border-width: thin;
        border-collapse: separate;
        border-spacing: 4px;
        table-layout: fixed; /*auto*/
    }

    td {
        border-radius: 4px;
        text-align: center;
        vertical-align: middle;
        color: white;
        width: 26px;
        height: 26px;
    }

    div .review {
        box-shadow: 2px 2px rgba(0, 0, 0, 0);
        font-weight: bold;
        border: solid 1.5px #ccc;
        border-radius: 5px;
        padding: 0 5px;
        background: #fff;
        margin-bottom: 7px;
    }

    .review .id {
        margin-left: 5px;
        font-weight:bold;
    }
    .review .date {
        float:right;
        margin-right: 10px;
        font-weight: lighter;
    }
    .review p {
        font-weight: lighter;
    }

</style>
<div class="row" style="margin-top:20px">
    <div class="col-md-6">
        <h1>
            <a href="javascript:history.back()" class="glyphicon glyphicon-menu-left" aria-hidden="true"></a>@place.Name
        </h1>
        @if (System.IO.File.Exists(System.IO.Path.Combine(env.WebRootPath, $"Images/places/{place.Id}.jpg"))) {
            <img src="~/images/places/@(place.Id).jpg" style="border-radius:10px; margin-bottom:10px; border: solid 1.5px #ccc; width:100%;" /><br />
        }

        @foreach (var line in place.Introduction.Split("\n")) {
        @if (line.First() == '!') {
        <h4>@line.Substring(1)</h4>
} else {
    <p>@line</p>
}
}
        <hr />
        <h3>요금</h3>
        @if (farePerHour < 0) {
        <p>알 수 없음</p>
} else {
    <p>시간당 ￦@(farePerHour.ToString("N0"))</p>
}
        <hr />
    </div>
    <div class="col-md-6">
        <h3>좌석 현황</h3>
        <div id="mapDiv"><div id="innerdiv"></div><img src="~/images/loading_spinner.gif" width="100" /></div>
        <input type="hidden" id="scrollPos" name="scrollPos" value="0" />
        <script type="text/javascript">
            var timeo = setTimeout("refresher();", 1000);
        function refresher() {
            clearTimeout(timeo);
            saveScrollPos();
                //$("#mapDiv").load("Map");
                $.ajax({
                type: 'get',
                    url: 'Map',
                    cache: false,
                    data: {
                    placeId: "@place.Id"
                    },
                    success: function (response) {
                        $("#mapDiv").html(response);
                    setScrollPos();
                }
            });
            timeo = setTimeout("refresher();", 3000);
        }
        function saveScrollPos() {
            document.getElementById("scrollPos").value = document.getElementById("innerdiv").scrollLeft;
        }
        function setScrollPos() {
            document.getElementById("innerdiv").scrollLeft = document.getElementById("scrollPos").value;
        }
        </script>
        <hr />
        <h3>위치</h3>
        <p>@place.Address</p>
        <div id="map" class="form-control" style="border-radius:10px; width:100%;height:250px;"></div>
        <script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=b8a1c577f3130c11f37766981e70beb5"></script>
        @*<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=APIKEY&libraries=services,clusterer,drawing"></script>*@
        <script>
            var mapContainer = document.getElementById('map'), // 지도를 표시할 div
                mapOption = {
                    center: new daum.maps.LatLng(@place.Location), // 지도의 중심좌표
                    level: 3, // 지도의 확대 레벨
                    mapTypeId: daum.maps.MapTypeId.ROADMAP // 지도종류
                };

            // 지도를 생성한다
            var map = new daum.maps.Map(mapContainer, mapOption);

            // 마우스 휠과 모바일 터치를 이용한 지도 확대, 축소를 막는다
            //map.setZoomable(false);

            // 지도에 마커를 생성하고 표시한다
            var marker = new daum.maps.Marker({
                position: new daum.maps.LatLng(@place.Location), // 마커의 좌표
                map: map // 마커를 표시할 지도 객체
            });

            // 커스텀 오버레이를 생성하고 지도에 표시한다
            var customOverlay = new daum.maps.CustomOverlay({
                map: map,
                content: '<div style="box-shadow: 2px 2px rgba(0, 0, 0, .075); font-weight:bold; border:solid 1.5px #888; border-radius:5px; padding:0 5px;background:#fff;">@place.Name</div>',
                position: new daum.maps.LatLng(@place.Location), // 커스텀 오버레이를 표시할 좌표
                xAnchor: 0.5, // 컨텐츠의 x 위치
                yAnchor: -0.2 // 컨텐츠의 y 위치
            });
        </script>
        <hr />
        <h3>고객 평가</h3>
        @{
            var reviews = DbManager.GetPlaceReviews(place.Id);
            var recentAverage = reviews.Length > 0 ? reviews.Take(30).Average(review => review.score) : 0d;

            var reviewStr = "좋습니다.";
            var reviewColor = "forestgreen";
            if (recentAverage < -0.667) {
                reviewStr = "나쁩니다.";
                reviewColor = "orangered";
            } else if (recentAverage < -0.333) {
                reviewStr = "대체로 나쁩니다.";
                reviewColor = "darkorange";
            } else if (recentAverage < 0.333) {
                reviewStr = "복합적입니다.";
                reviewColor = "chocolate";
            } else if (recentAverage < 0.667) {
                reviewStr = "대체로 좋습니다.";
                reviewColor = "darkolivegreen";
            }
        }
        @if (reviews.Length == 0) {
            <p>이 PC방에는 아직 평가가 하나도 없습니다.</p>
        } else {
            <p>이 PC방을 이용한 고객의 <b>@(reviews.Length.ToString("N0"))개의 평가</b>가 있습니다.<br />평균적으로 볼 때, <b>최근 고객들의 평가는 @(Html.Raw($"<span style=\"color:{reviewColor}\">{reviewStr}</span>"))</b></p>
            <h4>최근 평가</h4>
            @foreach (var review in reviews.Take(5)) {
                var glyphClass = review.score > 0 ? "glyphicon-thumbs-up" : "glyphicon-thumbs-down"; ;
                var glyphColor = review.score > 0 ? "darkseagreen" : "indianred";
                var dateStr = "방금 전에";
                var span = DateTime.Now - review.time;
                var days = DateTime.Today - review.time.Date;
                if (span.TotalHours >= 1 && DateTime.Today == review.time.Date) {
                    dateStr = $"{span.TotalHours:N0} 시간 전에";
                } else if (days == TimeSpan.FromDays(1)) {
                    dateStr = "어제";
                } else if (days == TimeSpan.FromDays(2)) {
                    dateStr = "그저께";
                } else if (days >= TimeSpan.FromDays(3)) {
                    dateStr = $"{days.TotalDays:N0}일 전에";
                }

                <div class="review">
                    <h5>@Html.Raw($"<span class=\"glyphicon {glyphClass}\" style=\"color: {glyphColor}\"></span>") <span class="id">@review.nickname</span><span class="date">@dateStr 작성</span></h5>
                    <p>@review.text</p>
                </div>
            }
        }

        <hr />
    </div>
</div>
<div>
    <a href="javascript:history.back()">돌아가기</a>
</div>