@page
@model Manage.PartnerModel
@using Microsoft.AspNetCore.Http
@using JtkMainServer.ApiModels
@using JtkMainServer.Managers
@{
    //ViewData["Title"] = "매출";
    ViewData["LoggedInUserId"] = HttpContext.Session.GetString("LoggedInUserId");
    ViewData["LoggedIn"] = ViewData["LoggedInUserId"] != null;
    //ViewData["ActivatedTabIndex"] = 2;

    var toDate = DateTime.Today;
    var fromDate = toDate + TimeSpan.FromDays(1);
    if (HttpContext.Request.Query.TryGetValue("from", out var fromDateTexts) == true && fromDateTexts.Count > 0 && string.IsNullOrWhiteSpace(fromDateTexts[0]) == false) {
        DateTime.TryParse(fromDateTexts[0], out fromDate);
    }
    if (HttpContext.Request.Query.TryGetValue("to", out var toDateTexts) == true && toDateTexts.Count > 0 && string.IsNullOrWhiteSpace(toDateTexts[0]) == false) {
        DateTime.TryParse(toDateTexts[0], out toDate);
    }
    if (fromDate > toDate) {
        fromDate = DateTime.Parse($"{toDate.Year}-{toDate.Month}-01");
    }
    var days = Math.Round((toDate - fromDate).TotalDays) + 1;

    var place = ViewData["Place"] as Place;
    ViewData["Title"] = $"{place.Name} 매출액 지급 내역";

    var list = DbManager.GetSalesPlacePaymentExpensesList(fromDate, toDate, place.Id, true);
    var totalList = DbManager.GetSalesPlacePaymentExpensesList(DateTime.MinValue, DateTime.MaxValue, place.Id, true);  // 최적화 그지 ★
    //var totalPlaceExpense = DbManager.GetPlaceExpense(place.Id);
    var pingLogs = DbManager.GetPlacePingLogs(place.Id, fromDate, toDate);
    var totalPingLogs = DbManager.GetPlacePingLogs(place.Id); // 최적화 그지 ★
}

<style type="text/css">
    .table-stats {
        width: 100%;
    }

        .table-stats th {
            font-weight: normal;
            font-size: large;
            padding: 8px 4px 8px 4px;
        }

        .table-stats td {
            text-align: right;
        }

    .table-daterange {
        width: 100%;
    }

        .table-daterange th {
            font-weight: normal;
        }

        .table-daterange td {
            text-align: right;
        }

    input[type=date] {
        width: unset;
        display: inline;
        margin: 0px 8px;
    }

    input[type=text] {
        width: 150px;
        display: inline;
        margin: 0px 8px;
    }

    input[type=time] {
        width: 150px;
        display: inline;
        margin: 0px 8px;
    }
</style>

<div class="row" style="margin-top:20px">
    <div class="col-md-6">
        @*@Html.Partial("~/Views/ManageTabs.cshtml")*@
        <h1><a href="./Partners?from=@(fromDate.ToShortDateString())&to=@(toDate.ToShortDateString())" class="glyphicon glyphicon-menu-left" aria-hidden="true"></a>@place.Name</h1>
        @*<h2>매출액 지급 내역</h2>*@
        <h3>기간</h3>
        <form method="get" id="form">
            <table class="table-daterange">
                <tr>
                    <th>
                        <input type="hidden" name="id" value="@place.Id" />
                        <input type="date" name="from" class="form-control" value="@fromDate.ToShortDateString()" />부터
                        <input type="date" name="to" class="form-control" value="@toDate.ToShortDateString()" />까지
                    </th>
                    <td>
                        <a href="javascript:document.getElementById('form').submit()" class="btn btn-default"><span class="glyphicon glyphicon-search"></span> 조회</a>
                        <input type="submit" hidden="hidden" />
                    </td>
                </tr>
            </table>
        </form>
        <hr />
        <h3>합계</h3>
        <table class="table-stats">
            <tr>
                <th>등록일</th>
                <td>@place.RegisteredTime.ToLongDateString()</td>
            </tr>
            <tr>
                <th> 총 매출액 </th>
                <td>￦@(totalPingLogs.Sum(item => item.totalCashUse).ToString("N0")) </td>
            </tr>
            <tr>
                <th> 기간 매출액 </th>
                <td>￦@(pingLogs.Sum(item => item.totalCashUse).ToString("N0")) </td>
            </tr>
            <tr>
                <th> 총 지급액 </th>
                <td>￦@(totalList.Sum(item => item.cash).ToString("N0")) </td>
            </tr>
            <tr>
                <th> 기간 지급액 </th>
                <td>￦@(list.Sum(item => item.cash).ToString("N0")) </td>
            </tr>
        </table>
        <hr />
        <h3> 매출액 지급 설정</h3>
        <form method="post" id="postform">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @*<h4> 지급 시간 </h4>*@
            <div class="form-group">
                <label asp-for="PaymentTime.Time" class="control-label"></label>
                <p>매일<input asp-for="PaymentTime.Time" type="time" class="form-control" />에 지급</p>
                <span asp-validation-for="PaymentTime.Time" class="text-danger"></span>

            </div>
            @*<h4>지급 계좌번호</h4>*@
            <div class="form-group">
                <label asp-for="PaymentTime.AccountNumber" class="control-label"></label>
                <p>신한<input asp-for="PaymentTime.AccountNumber" type="text" class="form-control" />으로 지급</p>
                <span asp-validation-for="PaymentTime.AccountNumber" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PaymentTime.Royalty" class="control-label"></label>
                <p>매출의 <input asp-for="PaymentTime.Royalty" type="number" min="0" max="10" step="0.5" class="form-control" style="width: 80px; display: inline; margin: 0px 8px; text-align:right;" />%를 제외하고 지급</p>
                <span asp-validation-for="PaymentTime.Royalty" class="text-danger"></span>
            </div>
            <div class="form-group">
                <span class="text-success">@Model.Message</span>
            </div>
            <a href="javascript:document.getElementById('postform').submit()" class="btn btn-default"><span class="glyphicon glyphicon-floppy-disk"></span> 변경내용 저장</a>
            <input type="submit" hidden="hidden" />
        </form>
        <hr />
        <h3>매출액 지급 내역<span style="font-size: small"> @fromDate.ToShortDateString() ~@toDate.ToShortDateString() (@(days) 일간)</span></h3>
        <table class="table">
            <thead>
                <tr>
                    <th>기간</th>
                    <th>매출</th>
                    <th>지급</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var tuple in list) {
                <tr>
                <td>@(tuple.prevTime == default(DateTime) ? "" : tuple.prevTime.ToString("yyyy-MM-dd HH:mm")) ~@tuple.time.ToString("yyyy-MM-dd HH:mm") </td >
                @{ var sum = 0.0; }
                @foreach (var item in pingLogs) {
                if ((tuple.prevTime == default(DateTime) ? DateTime.MinValue : tuple.prevTime) <= item.logoutTime && item.logoutTime <= tuple.time) {
                    sum += item.totalCashUse;
                }
            }
                <td>￦@sum.ToString("N0") </td>

                <td>￦@tuple.cash.ToString("N0") </td>

                </tr>
        }
            </tbody>
        </table>
        @if (list?.Length == 0) {<center> 내용이 없습니다.</center>}
        <hr />
        <h3>매출 내역<span style="font-size: small"> @fromDate.ToShortDateString() ~@toDate.ToShortDateString() (@(days) 일간)</span></h3>
        @*<p>항목을 클릭하면 자세히 볼 수 있습니다.</p>*@
        <table class="table">
            <thead>
                <tr>
                    <th>일시</th>
                    <th>회원</th>
                    <th>사용시간</th>
                    <th>사용금액</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var tuple in pingLogs) {
                <tr>
                    <td>@tuple.loginTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                    <td>@tuple.userId</td>
                    @{ var usedTime = tuple.logoutTime - tuple.loginTime; }
                    <td>@($"{Math.Floor(usedTime.TotalHours):00}:{usedTime.Minutes:00}:{usedTime.Seconds:00}")</td>
                    <td>￦@tuple.totalCashUse.ToString("N0")</td>
                </tr>
        }
            </tbody>
        </table>
        @if (pingLogs?.Length == 0) {<center>내용이 없습니다.</center>}
        <hr />
    </div>
</div>

<div>
    <a href="./Partners?from=@(fromDate.ToShortDateString())&to=@(toDate.ToShortDateString())">이전 페이지로</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
