@{
    ViewData["MainNum"] = "4";
    ViewData["SubNum"] = "1";
    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>
                                                <li class="list-group-item pr-0 d-flex justify-content-between">
                                                    <a href="#"><i class="fal fa-sun"></i> 日照計 R002</a>
                                                    <div class="">
                                                        <input type="checkbox" class="" id="defaultUnchecked">
                                                    </div>
                                                </li>
                                                <li class="list-group-item pr-0 d-flex justify-content-between">
                                                    <a href="#"><i class="fal fa-thermometer-half"></i> 環境溫度計 R003</a>
                                                    <div class="">
                                                        <input type="checkbox" class="" id="defaultUnchecked">
                                                    </div>
                                                </li>
                                                <li class="list-group-item pr-0 d-flex justify-content-between">
                                                    <a href="#"><i class="fal fa-wind"></i> 風速計 R002</a>
                                                    <div class="">
                                                        <input type="checkbox" class="" id="defaultUnchecked">
                                                    </div>
                                                </li>
                                                <li class="list-group-item pr-0 d-flex justify-content-between">
                                                    <a href="#"><i class="fal fa-sun-dust"></i> 落塵計 R002</a>
                                                    <div class="">
                                                        <input type="checkbox" class="" id="defaultUnchecked">
                                                    </div>
                                                </li>
                                                <li class="list-group-item pr-0 d-flex justify-content-between">
                                                    <a href="#"><i class="fal fa-tint"></i> 濕度計 R002</a>
                                                    <div class="">
                                                        <input type="checkbox" class="" id="defaultUnchecked">
                                                    </div>
                                                </li>
                                                <li class="list-group-item pr-0 d-flex justify-content-between">
                                                    <a href="#"><i class="fal fa-server"></i> 逆變器 R002</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 class="collapsed-hidden">
                                            <i class="fal fa-chevron-down 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>
                                        <li class="list-group-item">
                                            <span data-filter-tags="analytics graphs">Analytics</span>
                                        </li>
                                        <li class="list-group-item">
                                            <span data-filter-tags="export download">Export</span>
                                        </li>
                                        <li class="list-group-item">
                                            <span data-filter-tags="storage">Storage</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:;" id="collapse" data-target=".sidebar" data-toggle="collapse" class="btn btn-default btn-xs btn-icon waves-effect waves-themed" style="border-radius: 0;" aria-expanded="true">
                <span class="collapsed-reveal"><i class="fal fa-angle-left fa-lg py-3"></i></span>
                <span class="collapsed-hidden"><i class="fal fa-angle-right fa-lg py-3"></i></span>
            </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)">日</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" id="quickSearchOption">
                                        <button type="button" class="btn btn-secondary waves-effect waves-themed btn-change-quickSearch1" onclick="quickSearch(0)">今天</button>
                                        <button type="button" class="btn btn-secondary waves-effect waves-themed btn-change-quickSearch2" onclick="quickSearch(1)">昨天</button>
                                    </div>
                                    <div class="pr-3">
                                        <div class="btn-group" id="js-demo-nesting" 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="Dateform(0)" id="daybtn">日報表</button>
                                        <button type="button" class="btn btn-primary waves-effect waves-themed ml-1" onclick="Dateform(1)" id="monthbtn">月報表</button>
                                        <button type="button" class="btn btn-primary waves-effect waves-themed ml-1" onclick="Dateform(2)" id="yearbtn">綜合報表</button>
                                    </div>
                                </div>
                                <div class="mb-3 d-flex justify-content-start">
                                    <div class="pr-3">
                                        <button type="button" class="btn btn-primary waves-effect waves-themed" onclick="ExportExcel()"><span class="fal fa-file-excel mr-1"></span> 匯出</button>
                                    </div>
                                    <div class="row">
                                        <div class="pr-3" id="selectOneStation">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row mb-5">
                <div class="col-xl-12">
                    <div class="card p-3 w-100" id="overviewtable">
                        <table class="table m-0">
                            <thead id="tothead">
                            </thead>
                            <tbody id="totbody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="row mb-5">
                <div class="col-xl-12">
                    <div class="card p-3 w-100" id="hiretable" style="overflow-x:auto">
                        <table class="table m-0">
                            <thead id="HireTableHead">
                                <tr>
                                    <th>出租人</th>
                                    <th>租金比例</th>
                                    <th>租金金額(未稅)</th>
                                    <th>租金金額(含稅)</th>
                                </tr>
                            </thead>
                            <tbody id="HireTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="row mb-5">
                <div class="col-xl-12">
                    <div class="card p-3 w-100 " id="maxtable" style="overflow-x:auto">
                        <table class="table m-0">
                            <thead>
                                <tr>
                                    <th>縣市</th>
                                    <th>平均發電量(kWp)</th>
                                    <th>發電時間(小時)</th>
                                </tr>
                            </thead>
                            <tbody id="maxtableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="row mb-5">
                <div class="col-xl-12">
                    <div class="card p-3 w-100" id="detailtable" style="overflow-x:auto">
                        <table class="table m-0">
                            <thead id="TableHead">
                            </thead>
                            <tbody id="TableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>


        </main>
    </div>
</div>

@section Scripts{
    <script>
        var searchType = 0;//搜尋條件(日,日區間,月,年)
        var datepicker;
        var timerange;//選取時間
        var selecterd_invert = [];
        var nowpowerstation = null;//選擇電站
        var haveinvertName = [];
        var nowform;
        var xxx;

        $(function () {
            //#region 預設初始值
            $('#collapse').trigger("click");
            $('#overviewtable').hide();
            $('#maxtable').hide();
            $('#hiretable').hide();
            $('#detailtable').hide();
            $('#DateGet').val(new Date().toISOString().substring(0, 10));
            document.getElementById("DateGettextdiv").style.display = "none";//隱藏
            $('#DateGet').attr('style', 'width:205px');
            $('#DateGettext').attr('style', 'width:205px');
            timerange = $('#DateGet').val();
            document.getElementById("monthbtn").disabled = true;//月報表鎖定
            document.getElementById("yearbtn").disabled = false;//綜合報表鎖定
            document.getElementById("daybtn").disabled = false;//日報表鎖定
            //#endregion

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

        //#region 更換搜尋條件(日,日區間,月,年)
        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("DateGet").style.display = "";//隱藏
            $(e).removeClass("btn-secondary").addClass("btn-success");
            switch (type) {
                case 0: $('#DateGet').prop({ 'type': 'date' });
                    $(".btn-change-quickSearch1").html("今天");
                    $(".btn-change-quickSearch2").html("昨天");
                    var today = new Date().toISOString().substring(0, 10);
                    $('#DateGet').val(today);
                    document.getElementById("monthbtn").disabled = true;//月報表鎖定
                    document.getElementById("yearbtn").disabled = false;//綜合報表鎖定
                    document.getElementById("daybtn").disabled = false;//日報表鎖定
                    break;
                case 1:

                    //#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

                    $(".btn-change-quickSearch1").html("近7天");
                    $(".btn-change-quickSearch2").html("近30天");
                    //#region 預設近7天
                    var today = new Date();
                    var dateLimit = new Date(new Date().setDate(today.getDate() - 7));
                    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("DateGet").style.display = "none";//隱藏
                    //#endregion
                    $('#DateGettext').val(dateLimit_format + ' - ' + today_format);
                    document.getElementById("daybtn").disabled = true;//日報表鎖定
                    document.getElementById("monthbtn").disabled = false;//月報表鎖定
                    document.getElementById("yearbtn").disabled = false;//綜合報表鎖定
                    break;
                case 2: $('#DateGet').prop({ 'type': 'month' });
                    $(".btn-change-quickSearch1").html("本月");
                    $(".btn-change-quickSearch2").html("上個月");
                    var now_month = new Date().toISOString().substring(0, 7);
                    $('#DateGet').val(now_month);
                    document.getElementById("daybtn").disabled = true;//日報表鎖定
                    document.getElementById("monthbtn").disabled = false;//月報表鎖定
                    document.getElementById("yearbtn").disabled = false;//綜合報表鎖定
                    break;
                case 3:
                    $(".btn-change-quickSearch1").html("今年");
                    $(".btn-change-quickSearch2").html("去年");
                    var now_year = new Date().toISOString().substring(0, 4);
                    $('#DateGet').prop({ 'type': 'number', 'min': 1900, 'max': now_year, 'step': 1 });
                    $('#DateGet').val(now_year);
                    document.getElementById("daybtn").disabled = true;//日報表鎖定
                    document.getElementById("monthbtn").disabled = true;//月報表鎖定
                    document.getElementById("yearbtn").disabled = false;//綜合報表鎖定
                    break;
            }
            if (type == 1) {
                timerange = $('#DateGettext').val();
            }
            else {
                timerange = $('#DateGet').val();
            }
            nowform = null;
        }
        //#endregion

        //#region 快速填入條件(EX.今昨天)
        function quickSearch(day) {
            switch (searchType) {
                case 0:
                    if (day == 0) {
                        var today = new Date().toISOString().substring(0, 10);
                        $('#DateGet').val(today).trigger('change');
                    } else {
                        var dateLimit = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().substring(0, 10);
                        $('#DateGet').val(dateLimit).trigger('change');
                    }
                    break;
                case 1:
                    if (day == 0) {
                        //#region 預設近7天
                        var today = new Date();
                        var dateLimit = new Date(new Date().setDate(today.getDate() - 7));
                        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);
                        //#endregion
                        $('#DateGettext').val(dateLimit_format + ' - ' + today_format).trigger('change');
                    } else {
                        //#region 預設近30天
                        var today = new Date();
                        var dateLimit = new Date(new Date().setDate(today.getDate() - 30));
                        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);
                        //#endregion
                        $('#DateGettext').val(dateLimit_format + ' - ' + today_format).trigger('change');
                    }
                    break;
                case 2:
                    if (day == 0) {
                        var now_month = new Date().toISOString().substring(0, 7);
                        $('#DateGet').val(now_month).trigger('change');
                    } else {
                        var dateLimit = new Date(new Date().setMonth(new Date().getMonth() - 1)).toISOString().substring(0, 7);
                        $('#DateGet').val(dateLimit).trigger('change');
                    }
                    break;
                case 3:
                    if (day == 0) {
                        var now_year = new Date().toISOString().substring(0, 4);
                        $('#DateGet').val(now_year).trigger('change');
                    } else {
                        var dateLimit = new Date(new Date().setFullYear(new Date().getFullYear() - 1)).toISOString().substring(0, 4);
                        $('#DateGet').val(dateLimit).trigger('change');
                    }
                    break;
            }
        }
        //#endregion

        //#region 更換input
        $('#DateGet').on('change', function () {
            timerange = $('#DateGet').val();
        });
        //#endregion

        //#region 更換inputtext
        $('#DateGettext').on('change', function () {
            timerange = $('#DateGettext').val();
        });
        //#endregion

        //#region 顯示動態選取電站
        function AddButtonWithStation()
        {
            $('#selectOneStation').empty();
            var stri = '';
            $.each(selecterd_invert, function (index, inverter) {
                if (inverter.value == nowpowerstation)
                {
                    stri += '<button type="button" class="btn btn-success waves-effect waves-themed ml-2 mb-2 btn-station" id="' + inverter.value + '" onclick="selectPowerStation(' + inverter.value + ',this) ">' + inverter.name + '</button>';
                }
                else
                {
                    stri += '<button type="button" class="btn btn-outline-success waves-effect waves-themed ml-2 mb-2 btn-station" id="' + inverter.value + '" onclick="selectPowerStation(' + inverter.value + ',this) ">' + inverter.name + '</button>';
                }
            })
            $('#selectOneStation').append(stri);
            if (nowpowerstation == null && selecterd_invert.length>0) {
                document.getElementById(selecterd_invert[0].value).onclick();
            }
        }
        //#endregion

        //#region 選擇動態選取電站
        function selectPowerStation(a,e)
        {
            nowpowerstation = a;
            if ($('#selectOneStation').find('.btn-station').hasClass("btn-success")) {
                $('#selectOneStation').find('.btn-station').removeClass("btn-success").addClass("btn-outline-success");
            }
            $(e).removeClass("btn-outline-success").addClass("btn-success");
            if (nowform != null && nowform != 2) {
                Dateform(nowform);
            }
        }
        //#endregion

        //#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_invert.push(getstation);
            } else {
                var a = selecterd_invert.filter(function (n, i) {

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

                });
            }
            AddButtonWithStation();
        });


        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.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_invert.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_invert) > -1) {
                        $(this).prop('checked', true);
                    }
                });
                $("#js_list_accordion .collapse").collapse('show');


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

        function tablehand(form) {
            var send_data =
            {
                SearchType: searchType,
                Time: timerange,
                FormType: form,
                PowerStation: nowpowerstation
            }
            var url = "/StationReport/GetTableHead";
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_warning(rel.msg);
                    return;
                }
                $('#TableHead').empty();
                var str = "<tr>";
                switch (form)
                {
                    case 0:
                        str += "<th>Date</th>";
                        $.each(rel.data.inv, function (index, inverter) {
                            haveinvertName.push(inverter);
                            str += "<th>" + inverter + "</th>";
                        })
                        str += "<th>小時<br />發電量<br />(kWh)</th>";
                        str += "<th>小時<br />發電量<br />百分比<br />(%)</th>";
                        str += "<th>小時<br />平均<br />日照度<br />(W/㎡)</th>";
                        str += "<th>小時<br />平均<br />模組<br />溫度<br />(°C)</th>";
                        if (rel.data.showMoney == 1) {
                            str += "<th>小時<br />售電<br />金額<br />(NTD)</th>";
                        }
                        break;
                    case 1:
                        str += "<th>Date</th>";
                        $.each(rel.data.inv, function (index, inverter) {
                            haveinvertName.push(inverter);
                            str += "<th>" + inverter + "</th>";
                        })
                        str += "<th>日<br />發電量<br />(kWh)</th>";
                        str += "<th>日<br />發電量<br />百分比<br />(%)</th>";
                        str += "<th>日照小時(hr)</th>";
                        str += "<th>kWH/kWP</th>";
                        str += "<th>PR%</th>";
                        str += "<th>日<br />平均<br />日照度<br />(W/㎡)</th>";
                        str += "<th>日<br />平均<br />模組溫度<br />(°C)</th>";
                        if (rel.data.showMoney == 1) {
                            str += "<th>日<br />售電金額<br />(NTD)</th>";
                        }
                        break;
                    case 2:
                        str += "<th>區域</th>";
                        str += "<th>電站名稱</th>";
                        str += "<th>發電量</th>";
                        str += "<th>發電小時</th>";
                        str += "<th>平均日照</th>";
                        str += "<th>PR</th>";
                        if (rel.data.showMoney == 1) {
                            str += "<th>發電金額</th>";
                            str += "<th>租金收入</th>";
                            str += "<th>省電費用</th>";
                        }
                        break;
                }
                str += "</tr>";
                $('#TableHead').append(str);
                if (form != 2) {
                    tablebody(form, rel.data.showMoney);
                } else {
                    maxtableinfobody(rel.data.showMoney);
                }
            }, 'json');
        }

        function Dateform(form) {
            $('#hiretable').hide();
            $('#maxtable').hide();
            tablehand(form);
        }

        function tablebody(form,showmoney)
        {
            var send_data =
            {
                SearchType: searchType,
                Time: timerange,
                FormType: form,
                PowerStation: nowpowerstation
            }
            var url = "/StationReport/GetForm";
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    if (rel.code == "9985") {
                        toast_warning(rel.msg);
                    } else {
                        toast_error(rel.msg);
                    }
                    $('#TableBody').empty();
                    $('#totbody').empty();
                    return;
                }
                var sta = "";
                $('#TableBody').empty();
                $('#totbody').empty();
                $('#tothead').empty();
                if (form == 0) {//日報表
                    var thour = 0;
                    var tpr = 0;
                    var tkwh = 0;
                    var kWhkwp = 0;
                    var ntd = 0;
                    var ntdone = 0;

                    $.each(rel.data, function (index, inverter) {
                        sta += "<tr>";
                        sta += "<td>" + inverter.report_date + "</td>";
                        $.each(haveinvertName, function (item, i) {
                            if (inverter[i] == null) {
                                sta += "<td>" + 0 + "</td>";
                            } else {
                                sta += "<td>" + Number(inverter[i]).toFixed(2)  + "</td>";
                            }
                        });
                        sta += "<td>" + Number(inverter.hourKWH) + "</td>";
                        sta += "<td>" + Number(inverter.hourKWHp) + "</td>";
                        sta += "<td>" + Number(inverter.irradiance) + "</td>";
                        sta += "<td>" + Number(inverter.temperature) + "</td>";
                        if (showmoney == 1) {
                            sta += "<td>" + Number(inverter.hourmoney) + "</td>";
                        }
                        sta += "</tr>";
                        thour = inverter.tothour ? inverter.tothour.toFixed(2) : 0;
                        tpr = inverter.pr ? inverter.pr.toFixed(2) : 0;
                        tkwh = inverter.totKWH ? inverter.totKWH.toFixed(2) : 0;
                        kWhkwp = inverter.totKWHKWP ? inverter.totKWHKWP.toFixed(2) : 0;
                        ntd = inverter.totmoney ? inverter.totmoney.toFixed(2) : 0;
                        ntdone = inverter.totmoney / inverter.totKWH ? (inverter.totmoney / inverter.totKWH).toFixed(2) : 0;
                    })
                    var stc = "<tr>";
                    stc += "<th>" + '日照小時' + "</th>";
                    stc += "<th>" + 'kWH/kWP' + "</th>";
                    stc += "<th>" + 'PR%' + "</th>";
                    stc += "<th>" + '日發電量(kWh)' + "</th>";
                    if (showmoney == 1) {
                        stc += "<th>" + '日售電金額(NTD)' + "</th>";
                        stc += "<th>" + '日售電單價(NTD)' + "</th>";
                    }
                    stc += "</tr>";


                    var stb = "<tr>";
                    stb += "<td>" + thour + "</td>";
                    stb += "<td>" + kWhkwp + "</td>";
                    stb += "<td>" + tpr + "</td>";
                    stb += "<td>" + tkwh + "</td>";
                    if (showmoney == 1) {
                        stb += "<td>" + ntd + "</td>";
                        stb += "<td>" + ntdone + "</td>";
                    }
                    stb += "</tr>";


                    $('#TableBody').append(sta);
                    $('#totbody').append(stb);
                    $('#tothead').append(stc);
                    haveinvertName = [];
                }
                else {//月報表
                    var avghour = 0;
                    var avgKWHKWP = 0;
                    var avgdayKWH = 0;
                    var monthKWH = 0;
                    var monthmoney = 0;
                    var monthmoneyone = 0;
                    var monthday = 0;

                    var check_hire = false;
                    var sitedb = "";
                    $.each(rel.data, function (index, inverter) {
                        sta += "<tr>";
                        sta += "<td>" + inverter.report_date + "</td>";
                        $.each(haveinvertName, function (item, i) {
                            if (inverter[i] == null) {
                                sta += "<td>" + 0 + "</td>";
                            } else {
                                sta += "<td>" + inverter[i] + "</td>";
                            }
                        });
                        sta += "<td>" + inverter.dayKWH + "</td>";
                        sta += "<td>" + inverter.dayKWHp + "</td>";
                        sta += "<td>" + inverter.tothour + "</td>";
                        sta += "<td>" + inverter.KWHKWP + "</td>";
                        sta += "<td>" + inverter.PR + "</td>";
                        sta += "<td>" + inverter.irradiance + "</td>";
                        sta += "<td>" + inverter.temperature + "</td>";
                        if (showmoney == 1) {
                            sta += "<td>" + inverter.soldmoney + "</td>";
                        }
                        sta += "</tr>";
                        avghour += inverter.tothour ? inverter.tothour : 0;
                        avgKWHKWP += inverter.KWHKWP ? inverter.KWHKWP : 0;
                        avgdayKWH += inverter.dayKWH ? inverter.dayKWH : 0;
                        monthKWH = inverter.monthKWH ? inverter.monthKWH : 0;
                        monthmoney = inverter.monthmoney ? inverter.monthmoney : 0;
                        monthmoneyone += inverter.monthmoneyone ? inverter.monthmoneyone : 0;

                        if (inverter.SolarType == 1)
                        {
                            check_hire = true;
                            sitedb = inverter.SiteDB
                        }

                    })
                    monthday = rel.data.length;


                    var stc = "<tr>";
                    stc += "<th>" + '日日照小時平均' + "</th>";
                    stc += "<th>" + '日kWH/kWP平均' + "</th>";
                    stc += "<th>" + '日發電量平均(kWh)' + "</th>";
                    stc += "<th>" + '月發電量(kWh)' + "</th>";
                    if (showmoney == 1) {
                        stc += "<th>" + '月售電金額(NTD)' + "</th>";
                        stc += "<th>" + '月售電單價(NTD)' + "</th>";
                    }
                    stc += "<th>" + '月售電天數' + "</th>";
                    stc += "</tr>";

                    var stb = "<tr>";
                    if (monthday == 0) {
                        stb += "<td>" + 0 + "</td>";
                        stb += "<td>" + 0 + "</td>";
                        stb += "<td>" + 0 + "</td>";
                        stb += "<td>" + 0 + "</td>";
                        stb += "<td>" + 0 + "</td>";
                        stb += "<td>" + 0 + "</td>";
                        stb += "<td>" + 0 + "</td>";
                        stb += "</tr>";
                    }
                    else
                    {
                        stb += "<td>" + (avghour / monthday).toFixed(2) + "</td>";
                        stb += "<td>" + (avgKWHKWP / monthday).toFixed(2) + "</td>";
                        stb += "<td>" + (avgdayKWH / monthday).toFixed(2) + "</td>";
                        stb += "<td>" + monthKWH + "</td>";
                        if (showmoney == 1) {
                            stb += "<td>" + monthmoney + "</td>";
                            stb += "<td>" + (monthmoneyone / monthday).toFixed(2) + "</td>";
                        }
                        stb += "<td>" + monthday + "</td>";
                        stb += "</tr>";
                    }
                    var std = "";
                    if (check_hire == true && showmoney == 1)
                    {
                        var dataTosent =
                        {
                            Sitedb: sitedb,
                            PowerstationId: nowpowerstation
                        }
                        $('#HireTableBody').empty();
                        var posturl = "/StationReport/GetHireInfo";
                        $.post(posturl, dataTosent, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.data.msg);
                                return;
                            }
                            $.each(rel.data, function (index, value) {
                                std += "<tr>";
                                std += "<td>" + value.landowner + "</td>";
                                std += "<td>" + value.leaseRate + "%" + "</td>";
                                std += "<td>" + (monthmoney * value.leaseRate / 100).toFixed(2) + "</td>";
                                std += "<td>" + (monthmoney * value.leaseRate / 100 * 1.05).toFixed(2) + "</td>";
                                std += "</tr>";
                            })
                            $('#HireTableBody').append(std);
                            $('#hiretable').show();
                        })
                    }


                    $('#TableBody').append(sta);
                    $('#totbody').append(stb);
                    $('#tothead').append(stc);


                    haveinvertName = [];
                }
                $('#overviewtable').show();
                $('#detailtable').show();
                
                nowform = form;
            }, 'json');
        }

        function ExportExcel() {
            var send_data =
            {
                SearchType: searchType,
                Time: timerange,
                FormType: nowform,
                PowerStation: selecterd_invert
            }
            if (send_data.FormType != null && send_data.PowerStation.length != 0 && send_data.FormType != 2) {
                window.location = "/StationReport/ExportExcel?post=" + JSON.stringify(send_data);
            }
            else
            {
                if (send_data.FormType != 2) {
                    toast_warning("請先選擇電站及報表類型");
                }
                else
                {
                    window.location = "/StationReport/ExportExcelmaxtable?post=" + JSON.stringify(send_data);
                }
            }
        }

        function maxtableinfobody(showmoney)
        {
            var send_data =
            {
                SearchType: searchType,
                Time: timerange,
                FormType: 2,
                PowerStation: selecterd_invert
            }
            var url = "/StationReport/GetMaxForm";
            var StrInfoBody;
            var CityArray = [];
            var CityInfoBody;
            var TotalHead;
            var TotalBody;
            var kwhkwp = 0;
            var kwp = 0;
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_warning(rel.msg);
                    return;
                }
                //下方
                $.each(rel.data, function (index, data) {
                    var hirerate = 0;
                    if (data.powerstationType == 1)
                    {
                        hirerate = hire(data.powerstationDB, data.powerstationId);
                    }

                    var cityinfo = {
                        city: data.cityName,
                        kwp: data.kwh,
                        hour: data.solarHour,
                        count : 1
                    }
                    if (CityArray.length == 0) {
                        CityArray.push(cityinfo);
                    }
                    else
                    {
                        var npush = true;
                        CityArray.filter(function (n, i) {
                            if (n.city == data.cityName) {
                                n.kwp += cityinfo.kwp;
                                n.hour += cityinfo.hour;
                                n.count += cityinfo.count;
                                npush = false;
                            }
                        });
                        if (npush) {
                            CityArray.push(cityinfo);
                        }
                    }


                    StrInfoBody += "<tr>";
                    StrInfoBody += "<td>" + data.cityName + data.areaName + "</td>";
                    StrInfoBody += "<td>" + data.powerstationName + "</td>";
                    StrInfoBody += "<td>" + data.kwh.toFixed(2) + "</td>";
                    StrInfoBody += "<td>" + data.solarHour.toFixed(2) + "</td>";
                    StrInfoBody += "<td>" + data.avgIrradiance.toFixed(2) + "</td>";
                    StrInfoBody += "<td>" + data.avgPR.toFixed(2) + "</td>";
                    if (showmoney == 1) {
                        StrInfoBody += "<td>" + data.todayMoney.toFixed(2) + "</td>";

                        StrInfoBody += "<td>" + (data.todayMoney * hirerate * 0.01).toFixed(2)+ "</td>";

                        StrInfoBody += "<td>" + data.todayMoney.toFixed(2) + "</td>";
                    }



                    StrInfoBody += "</tr>";
                    kwp += data.kwh;
                    kwhkwp += data.avgKWHKWP;

                })
                //中間
                $.each(CityArray, function (index, data) {
                    CityInfoBody += "<tr>";
                    CityInfoBody += "<td>" + data.city + "</td>";
                    CityInfoBody += "<td>" + (data.kwp / data.count).toFixed(2) + "</td>";
                    CityInfoBody += "<td>" + (data.hour / data.count).toFixed(2) + "</td>";
                    CityInfoBody += "</tr>";
                })
                //上面
                //#region TotalHead
                TotalHead += "<tr>";
                TotalHead += "<th>" + "時間" + "</th>";
                TotalHead += "<th>" + "發電量" + "</th>";
                TotalHead += "<th>" + "有效日照時數" + "</th>";
                TotalHead += "</tr>";
                //#endregion
                //#region TotalBody
                TotalBody += "<tr>";
                TotalBody += "<th>" + timerange + "</th>";
                TotalBody += "<th>" + kwp.toFixed(2) + "</th>";
                TotalBody += "<th>" + (kwhkwp / rel.data.length).toFixed(2) + "</th>";
                TotalBody += "</tr>";
                //#endregion

                $('#totbody').empty();
                $('#totbody').append(TotalBody);

                $('#tothead').empty();
                $('#tothead').append(TotalHead);
                $('#TableBody').empty();
                $('#TableBody').append(StrInfoBody);
                $('#maxtableBody').empty();
                $('#maxtableBody').append(CityInfoBody);
                $('#maxtable').show();

                $('#overviewtable').show();
                $('#detailtable').show();
               
                nowform = 2;
            })
        }

        function hire(db, id)
        {
            var hirerate = 0;
            var dataTosent =
            {
                Sitedb: db,
                PowerstationId: id
            }
            var posturl = "/StationReport/GetHireInfo";
            $.ajax({
                url: posturl,
                type: "POST",
                dataType: 'json',
                data: dataTosent,
                cache: false,
                async: false,
                success: function (response) {
                    $.each(response.data, function (index, value) {
                        hirerate += Number(value.leaseRate);
                    })
                }
            });
            return hirerate;
        }

    </script>
}