@{
    ViewData["MainNum"] = "7";
    ViewData["SubNum"] = "3";
    ViewData["Title"] = "裝置管理";
}
@using SolarPower.Models.Role
@model RoleLayerEnum

<ol class="breadcrumb page-breadcrumb">
    <li class="breadcrumb-item"><a href="javascript:void(0);">系統管理</a></li>
    <li class="breadcrumb-item active">@ViewData["Title"]</li>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>

<div class="subheader">
    <h1 class="subheader-title">
        <i class='subheader-icon fal fa-globe'></i> @ViewData["Title"]
    </h1>
</div>
<!-- Your main content goes below here: -->

<div class="d-flex justify-content-center text-secondary" style="top: 10%; transform: translateY(50%); z-index: 100; position: relative;">
    <div class="spinner-border" role="status" style="width: 3rem; height: 3rem; display:none;" id="loading"></div>
</div>

<div class="row">
    <div class="col-xl-12">
        <div id="panel-5" class="panel">
            <div class="panel-container show">
                <div class="panel-content">
                    @*只有平台人員可以新增公司*@
                    @if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformUser)
                    {
                        <button type="button" class="btn btn-success waves-effect waves-themed mb-3" onclick="AddSensor()">
                            <span class="fal fa-plus mr-1"></span>
                            新增
                        </button>
                    }
                    <div class="card-body">
                        <div class="w-100">
                            <table id="SensorType_table" class="table table-bordered table-hover m-0 text-center">
                                <thead class="thead-themed">
                                    <tr>
                                        <th>裝置編號</th>
                                        <th>啟用</th>
                                        <th>裝置名稱</th>
                                        <th>英文簡稱</th>
                                        <th>建立時間</th>
                                        <th>功能</th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="SensorType-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="SensorType-form" id="SensorType-form">

                    <div class="row">
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorType_Name_modal"><span class="text-danger">*</span>設備名稱</label>
                            <input type="text" id="SensorType_Name_modal" name="SensorType_Name_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorType_EName_modal"><span class="text-danger">*</span>設備英文名稱</label>
                            <input type="text" id="SensorType_EName_modal" name="SensorType_EName_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-3">
                            <label class="form-label" for="SensorType_Enabled_modal">啟用</label>
                            <select class="form-control" id="SensorType_Enabled_modal">
                                <option value="0" action>未啟用</option>
                                <option value="1">啟用</option>
                            </select>
                        </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="SaveSensorType()">確定</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="SensorDetail-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="SensorDetail-form" id="SensorDetail-form">

                    <div class="row">
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorDetail_SensorType_modal"><span class="text-danger">*</span>裝置類型</label>
                            <input type="text" id="SensorDetail_SensorType_modal" name="SensorDetail_SensorType_modal" class="form-control" disabled>
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorDetail_ItemName_modal"><span class="text-danger">*</span>項目名稱</label>
                            <input type="text" id="SensorDetail_ItemName_modal" name="SensorDetail_ItemName_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorDetail_ItemEName_modal"><span class="text-danger">*</span>英文簡稱</label>
                            <input type="text" id="SensorDetail_ItemEName_modal" name="SensorDetail_ItemEName_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorDetail_WarningURL_modal"><span class="text-danger">*</span>警告網址</label>
                            <input type="text" id="SensorDetail_WarningURL_modal" name="SensorDetail_WarningURL_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-3">
                            <label class="form-label" for="SensorDetail_HourType_modal">每小時取值類別</label>
                            <select class="form-control" id="SensorDetail_HourType_modal">
                                <option value="Sum" action>總數</option>
                                <option value="Max">最大值</option>
                                <option value="Avg">平均值</option>
                                <option value="Min">最小值</option>
                            </select>
                        </div>
                        <div class="form-group col-lg-3">
                            <label class="form-label" for="SensorDetail_DayType_modal">每日取值類別</label>
                            <select class="form-control" id="SensorDetail_DayType_modal">
                                <option value="Sum" action>總數</option>
                                <option value="Max">最大值</option>
                                <option value="Avg">平均值</option>
                                <option value="Min">最小值</option>
                            </select>
                        </div>
                        <div class="form-group col-lg-3">
                            <label class="form-label" for="SensorDetail_MonthType_modal">每月取值類別</label>
                            <select class="form-control" id="SensorDetail_MonthType_modal">
                                <option value="Sum" action>總數</option>
                                <option value="Max">最大值</option>
                                <option value="Avg">平均值</option>
                                <option value="Min">最小值</option>
                            </select>
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorDetail_UpperValue_modal"><span class="text-danger">*</span>上限值</label>
                            <input type="text" id="SensorDetail_UpperValue_modal" name="SensorDetail_UpperValue_modal" class="form-control">
                        </div>
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="SensorDetail_LowerValue_modal"><span class="text-danger">*</span>下限值</label>
                            <input type="text" id="SensorDetail_LowerValue_modal" name="SensorDetail_LowerValue_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="SaveSensorDetail()">確定</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal 細項項目資訊 -->
<div class="modal fade" id="sensor-detail-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-xl" 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">
                <table id="sensor-detail-table" class="table table-bordered text-center">
                    <thead>
                        <tr>
                            <th>項目名稱</th>
                            <th>英文簡稱</th>
                            <th>小時的數值類別</th>
                            <th>天的數值類別</th>
                            <th>月的數值類別</th>
                            <th>警告URL</th>
                            <th>上限</th>
                            <th>下限</th>
                            <th>功能</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
                @*<div class="col-12"> <a href="javascript:;" class="btn btn-success waves-effect waves-themed mb-3 " id="add-user-power-station" onclick="AddUserPowerStation(this)"><span class="fal fa-plus mr-1"></span> 增加項目</a> </div>*@
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        var SensorTypeDeviceTable;
        var selected_id = 0;
        var selected_type_id = 0;

        //#region 新增裝置資料
        function AddSensor() {
            selected_id = 0;
            document.getElementById('SensorType_Enabled_modal').disabled = false;
            $("#SensorType-modal .modal-title").html("裝置資料 - 新增");
            $("#SensorType-form").trigger("reset");
            $("#SensorType-modal").modal();
        }
        //#endregion

        function showLoading() {
            var i = document.getElementById("loading");
            i.style.display = "block";
        }

        function hideLoading() {
            var i = document.getElementById("loading");
            i.style.display = "none";
        }

        $(function () {
            //#region 裝置類型列表 DataTable
            showLoading();
            SensorTypeDeviceTable = $("#SensorType_table").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": false,
                "columns": [{
                    "data": "id"
                }, {
                    "data": "enabledName"
                }, {
                    "data": "sensorName"
                }, {
                    "data": "sensorEName"
                }, {
                    "data": "createdAt"
                }, {
                    "data": null,
                    "defaultContent": '<button class="btn btn-success detail-btn">新增細項</button><button class="btn btn-primary edit-btn">修改</button> <button class="btn btn-danger del-btn">刪除</button>'
                }],
                "columnDefs": [{
                    'targets': 2,
                    'searchable': false,
                    'orderable': false,
                    'render': function (data, type, full, meta) {
                        return '<a href="javascript:void(0);" onclick="GetSensorDetail(' + full.id + ')">' + data + '</a>';
                    }
                }],
                "language": {
                    "emptyTable": "查無資料",
                    "processing": "處理中...",
                    "loadingRecords": "載入中...",
                    "lengthMenu": "顯示 _MENU_ 項結果",
                    "zeroRecords": "沒有符合的結果",
                    "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                    "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                    "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                    "infoPostFix": "",
                    "search": "搜尋:",
                    "paginate": {
                        "first": "第一頁",
                        "previous": "上一頁",
                        "next": "下一頁",
                        "last": "最後一頁"
                    }
                },
                'createdRow': function (row, data, dataIndex) {
                    $(row).attr('data-id', data.id);
                },
                "ajax": {
                    "url": "/SensorType/SensorTypeDeviceTable",
                    "type": "POST",
                    "data": function (d) {
                        //d.stationId = stationId;
                    },
                    "dataSrc": function (rel) {
                        if (rel.data.code == "9999") {
                            hideLoading();
                            toast_error(rel.data.msg);
                            return;
                        }

                        data = rel.data.data;

                        if (data == null || data.length == 0) {
                            this.data = [];
                        }
                        hideLoading();
                        return data;
                    }
                },
                "error": function (xhr, error, thrown) {
                    hideLoading();
                    console.log(xhr);
                }
            });
            //#endregion
        });

        //#region 儲存裝置類型資料
        function SaveSensorType() {
            showLoading();
            var url = "/SensorType/SaveSensorType";
            if ($("#SensorType-form").valid()) {
                var send_data = {
                    Id: selected_id,
                    Enabled: $("#SensorType_Enabled_modal").val(),
                    SensorName: $("#SensorType_Name_modal").val(),
                    SensorEName: $("#SensorType_EName_modal").val()
                }
                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        hideLoading();
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        hideLoading();
                        toast_ok(rel.msg);
                        $('#SensorType-modal').modal('hide');
                        SensorTypeDeviceTable.ajax.reload();
                        return;
                    }
                }, 'json');
            }
        }
        //#endregion

        //#region 刪除使用者
        $('#SensorType_table').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) {
                        //取得單一系統管理員
                        showLoading();
                        var url = "/SensorType/DeleteOneSensorType/";
                        var send_data = {
                            Id: selected_id
                        }
                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                hideLoading();
                                toast_error(rel.msg);
                                return;
                            }

                            toast_ok(rel.msg);


                            SensorTypeDeviceTable.ajax.reload();
                            hideLoading();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 編輯裝置
        $('#SensorType_table').on("click", "button.edit-btn", function () {

            $("#SensorType-modal .modal-title").html("裝置資料 - 修改");

            selected_id = $(this).parents('tr').attr('data-id');

            //取得單一裝置
            showLoading();
            var url = "/SensorType/GetOneSensorType/";

            var send_data = {
                id: selected_id
            }

            $.post(url, send_data, function (rel) {
                if (rel.code == "9999") {
                    hideLoading();
                    toast_error(rel.msg);
                    return;
                }
                else if (rel.code == "9998") {
                    hideLoading();
                    toast_error(rel.msg);
                    return;
                }

                $("#SensorType_Name_modal").val(rel.data.sensorName);
                $("#SensorType_EName_modal").val(rel.data.sensorEName);
                $("#SensorType_Enabled_modal").val(rel.data.enabled);

                $("#SensorType-modal").modal();
                hideLoading();
            }, 'json');

        });
        //#endregion

        //#region 新增裝置-細項
        $('#SensorType_table').on("click", "button.detail-btn", function () {
            $("#SensorDetail-modal .modal-title").html("裝置細項 - 新增");
            $("#SensorDetail-form").trigger("reset");
            document.getElementById('SensorDetail_SensorType_modal').disabled = true;
            selected_id = 0;
            selected_type_id = $(this).parents('tr').attr('data-id');


            //取得單一裝置
            showLoading();
            var url = "/SensorType/GetOneSensorType/";

            var send_data = {
                id: selected_type_id
            }

            $.post(url, send_data, function (rel) {
                if (rel.code == "9999") {
                    hideLoading();
                    toast_error(rel.msg);
                    return;
                }
                else if (rel.code == "9998") {
                    hideLoading();
                    toast_error(rel.msg);
                    return;
                }

                //$("#SensorDetail_SensorType_modal").val(selected_type_id);
                $("#SensorDetail_SensorType_modal").val(rel.data.sensorName);

                $("#SensorDetail-modal").modal();
                hideLoading();
            }, 'json');
        });
        //#endregion

        //#region 儲存裝置細項資料
        function SaveSensorDetail() {
            showLoading();
            var url = "/SensorType/SaveSensorDetail";
            if ($("#SensorDetail-form").valid()) {
                var send_data = {
                    Id: selected_id,
                    SensorTypeId: selected_type_id,
                    ItemName: $("#SensorDetail_ItemName_modal").val(),
                    ItemEName: $("#SensorDetail_ItemEName_modal").val(),
                    HourType: $("#SensorDetail_HourType_modal").val(),
                    DayType: $("#SensorDetail_DayType_modal").val(),
                    MonthType: $('#SensorDetail_MonthType_modal').val(),
                    WarningURL: $('#SensorDetail_WarningURL_modal').val(),
                    UpperValue: $('#SensorDetail_UpperValue_modal').val(),
                    LowerValue: $('#SensorDetail_LowerValue_modal').val()
                }
                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        hideLoading();
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        $('#SensorDetail-modal').modal('hide');
                        SensorTypeDeviceTable.ajax.reload();
                        hideLoading();
                        return;
                    }
                }, 'json');
            }
        }
        //#endregion

        //#region 裝置-細項資訊
        function GetSensorDetail(id) {
            var send_data = {
                Id: id
            }
            showLoading();
            var url_sensorType_info = "/SensorType/GetOneSensorType";

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

                $("#sensor-detail-modal .modal-title").html(rel.data.sensorName + "- 細項");
                hideLoading();
            }, 'json');

            UpdateSensorDetailTable(id, function (returnData) {
                if (returnData) {
                    $("#sensor-detail-modal").modal();
                }
            });
        }
        //#endregion

        function UpdateSensorDetailTable(sensorType_id, callback) {
            showLoading();
            var url = "/SensorType/GetSensorDetail";
            var send_data = {
                Id: sensorType_id
            }

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

                sensorDetailTable = $("#sensor-detail-table > tbody");

                sensorDetailTable.empty();
                rel.data.forEach(function (value, index) {
                    var str = "";
                    str += "<tr>";
                    str += "<td>" + value.itemName + "</td>";
                    str += "<td>" + value.itemEName + "</td>";
                    str += "<td>" + value.hourTypeName + "</td>";
                    str += "<td>" + value.dayTypeName + "</td>";
                    str += "<td>" + value.monthTypeName + "</td>";
                    str += "<td>" + value.warningURL + "</td>";
                    str += "<td>" + value.upperValue + "</td>";
                    str += "<td>" + value.lowerValue + "</td>";
                    str += "<td>" + '<button type="button" class="btn btn-danger btn-pills waves-effect waves-themed del-sensor-detail" data-id="' + value.id + '">刪除</button>' + "</td>";
                    str += "</tr>";
                    sensorDetailTable.append(str);
                });

                SensorTypeDeviceTable.ajax.reload();

                callback(true);
                hideLoading();
            }, 'json');
        }

        //#region 刪除裝置細項
        $("#sensor-detail-table").on("click", "button.del-sensor-detail", function () {
            selected_id = $(this).attr('data-id');
            var del_btn = $(this);
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        //取得單一裝置細項
                        showLoading();
                        var url = "/SensorType/DeleteOneSensorDetail/";
                        var send_data = {
                            Id: selected_id
                        }
                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                hideLoading();
                                toast_error(rel.msg);
                                return;
                            }

                            del_btn.parents("tr").remove();
                            toast_ok(rel.msg);
                            sensorDetailTable.ajax.reload();
                            hideLoading();
                        }, 'json');
                    }
                });
        });

    </script>
}