@{
    ViewData["MainNum"] = "4";
    ViewData["SubNum"] = "2";
    ViewData["Title"] = "台電售電記錄";
}
@using SolarPower.Models.Role
@model RoleLayerEnum

<div class="container-fluid">
    <div class="row flex-nowrap wrapper">
        <div class="col-md-2 col-1 pl-0 pr-0 collapse width border-right sidebar vh-100 overflow-auto">

            <div class="list-group border-0 card text-center text-md-left" id="sidebar">

                <div class="border bg-light rounded-top">
                    <div class="form-group p-2 m-0 rounded-top">
                        <input type="text" class="form-control form-control-lg shadow-inset-2 m-0" id="js_list_accordion_filter" placeholder="">
                    </div>
                    <div id="js_list_accordion" class="accordion accordion-hover accordion-clean js-list-filter">
                        <div class="card border-top-left-radius-0 border-top-right-radius-0">
                            <div class="card-header">
                                <a href="javascript:void(0);" class="card-title collapsed" data-toggle="collapse" data-target="#js_list_accordion-a" aria-expanded="true" data-filter-tags="settings">
                                    <i class="fal fa-globe width-2 fs-xl"></i>
                                    新北市
                                    <span class="ml-auto">
                                        <span class="collapsed-reveal">
                                            <i class="fal fa-chevron-up fs-xl"></i>
                                        </span>
                                        <span class="collapsed-hidden">
                                            <i class="fal fa-chevron-down fs-xl"></i>
                                        </span>
                                    </span>
                                </a>
                            </div>
                            <div id="js_list_accordion-a" class="collapse" data-parent="#js_list_accordion" style="">
                                <div class="card-body">
                                    <ul class="list-group list-group-flush">
                                        <li class="list-group-item">
                                            <div class="d-flex justify-content-between">
                                                <h4 class="font-weight-bold"><i class="fal fa-charging-station"></i> 新竹交大站</h4>
                                                <div class="">
                                                    <input type="checkbox" class="" id="defaultUnchecked">
                                                </div>
                                            </div>
                                            <ul class="list-group list-group-flush">
                                                <li class="list-group-item pr-0 d-flex justify-content-between">
                                                    <a href="#"><i class="fal fa-tachometer-alt-slow"></i> 電錶 R001</a>
                                                    <div class="">
                                                        <input type="checkbox" class="" id="defaultUnchecked">
                                                    </div>
                                                </li>
                                            </ul>
                                        </li>
                                        <li class="list-group-item">
                                            <div class="d-flex justify-content-between">
                                                <h4 class="font-weight-bold"><i class="fal fa-charging-station"></i> 新竹動物園站</h4>
                                                <div class="">
                                                    <input type="checkbox" class="" id="defaultUnchecked">
                                                </div>
                                            </div>
                                        <li class="list-group-item">
                                            <div class="d-flex justify-content-between">
                                                <h4 class="font-weight-bold"><i class="fal fa-charging-station"></i> 新竹火車站</h4>
                                                <div class="">
                                                    <input type="checkbox" class="" id="defaultUnchecked">
                                                </div>
                                            </div>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header">
                                <a href="javascript:void(0);" class="card-title collapsed" data-toggle="collapse" data-target="#js_list_accordion-b" aria-expanded="false" data-filter-tags="merge">
                                    <i class="fal fa-globe width-2 fs-xl"></i>
                                    台南市
                                    <span class="ml-auto">
                                        <span class="collapsed-reveal">
                                            <i class="fal fa-chevron-up fs-xl"></i>
                                        </span>
                                        <span class="collapsed-hidden">
                                            <i class="fal fa-chevron-down fs-xl"></i>
                                        </span>
                                    </span>
                                </a>
                            </div>
                            <div id="js_list_accordion-b" class="collapse" data-parent="#js_list_accordion">
                                <div class="card-body">
                                    放台南市list
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header">
                                <a href="javascript:void(0);" class="card-title collapsed" data-toggle="collapse" data-target="#js_list_accordion-c" aria-expanded="false" data-filter-tags="backup">
                                    <i class="fal fa-globe width-2 fs-xl"></i>
                                    屏東縣
                                    <span class="ml-auto">
                                        <span class="collapsed-reveal">
                                            <i class="fal fa-chevron-up fs-xl"></i>
                                        </span>
                                    </span>
                                </a>
                            </div>
                            <div id="js_list_accordion-c" class="collapse" data-parent="#js_list_accordion">
                                <div class="card-body">
                                    <ul class="list-group">
                                        <li class="list-group-item">
                                            <span data-filter-tags="reports file">Reports</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <span class="filter-message js-filter-message"></span>
                </div>
            </div>
        </div>
        <div class="col-auto px-0">
            <a href="javascript:;" data-target=".sidebar" data-toggle="collapse" class="btn btn-default btn-xs btn-icon waves-effect waves-themed" style="border-radius: 0;"><i onclick="myfunc(this)" class="fal fa-angle-right fa-lg py-3" id="collapse"></i></a>
        </div>

        <main class="col px-5 pl-md-2 main">
            <div class="subheader">
                <h1 class="subheader-title">
                    <i class="subheader-icon fal fa-file-chart-line"></i> @ViewData["Title"]
                </h1>
            </div>


            <div class="row">
                <div class="col-xl-12">
                    <div id="panel-5" class="panel">
                        <div class="panel-container show">
                            <div class="panel-content">
                                <div class="mb-3 d-flex justify-content-start">
                                    <div class="pr-3">
                                        <div class="btn-group btn-group-md">
                                            <button type="button" class="btn btn-success waves-effect waves-themed btn-change-searchType" id="Group0" onclick="changeType(0,this)">60天內</button>
                                            <button type="button" class="btn btn-secondary waves-effect waves-themed btn-change-searchType" id="Group1" onclick="changeType(1,this)">日區間</button>
                                            <button type="button" class="btn btn-secondary waves-effect waves-themed btn-change-searchType" id="Group2" onclick="changeType(2,this)">月</button>
                                            <button type="button" class="btn btn-secondary waves-effect waves-themed btn-change-searchType" id="Group3" onclick="changeType(3,this)">年</button>
                                        </div>
                                    </div>
                                    <div class="pr-3">
                                        <div class="btn-group" id="DateGetdiv" role="group" aria-label="Button group with nested dropdown">
                                            <input type="date" class="form-control" id="DateGet" />
                                        </div>
                                        <div class="btn-group" id="DateGettextdiv" role="group" aria-label="Button group with nested dropdown">
                                            <input type="text" class="form-control" id="DateGettext" />
                                        </div>
                                    </div>
                                    <div class="pr-3" id="quickSearchOption">
                                        <button type="button" class="btn btn-primary waves-effect waves-themed ml-1" onclick="Searchform()" id="daybtn">查詢</button>
                                    </div>
                                    <div class="pr-3">
                                        <button type="button" class="btn btn-primary waves-effect waves-themed" onclick="AddRecord()"><span class="fal fa-plus mr-1"></span> 新增</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>

                </div>
            </div>

            <div class="row mb-5">
                <div class="col-xl-12">
                    <div class="card p-3 w-100 overflow-auto">
                        <table class="table m-0" id="RecordTable">
                            <thead id="tothead">
                                <tr>
                                    <th>編號</th>
                                    <th>電站名稱</th>
                                    <th>開始日期</th>
                                    <th>結束日期</th>
                                    <th>購電度數</th>
                                    <th>售出電費</th>
                                    <th>建立日期</th>
                                    <th>功能</th>
                                </tr>
                            </thead>
                            <tbody id="totbody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<div class="modal fade" id="Record-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    台電售電紀錄-新增
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <form class="Record-form" id="Record-form">
                    <div class="row">
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="PowerStationId_modal"><span class="text-danger">*</span>電站名稱</label>
                            <select class="form-control" id="PowerStationId_modal">
                            </select>
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="StartTime_modal"><span class="text-danger">*</span>開始日期</label>
                            <input type="date" id="StartTime_modal" name="StartTime_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="BuyKwh_modal"><span class="text-danger">*</span>購電度數</label>
                            <input type="number" id="BuyKwh_modal" name="BuyKwh_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="EndTime_modal"><span class="text-danger">*</span>結束日期</label>
                            <input type="date" id="EndTime_modal" name="EndTime_modal" class="form-control">
                        </div>

                        <div class="form-group col-lg-6">
                            <label class="form-label" for="Money_modal"><span class="text-danger">*</span>售出電費</label>
                            <input type="number" id="Money_modal" name="Money_modal" class="form-control">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="SaveSoldMoney()">確定</button>
            </div>
        </div>
    </div>
</div>

@section Scripts{
    <script>
        var searchType = 0;//搜尋條件(日,日區間,月,年)
        var datepicker;
        var timerange = "";//選取時間
        var selecterd_powerstationId = [];
        var selected_id;
        var RecordTable;
        //#region Date-Picker
            datepicker = $('#DateGettext').daterangepicker({
                autoUpdateInput: false,
                locale: { format: 'YYYY/MM/DD' },
                opens: 'left'
            });

            $('#DateGettext').on('apply.daterangepicker', function (ev, picker) {
                $(this).val(picker.startDate.format('YYYY/MM/DD') + ' - ' + picker.endDate.format('YYYY/MM/DD'));
                $(this).trigger('change');
            });

            $('#DateGettext').on('cancel.daterangepicker', function (ev, picker) {
                $(this).val('');
                $(this).trigger('change');
            });
        //#endregion
        $(function () {
            //#region 預設初始值
            var a = $('#collapse').trigger("click");
            document.getElementById("DateGetdiv").style.display = "none";//隱藏
            $('#DateGet').attr('style', 'width:205px');
            $('#DateGettext').attr('style', 'width:205px');
            //#endregion

            //#region 載入左邊選單列表
            GetPowerStationCollapse("");
            //#endregion

            var today = new Date();
            var dateLimit = new Date(new Date().setDate(today.getDate() - 60));
            var today_format = today.toISOString().slice(0, 10).replace(/-/g, "/");
            var dateLimit_format = dateLimit.toISOString().slice(0, 10).replace(/-/g, "/");
            datepicker.data('daterangepicker').setStartDate(dateLimit_format);
            datepicker.data('daterangepicker').setEndDate(today_format);
            document.getElementById("DateGettextdiv").style.display = "";//隱藏
            document.getElementById("DateGetdiv").style.display = "none";//隱藏
            //#endregion
            $('#DateGettext').val(dateLimit_format + ' - ' + today_format);
            $("#PowerStationId_modal").append($("<option />").val(0).text("請先選擇電站"));
            $("#PowerStationId_modal").attr("disabled", true);
            DataTable();
        })

        //#region 左邊的搜索欄位
        function myfunc(div) {
            var className = div.getAttribute("class");
            if (className == "fal fa-angle-left fa-lg py-3") {
                div.className = "fal fa-angle-right fa-lg py-3";
            }
            else {
                div.className = "fal fa-angle-left fa-lg py-3";
            }
        }

        $("#js_list_accordion_filter").change(function (e) {
            GetPowerStationCollapse($(this).val());
        });

        $('#js_list_accordion').on("change", 'input[name="selectedInverterLayer2[]"]', function (event) {
            var getstation =
            {
                name: $(this).attr('valuename'),
                value: this.value
            }

            if (this.checked) {
                selecterd_powerstationId.push(getstation);
            } else {
                var a = selecterd_powerstationId.filter(function (n, i) {

                    if (n.name === getstation.name && n.value === getstation.value) {
                        selecterd_powerstationId.splice(i, 1);
                    }

                });
            }

            $('#PowerStationId_modal').empty();
            $("#PowerStationId_modal").attr("disabled", false);
            $.each(selecterd_powerstationId, function (index, val) {
                $("#PowerStationId_modal").append($("<option />").val(parseInt(val.value)).text(val.name));
            });
            if (selecterd_powerstationId.length == 0) {
                $("#PowerStationId_modal").append($("<option />").val(0).text("請先選擇電站"));
                $("#PowerStationId_modal").attr("disabled", true);
            }


            console.log(selecterd_powerstationId);
        });


        function GetPowerStationCollapse(filter) {
            var url = "/StationReport/GetPowerStationNameList"

            var send_data = {
                Filter: filter
            }

            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.data.msg);
                    return;
                }

                var inverterCollapse = rel.data;



                $('#js_list_accordion').empty();

                if (inverterCollapse.length <= 0) {
                    $('#js_list_accordion').append("<div>查無結果</div>");
                }

                var str = "";

                Object.keys(inverterCollapse).map(function (key, index) {
                    str += '<div class="card border-top-left-radius-0 border-top-right-radius-0" id="templateCard">' +
                        '<div class="card-header">' +
                        '<a href="javascript:void(0);" class="card-title collapsed" data-toggle="collapse" data-target="#js_list_accordion-' + index + '" aria-expanded="false" data-filter-tags="settings">' +
                        '<i class="fal fa-globe width-2 fs-xl"></i>' +
                        '<span class="city-name">' + key + '</span>' +
                        '<span class="ml-auto">' +
                        '<span class="collapsed-reveal"><i class="fal fa-chevron-up fs-xl"></i></span>' +
                        '<span class="collapsed-hidden"><i class="fal fa-chevron-down fs-xl"></i></span>' +
                        '</span>' +
                        '</a>' +
                        '</div>' +
                        '<div id="js_list_accordion-' + index + '" class="collapse" data-parent="#js_list_accordion-' + index + '" style="">' +
                        '<div class="card-body">' +
                        '<ul class="list-group list-group-flush">';
                    $.each(inverterCollapse[key], function (index, inverter) {
                        var getstation =
                        {
                            name: inverter.powerStationName,
                            value: String(inverter.powerStationId)
                        }
                        var on = false;
                        var a = selecterd_powerstationId.find(function (n, i) {
                            if (n.name === getstation.name && n.value === getstation.value) {
                                on = true;
                            }
                        });
                        if (on == true) {
                            str += '<li class="list-group-item">' +
                                '<div class="d-flex justify-content-start">' +
                                '<div class="mr-2">' +
                                '<input type="checkbox" class="" name="selectedInverterLayer2[]" value="' + inverter.powerStationId + '" valueName ="' + inverter.powerStationName + '" checked>' +
                                '</div>' +
                                '<h5 class="font-weight-bold">' + inverter.powerStationName + '</h5>' +
                                '</div>' +
                                '</li>';
                        }
                        else {
                            str += '<li class="list-group-item">' +
                                '<div class="d-flex justify-content-start">' +
                                '<div class="mr-2">' +
                                '<input type="checkbox" class="" name="selectedInverterLayer2[]" value="' + inverter.powerStationId + '" valueName ="' + inverter.powerStationName + '">' +
                                '</div>' +
                                '<h5 class="font-weight-bold">' + inverter.powerStationName + '</h5>' +
                                '</div>' +
                                '</li>';
                        }
                    });

                    str += '</ul>';
                    str += '</div>';
                    str += '</div>';

                });

                $('#js_list_accordion').append(str);
                $('#js_list_accordion').find('.card').first().addClass(" border-top-left-radius-0 border-top-right-radius-0");

                $('input[name="selectedInverterLayer2[]"]').each(function () {
                    if ($.inArray(this.value, selecterd_powerstationId) > -1) {
                        $(this).prop('checked', true);
                    }
                });
                $("#js_list_accordion .collapse").collapse('show');


            }, 'json');
        }
        //#endregion

        function changeType(type, e) {
            searchType = type;
            if ($(".btn-change-searchType").hasClass("btn-success")) {
                $(".btn-change-searchType").removeClass("btn-success").addClass("btn-secondary");
            }
            document.getElementById("DateGettextdiv").style.display = "none";//隱藏
            document.getElementById("DateGetdiv").style.display = "";//隱藏
            $(e).removeClass("btn-secondary").addClass("btn-success");
            switch (type) {
                case 0:
                    //#region 預設近60天
                    var today = new Date();
                    var dateLimit = new Date(new Date().setDate(today.getDate() - 60));
                    var today_format = today.toISOString().slice(0, 10).replace(/-/g, "/");
                    var dateLimit_format = dateLimit.toISOString().slice(0, 10).replace(/-/g, "/");
                    datepicker.data('daterangepicker').setStartDate(dateLimit_format);
                    datepicker.data('daterangepicker').setEndDate(today_format);
                    document.getElementById("DateGettextdiv").style.display = "";//隱藏
                    document.getElementById("DateGetdiv").style.display = "none";//隱藏
                    //#endregion
                    $('#DateGettext').val(dateLimit_format + ' - ' + today_format);
                    break;
                    break;
                case 1:
                    //#region 預設近7天
                    $('#DateGettext').val("");
                    document.getElementById("DateGettextdiv").style.display = "";//隱藏
                    document.getElementById("DateGetdiv").style.display = "none";//隱藏
                    //#endregion
                    break;
                case 2:
                    $('#DateGet').prop({ 'type': 'month' });
                    var now_month = new Date().toISOString().substring(0, 7);
                    $('#DateGet').val(now_month);
                    
                    break;
                case 3:
                    var now_year = new Date().toISOString().substring(0, 4);
                    $('#DateGet').prop({ 'type': 'number', 'min': 1900, 'max': now_year, 'step': 1 });
                    $('#DateGet').val(now_year);
                    break;
            }
        }

        function AddRecord() {
            selected_id = 0;
            $("#Record-modal .modal-title").html("台電售電紀錄-新增");
            $("#Record-form").trigger("reset");
            $("#Record-modal").modal();
        }

        function SaveSoldMoney()
        {
            if ($("#Record-form").valid()) {
                var url = "/ElectricitySoldRecord/SaveSoldMoney";
                var send_data = {
                    Id: selected_id,
                    StartAt: $("#StartTime_modal").val(),
                    EndAt: $("#EndTime_modal").val(),
                    Kwh: $("#BuyKwh_modal").val(),
                    Money: $("#Money_modal").val(),
                    PowerstationId: $("#PowerStationId_modal").val()
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        $('#Record-modal').modal('hide');
                        RecordTable.ajax.reload();
                        return;
                    }

                }, 'json');
            }
        }

        function DataTable() {
            RecordTable = $("#RecordTable").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                "columns": [{
                    "data": "id"
                }, {
                    "data": "powerStationName"
                }, {
                    "data": "startAt"
                }, {
                    "data": "endAt"
                }, {
                    "data": "kwh"
                }, {
                    "data": "money"
                }, {
                    "data": "createdDay"
                }, {
                    "data": "function"
                }],
                "language": {
                    "emptyTable": "查無資料",
                    "processing": "處理中...",
                    "loadingRecords": "載入中...",
                    "lengthMenu": "顯示 _MENU_ 項結果",
                    "zeroRecords": "沒有符合的結果",
                    "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                    "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                    "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                    "infoPostFix": "",
                    "search": "搜尋:",
                    "paginate": {
                        "first": "第一頁",
                        "previous": "上一頁",
                        "next": "下一頁",
                        "last": "最後一頁"
                    },
                    "aria": {
                        "sortAscending": ": 升冪排列",
                        "sortDescending": ": 降冪排列"
                    }
                },
                'createdRow': function (row, data, dataIndex) {
                    $(row).attr('data-id', data.id);
                    $(row).attr('powerstation-Name', data.powerStationName);
                },
                "ajax": {
                    "url": "/ElectricitySoldRecord/RecordTable",
                    "type": "POST",
                    "data": function (d) {
                        d.stationId = selecterd_powerstationId,
                        d.time = timerange,
                        d.searchType = searchType
                    },
                    "dataSrc": function (rel) {
                        if (rel.data.code == "9999") {
                            toast_error(rel.data.msg);
                            return;
                        }

                        data = rel.data.data;

                        if (data == null || data.length == 0) {
                            this.data = [];
                        }

                        return data;
                    }
                },
                "error": function (xhr, error, thrown) {
                    console.log(xhr);
                }
            });
        }

        function Searchform() {
/*            console.log(selecterd_powerstationId);*/
            if (searchType == 0 || searchType == 1) {
                timerange = $('#DateGettext').val();
            }
            else {
                timerange = $('#DateGet').val();
            }
            RecordTable.ajax.reload();
        }

        $('#RecordTable').on("click", "button.edit-btn", function () {
            $("#Record-modal .modal-title").html("台電售電紀錄 - 編輯");
            selected_id = $(this).parents('tr').attr('data-id');
            var powerstationName = $(this).parents('tr').attr('powerstation-Name');
            //取得單一運維基本資料
            var url = "/ElectricitySoldRecord/GetOnePowerStation/";
            var send_data = {
                Id: selected_id
            }
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $('#PowerStationId_modal').empty();
                $("#PowerStationId_modal").attr("disabled", true);
                $("#PowerStationId_modal").append($("<option />").val(999).text(powerstationName));
                $("#StartTime_modal").val(rel.data.startAt);
                $("#BuyKwh_modal").val(rel.data.kwh);
                $("#EndTime_modal").val(rel.data.endAt);
                $("#Money_modal").val(rel.data.money);
                $("#Record-modal").modal();
            }, 'json');
        });

        $('#RecordTable').on("click", "button.bill-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');
            window.location = "/ElectricitySoldRecord/BillExcel?post=" + selected_id;

        })


        $('#RecordTable').on("click", "button.del-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/ElectricitySoldRecord/DeleteRecord/";

                        var send_data = {
                            Id: selected_id
                        }

                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            RecordTable.ajax.reload();
                        }, 'json');
                    }
                });
        });


        $("#Record-form").validate({
            rules: {
                PowerStationId_modal: {
                    required: true,
                },
                StartTime_modal: {
                    required: true
                },
                EndTime_modal: {
                    required: true,
                },
                BuyKwh_modal: {
                    required: true,
                },
                Money_modal: {
                    required: true,
                },
            },
        });
    </script>
}