@{
    ViewData["MainNum"] = "7";
    ViewData["SubNum"] = "2";
    ViewData["Title"] = "帳號管理";
}

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

<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">
                    <div class="subheader">
                        <h1 class="subheader-title">
                            <img src="img/asus.png" id="company-logo"><span id="company-name">華碩電腦</span>
                        </h1>
                    </div>
                    <ul class="nav nav-tabs" id="tabs" role="tablist">
                        <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#tab-user-manager" role="tab"><i class="fal fa-home text-success"></i> <span class="hidden-sm-down ml-1">帳號管理</span></a></li>
                        <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#tab-role-manager" role="tab"><i class="fal fa-user text-primary"></i> <span class="hidden-sm-down ml-1">角色管理</span></a></li>
                        <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#tab-role-auth" role="tab"><i class="fal fa-cog text-danger"></i> <span class="hidden-sm-down ml-1">角色權限</span></a></li>
                    </ul>
                    <div class="tab-content p-3">
                        <div class="tab-pane fade show active" id="tab-user-manager" role="tabpanel" aria-labelledby="tab-user-manager">
                            @Html.Partial("_UserManager")
                        </div>

                        <div class="tab-pane fade" id="tab-role-manager" role="tabpanel" aria-labelledby="tab-role-manager">
                            @Html.Partial("_RoleManager")
                        </div>

                        <div class="tab-pane fade" id="tab-role-auth" role="tabpanel" aria-labelledby="tab-role-auth">
                            @Html.Partial("_RoleAuth")
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        var userTable; var roleTable; var roleAuthTable; var roleAuthNotJoinTable;
        var selected_id = 0, selected_role_id = 0, selected_company_id = 0;
        var selected_tab = "";

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

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

        $(function () {
            selected_tab = $('#tabs').find("li a.active").attr("href"); // 當前tab

            //#region 預先載入公司下拉式選單select_option
            showLoading();
            var url_company_select_option = "/Company/GetCompanySelectOptionList";
            $.get(url_company_select_option, function (rel) {
                if (rel.code != "0000") {
                    hideLoading();
                    toast_error(rel.msg);
                    return;
                }

                $(".select_user_company").empty();

                $.each(rel.data, function (index, val) {
                    $(".select_user_company").append($("<option />").val(val.value).text(val.text));
                });

                //預設查詢第一個
                $(".select_user_company").val($(".select_user_company option:first").val()).trigger('change');
                hideLoading();

            });
            //#endregion

            //#region 選擇公司後角色下拉式選單select_option
            $(".select_user_company").change(function () {

                var select_option_with_tab = $(this).attr('data-tab');

                if (selected_tab != select_option_with_tab) {
                    //判斷是否為當前tab的 公司選單傳值被修改
                    return;
                }

                //變更其他tab裡面select_user_company的值
                switch (selected_tab) {
                    case "#tab-user-manager":
                        $("#select_company_role_roleManager_tab").val($(this).val()).trigger('change');
                        $("#select_companyId_roleAuth_tab").val($(this).val()).trigger('change');
                        break;
                    case "#tab-role-manager":
                        $("#select_user_company_userManager_tab").val($(this).val()).trigger('change');
                        $("#select_companyId_roleAuth_tab").val($(this).val()).trigger('change');
                        break;
                    case "#tab-role-auth":
                        $("#select_user_company_userManager_tab").val($(this).val()).trigger('change');
                        $("#select_company_role_roleManager_tab").val($(this).val()).trigger('change');
                        break;
                }

                //查詢該公司的基本資料
                showLoading();
                var url_company_info = "/Company/GetOneCompany"

                var send_data = {
                    Id: $(this).val()
                }

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

                    $("#company-logo").attr("src", rel.data.logo + "?v=" + Date.now());
                    $("#company-name").html(rel.data.name);

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

                //更新當前剩餘可註冊使用者人數
                UpdateRegisterNumber($(this).val());

                //查詢該公司的角色
                UpdateCompanyRoleSelectOption($(this).val());


            });
            //#endregion

            //#region 切換頁簽判斷被選中的tab
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                selected_tab = $(e.target).attr("href")

                switch (selected_tab) {
                    case "#tab-user-manager":
                        userTable.ajax.reload();
                        break;
                    case "#tab-role-manager":
                        roleTable.ajax.reload();
                        break;
                    case "#tab-role-auth":
                        roleAuthTable.ajax.reload();
                        break;
                }
            });
            //#endregion

            //#region 使用者列表 DataTable
            showLoading();
            userTable = $("#user_table").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": false,
                "deferLoading": 0,
                "order": [[7, "desc"]],
                "columns": [{
                    "data": "id"
                }, {
                    "data": "companyName"
                }, {
                    "data": "name"
                }, {
                    "data": "roleName"
                }, {
                    "data": "email"
                }, {
                    "data": "phone"
                }, {
                    "data": "spStationAmount",
                    "render": $.fn.DataTable.render.number(",")
                }, {
                    "data": "createdAt"
                }, {
                    "data": null,
                    "defaultContent": '<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="GetUserPowerStation(' + 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": "最後一頁"
                    },
                    "aria": {
                        "sortAscending": ": 升冪排列",
                        "sortDescending": ": 降冪排列"
                    }
                },
                'createdRow': function (row, data, dataIndex) {
                    $(row).attr('data-id', data.id);
                },
                "ajax": {
                    "url": "/User/UserList",
                    "type": "POST",
                    "data": function (d) {
                        d.SelectedCompanyId = $('#select_user_company_userManager_tab').val();
                        d.Name = $('#user_name').val();
                        d.SelectedRoleId = $('#select_company_role_userManager_tab').val();
                    },
                    "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 角色管理列表 DataTable
            showLoading();
            roleTable = $("#role_table").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": false,
                "deferLoading": 0,
                "order": [[4, "desc"]],
                "columns": [{
                    "data": "id"
                }, {
                    "data": "companyName"
                }, {
                    "data": "name"
                }, {
                    "data": "creatorName"
                }, {
                    "data": "createdAt"
                }, {
                    "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);
                },
                "ajax": {
                    "url": "/Role/RoleList",
                    "type": "POST",
                    "data": function (d) {
                        d.SelectedCompanyId = $('#select_company_role_roleManager_tab').val();
                        d.Name = $('#role_name').val();
                    },
                    "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 角色權限列表 DataTable
            showLoading();
            roleAuthTable = $("#roleAuth_table").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": false,
                "deferLoading": 0,
                "order": [[6, "desc"]],
                "columns": [{
                    "data": null,
                }, {
                    "data": "companyName"
                }, {
                    "data": "roleName"
                }, {
                    "data": "authPageSubName"
                }, {
                    "data": "authPageTagName"
                }, {
                    "data": "creatorName"
                }, {
                    "data": "createdAt"
                }, {
                    "data": null,
                    "defaultContent": '<button class="btn btn-danger del-btn">刪除</button>'
                }],
                "columnDefs": [{
                    'targets': 0,
                    'searchable': false,
                    'orderable': false,
                    'className': 'dt-body-center',
                    "createdCell": function (td, cellData, rowData, row, col) {
                        $(td).html(row + 1)
                    }
                }, {
                    'targets': 7,
                    'searchable': false,
                    'orderable': false,
                    'className': 'dt-body-center',
                    "createdCell": function (td, cellData, rowData, row, col) {
                        if (rowData.authCode == 'A') {
                            $(td).html("");
                        }
                    }
                }],
                "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-authCode', data.id + "_" + data.authCode);
                },
                "ajax": {
                    "url": "/Role/RoleAuthList",
                    "type": "POST",
                    "data": function (d) {
                        d.SelectedCompanyId = $('#select_companyId_roleAuth_tab').val();
                        d.SelectedRoleId = $('#select_roleId_roleAuth_tab').val();
                    },
                    "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 角色未加入權限列表 DataTable
            showLoading();
            roleAuthNotJoinTable = $("#roleAuth_NotJoin_table").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": false,
                "info": true,
                "autoWidth": false,
                "responsive": false,
                "deferLoading": 0,
                // "order": [[1, "desc"]],
                "columns": [{
                    "data": "authCode"
                }, {
                    "data": "mainName"
                }, {
                    "data": "subName"
                }, {
                    "data": "tagName"
                }],
                "columnDefs": [{
                    'targets': 0,
                    'searchable': false,
                    'orderable': false,
                    'className': 'dt-body-center',
                    'render': function (data, type, full, meta) {
                        var check_html = "";
                        check_html += '<div class="custom-control custom-checkbox">';
                        check_html += '<input type="checkbox" class="custom-control-input" name="selectedAuthPage[]" id="auth-page-' + data + '" value="' + data + '" /> ';
                        check_html += '<label class="custom-control-label" for="auth-page-' + data + '" />';
                        check_html += '</div>';
                        return check_html;
                    }
                }],
                "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-authCode', data.id + "_" + data.authCode);
                },
                "ajax": {
                    "url": "/Role/GetRoleNotAuthPageList",
                    "type": "POST",
                    "data": function (d) {
                        d.SelectedCompanyId = $('#select_companyId_roleAuth_tab').val();
                        d.SelectedRoleId = $('#select_roleId_roleAuth_tab').val();
                    },
                    "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 角色權限全選
            $("#select-all-role-auth").change(function () {

                var rows = roleAuthNotJoinTable.rows({ 'search': 'applied' }).nodes();

                if (this.checked) {
                    $("input[name='selectedAuthPage[]']", rows).prop('checked', this.checked);
                } else {
                    $("input[name='selectedAuthPage[]']", rows).prop('checked', this.checked);
                }
            });
            //#endregion
        });

        //#region 帳號管理Tab

        //#region 搜尋使用者列表
        function SearchUser() {
            userTable.ajax.reload();
        }
        //#endregion

        //#region 新增使用者
        function AddUser() {
            selected_id = 0;
            $("#user-modal .modal-title").html("人員基本資料 - 新增");

            //新增使用者不出現 預設密碼-----------------------
            var i = document.getElementById("btnDefPasswd");
            i.style.display = "none";
            //------------------------------------------------
            $("#user-form").trigger("reset");
            $("#user_companyId_modal").val($("#select_user_company_userManager_tab").val());
            $("#user_account_modal").prop("disabled", false);
            $(".user_account_same_email_div").show();
            $("#user_account_same_email").prop("disabled", false);
            $(".user-password-div").show();

            $("#user-modal").modal();
        }
        //#endregion

        //#region 帳號是否等同Email
        $('#user_account_same_email').change(function () {
            var email = $("#user_email_modal").val();

            if (email == undefined || email == null || email == "") {
                toast_warning("請先填寫email");
                $(this).prop("checked", false);
                return;
            }

            if (this.checked && selected_id == 0) {
                //只提供新增時，可透過email填入帳號欄位
                $("#user_account_modal").val(email);
                $("#user_account_modal").prop("disabled", true);
            }
            else {
                $("#user_account_modal").prop("disabled", false);
            }
        });
        //#endregion

        //#region 編輯使用者管理員
        $('#user_table').on("click", "button.edit-btn", function () {

            $("#user-modal .modal-title").html("人員基本資料 - 編輯");

            //修改使用者出現 預設密碼-----------------------------
            var i = document.getElementById("btnDefPasswd");
            i.style.display = "block";
            //----------------------------------------------------

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

            //取得單一使用者管理員
            showLoading();
            var url = "/User/GetOneUser/";

            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;
                }

                $("#user_companyId_modal").val(rel.data.companyId);
                $("#user_companyId_modal").prop("disabled", true);
                $("#user_name_modal").val(rel.data.name);
                $("#user_email_modal").val(rel.data.email);
                $("#user_account_modal").val(rel.data.account);
                $("#user_account_modal").prop("disabled", true);
                $(".user_account_same_email_div").hide();
                $("#user_account_same_email").prop("disabled", true);
                $(".system_admin_password_form_row").hide();
                $("#user_phone_modal").val(rel.data.phone);
                $("#user_role_modal").val(rel.data.roleId);

                $(".user-password-div").hide();

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

        });
        //#endregion

        //#region 使用者表單驗證
        $("#user-form").validate({
            rules: {
                user_name_modal: {
                    required: true,
                },
                user_email_modal: {
                    required: true,
                    email: true,
                },
                user_account_modal: {
                    required: true,
                },
            },
        });
        //#endregion

        //#region 儲存使用者
        function SaveUser() {

            if ($("#user-form").valid()) {
                showLoading();
                var url = "/User/SaveUser";

                @*var send_data = {
                    Id: selected_id,
                    CompanyId: $("#user_companyId_modal").val(),
                    Name: $("#user_name_modal").val(),
                    Email: $("#user_email_modal").val(),
                    Account: $("#user_account_modal").val(),
                    Phone: $("#user_phone_modal").val(),
                    RoleId: $("#user_role_modal").val()
                }*@

                var formData = new FormData();
                var logos = $('#user_logo_modal')[0].files;

                formData.append("Id", selected_id);
                formData.append("CompanyId", $("#user_companyId_modal").val());
                formData.append("Name", $("#user_name_modal").val());
                formData.append("Email", $("#user_email_modal").val());
                formData.append("Account", $("#user_account_modal").val());
                formData.append("Phone", $("#user_phone_modal").val());
                formData.append("RoleId", $("#user_role_modal").val());
                if (logos.length > 0) {
                    formData.append("LogoFile", logos[0])
                }

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

                    toast_ok(rel.msg);
                    $('#user-modal').modal('hide');

                    //更新當前剩餘可註冊使用者人數
                    UpdateRegisterNumber($("#user_companyId_modal").val());

                    userTable.ajax.reload();
                }, 'json');*@

                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (rel) {
                        if (rel.code != "0000") {
                            hideLoading();
                            toast_error(rel.msg);
                            return;
                        }

                        toast_ok(rel.msg);
                        $('#user-modal').modal('hide');

                        //更新當前剩餘可註冊使用者人數
                        UpdateRegisterNumber($("#user_companyId_modal").val());

                        userTable.ajax.reload();
                        hideLoading();
                    }
                });
            }
        }
        //#endregion

        //#region 預設密碼
        function DefaultPassword() {
            if ($("#user-form").valid()) {
                showLoading();
                var url = "/User/DefaultPassword";

                var formData = new FormData();
                formData.append("Id", selected_id);
                formData.append("CompanyId", $("#user_companyId_modal").val());
                formData.append("Name", $("#user_name_modal").val());
                formData.append("Email", $("#user_email_modal").val());
                formData.append("Account", $("#user_account_modal").val());

                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (rel) {
                        if (rel.code != "0000") {
                            hideLoading();
                            toast_error(rel.msg);
                            return;
                        }

                        toast_ok(rel.msg);
                        $('#user-modal').modal('hide');
                        hideLoading();
                    }
                });
            }
        }
        //#endregion

        //#region 刪除使用者
        $('#user_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 = "/User/DeleteOneUser/";
                        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);

                            //更新當前剩餘可註冊使用者人數
                            UpdateRegisterNumber($("#select_user_company_userManager_tab").val());

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

        //#region 更新公司當前剩餘註冊數量
        function UpdateRegisterNumber(companyId) {
            showLoading();
            var url = "/Company/GetRemainingRegisterNumber"

            var send_data = {
                Id: companyId
            }

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

                $("#remaining-number").html(rel.data);
                if (rel.data <= 0) {
                    $("#addUser-btn").hide();
                } else {
                    $("#addUser-btn").show();
                }
                hideLoading();
            }, 'json');
        }
        //#endregion

        //#region 使用者電站資訊
        function GetUserPowerStation(id) {
            var send_data = {
                Id: id
            }
            showLoading();
            var url_user_info = "/User/GetOneUser";

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

                $("#user-power-station-modal .modal-title").html(rel.data.companyName + "：" + rel.data.name);
                hideLoading();
            }, 'json');

            UpdateUserPowerStationTable(id, function (returnData) {
                if (returnData) {
                    $("#add-user-power-station").attr("data-user-id", id);

                    $("#user-power-station-modal").modal();
                }
            });
        }
        //#endregion

        //#region 刪除使用者電站
        $("#user-power-station-table").on("click", "button.del-user-power-station", 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 = "/User/DeleteOneUserPowerStation/";
                        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);
                            userTable.ajax.reload();
                            hideLoading();
                        }, 'json');
                    }
                });
        });

        //#endregion

        $("#user-power-station-table").on("click", "input.custom-control-input", function () {
            selected_id = $(this).attr('data-id');
            var clicktype = $(this).attr('id');
            var usetypename = clicktype.split("-");
            var usetype = 0;
            var check = 0;
            switch (usetypename[1])
            {
                case "emailDayReport": usetype = 0; break;
                case "emailMonthReport": usetype = 1; break;
                case "emailComplexReport": usetype = 2; break;
                case "emailException": usetype = 3; break;
            }
            if (this.checked) {
                check = 1;
            }
            else {
                check = 0;
            }

            showLoading();
            var url = "/User/DeleteOneGetEmail/";
            var send_data = {
                Id: selected_id,
                Type: usetype,
                Check: check
            }
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    hideLoading();
                    toast_error(rel.msg);
                    return;
                }
                toast_ok(rel.msg);
                hideLoading();
            }, 'json');
        })


        //#region 新增使用者管理電站
        function AddUserPowerStation(e) {

            var user_id = $(e).attr("data-user-id");
            showLoading();
            var url = "/User/GetUserCompanyPowerStation";
            var send_data = {
                Id: user_id
            }

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

                var companyPowerStationTable = $("#company-power-station-table");

                companyPowerStationTable.empty();
                rel.data.forEach(function (value, index) {
                    var str = "";
                    str += "<tr>";
                    str += "<td>" + value.code + "</td>";
                    str += "<td>" + value.powerStationName + "</td>";
                    str += "<td>" + value.escrowName + "</td>";
                    str += "<td>" + '<button type="button" class="btn btn-success btn-pills waves-effect waves-themed save-user-power-station" data-id="' + value.id + '" data-user-id="' + user_id + '">新增</button>' + "</td>";
                    str += "</tr>";

                    companyPowerStationTable.append(str);
                });

                $("#add-user-manager-station-modal").modal();
                userTable.ajax.reload();
                hideLoading();
            }, 'json');

        }
        //#endregion

        //#region 儲存使用者電站
        $("#company-power-station-table").on("click", "button.save-user-power-station", function () {
            selected_power_station_id = $(this).attr('data-id');
            selected_user_id = $(this).attr('data-user-id');
            var save_btn = $(this);

            //取得單一系統管理員
            showLoading();
            var url = "/User/SaveUserPowerStation/";
            var send_data = {
                PowerStationId: selected_power_station_id,
                UserId: selected_user_id
            }
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    hideLoading();
                    toast_error(rel.msg);
                    return;
                }

                save_btn.parents("tr").remove();
                toast_ok(rel.msg);

                UpdateUserPowerStationTable(selected_user_id);
                hideLoading();
            }, 'json');

        });

        function UpdateUserPowerStationTable(user_id, callback) {
            showLoading();
            var url = "/User/GetUserPowerStation";
            var send_data = {
                Id: user_id
            }

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

                userPowerStationTable = $("#user-power-station-table > tbody");

                userPowerStationTable.empty();
                rel.data.forEach(function (value, index) {
                    var str = "";
                    str += "<tr>";
                    str += "<td>" + value.code + "</td>";
                    str += "<td>" + value.powerStationName + "</td>";
                    str += "<td>" + value.escrowName + "</td>";
                    if (value.emailDayReport == 0) {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input' data-id='" + value.id + "' id = 'select-emailDayReport-" + value.code + "' ><label class='custom-control-label' for='select-emailDayReport-" + value.code +"'>接收</label></div>"+ "</td>";
                    }
                    else
                    {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input' data-id='" + value.id + "' id = 'select-emailDayReport-" + value.code + "' checked><label class='custom-control-label' for='select-emailDayReport-" + value.code + "'>接收</label></div>" + "</td>";
                    }
                    if (value.emailMonthReport == 0) {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input' data-id='" + value.id + "' id = 'select-emailMonthReport-" + value.code + "' ><label class='custom-control-label' for='select-emailMonthReport-" + value.code + "'>接收</label></div>" + "</td>";
                    }
                    else {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input' data-id='" + value.id + "' id = 'select-emailMonthReport-" + value.code + "' checked><label class='custom-control-label' for='select-emailMonthReport-" + value.code + "'>接收</label></div>" + "</td>";
                    }
                    if (value.emailComplexReport == 0) {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input' data-id='" + value.id + "' id = 'select-emailComplexReport-" + value.code + "' ><label class='custom-control-label' for='select-emailComplexReport-" + value.code + "'>接收</label></div>" + "</td>";
                    }
                    else {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input' data-id='" + value.id + "' id = 'select-emailComplexReport-" + value.code + "' checked><label class='custom-control-label' for='select-emailComplexReport-" + value.code + "'>接收</label></div>" + "</td>";
                    }
                    if (value.emailException == 0) {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input'data-id='" + value.id + "' id = 'select-emailException-" + value.code + "' ><label class='custom-control-label' for='select-emailException-" + value.code + "'>接收</label></div>" + "</td>";
                    }
                    else {
                        str += "<td>" + "<div class='custom-control custom-checkbox'><input type ='checkbox' class='custom-control-input' data-id='" + value.id + "' id = 'select-emailException-" + value.code + "' checked><label class='custom-control-label' for='select-emailException-" + value.code + "'>接收</label></div>" + "</td>";
                    }

                    str += "<td>" + '<button type="button" class="btn btn-danger btn-pills waves-effect waves-themed del-user-power-station" data-id="' + value.id + '">刪除</button>' + "</td>";
                    str += "</tr>";

                    userPowerStationTable.append(str);
                });

                hideLoading();
                userTable.ajax.reload();
                callback(true);
            }, 'json');
        }

        //#endregion

        //#endregion

        //#region 角色管理Tab

        //#region 搜尋角色列表
        function SearchRole() {
            roleTable.ajax.reload();
        }
        //#endregion

        //#region 新增公司角色
        function AddRole() {
            selected_role_id = 0;
            $("#role-modal .modal-title").html("人員基本資料 - 新增");
            $("#role-form").trigger("reset");
            $("#role_companyId_modal").val($("#select_company_role_roleManager_tab").val());

            $("#role-modal").modal();
        }
        //#endregion

        //#region 編輯公司角色
        $('#role_table').on("click", "button.edit-btn", function () {

            $("#role-modal .modal-title").html("角色資料 - 編輯");

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

            //取得單一公司角色資料
            showLoading();
            var url = "/Role/GetOneRole/";

            var send_data = {
                id: selected_role_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;
                }

                $("#role_companyId_modal").val(rel.data.companyId);
                $("#role_companyId_modal").prop("disabled", true);
                $("#role_name_modal").val(rel.data.name);

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

        });
        //#endregion

        //#region 公司角色表單驗證
        $("#role-form").validate({
            rules: {
                role_name_modal: {
                    role_companyId_modal: true,
                },
                role_name_modal: {
                    required: true,
                },
            },
        });
        //#endregion

        //#region 儲存公司角色
        function SaveRole() {

            if ($("#role-form").valid()) {
                showLoading();
                var url = "/Role/SaveRole";

                var send_data = {
                    Id: selected_role_id,
                    SelectedCompanyId: $("#role_companyId_modal").val(),
                    Name: $("#role_name_modal").val(),
                }

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

                    toast_ok(rel.msg);
                    $('#role-modal').modal('hide');

                    UpdateCompanyRoleSelectOption($("#role_companyId_modal").val())
                    roleTable.ajax.reload();
                    hideLoading();
                }, 'json');
            }
        }
        //#endregion

        //#region 刪除公司角色
        $('#role_table').on("click", "button.del-btn", function () {

            selected_role_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 = "/Role/DeleteOneRole/";

                        var send_data = {
                            Id: selected_role_id
                        }

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

                            toast_ok(rel.msg);
                            roleTable.ajax.reload();
                            hideLoading();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#endregion

        //#region 角色權限Tab

        //#region 搜尋角色權限列表

        $("#select_roleId_roleAuth_tab").change(function () {
            roleAuthTable.ajax.reload();
        });

        //#endregion

        //#region 新增角色權限
        function AddRoleAuth() {

            $("#select-all-company-auth").prop("checked", false);

            roleAuthNotJoinTable.ajax.reload();

            $("#role-auth-modal").modal();
        }
        //#endregion

        //#region 儲存角色權限
        function SaveRoleAuth() {

            var rows = roleAuthNotJoinTable.rows({ 'search': 'applied' }).nodes();
            //取得被選擇的角色權限
            var checkAuths = $("input[name='selectedAuthPage[]']:checked", rows).map(function () {
                return $(this).val();
            }).get();

            showLoading();
            var url = "/Role/SaveRoleAuth";

            var send_data = {
                SelectedRoleId: $("#select_roleId_roleAuth_tab").val(),
                CheckAuths: checkAuths
            }

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

                toast_ok(rel.msg);
                $("#role-auth-modal").modal('hide');

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

        //#region 刪除公司角色權限
        $('#roleAuth_table').on("click", "button.del-btn", function () {

            var row_id_authCode = $(this).parents('tr').attr('data-id-authCode');

            var split_arr = row_id_authCode.split("_");
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result)
                {
                    if (result.value) {
                        //取得單一系統管理員
                        showLoading();
                        var url = "/Role/DeleteOneRoleAuth/";

                        var send_data = {
                            RoleId: split_arr[0],
                            AuthCode: split_arr[1]
                        }

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

                            toast_ok(rel.msg);
                            roleAuthTable.ajax.reload();
                            hideLoading();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#endregion

        function UpdateCompanyRoleSelectOption(companyId) {
            showLoading();
            var url_company_role_select_option = "/Role/GetRoleSelectOptionList";

            send_data = {
                CompanyId: companyId
            }

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

                //#region 帳號管理Tab - 角色下拉式選單(搜尋)
                if (rel.data.length > 0) {
                    $("#select_company_role_userManager_tab").empty();
                    $("#select_company_role_userManager_tab").append($("<option />").val(0).text("全部"));

                    $.each(rel.data, function (index, val) {
                        $("#select_company_role_userManager_tab").append($("<option />").val(val.value).text(val.text));
                    });

                    //預設查詢第一個
                    $("#select_company_role_userManager_tab").val($("#select_company_role_userManager_tab option:first").val()).trigger('change');

                    //更新帳號管理DataTable
                    if (selected_tab == "#tab-user-manager") {
                        userTable.ajax.reload();
                    }
                } else {
                    $("#select_company_role_userManager_tab").empty();
                    $("#select_company_role_userManager_tab").append('<option value="0" disabled>請先新增角色</option>');

                    $("#select_company_role_userManager_tab").val($("#select_company_role_userManager_tab option:first").val()).trigger('change');
                }
                //#endregion

                //#region 帳號管理Tab - 人員基本資料新增/修改 modal
                if (rel.data.length > 0) {
                    $('#user_role_modal').empty();

                    $.each(rel.data, function (index, val) {
                        $("#user_role_modal").append($("<option />").val(val.value).text(val.text));
                    });

                    //預設查詢第一個
                    $("#user_role_modal").val($("#user_role_modal option:first").val()).trigger('change');
                } else {
                    $("#user_role_modal").empty();
                    $("#user_role_modal").append('<option value="0" disabled>請先新增角色</option>');

                    $("#user_role_modal").val($("#user_role_modal option:first").val()).trigger('change');
                }
                //#endregion

                //#region 角色權限Tab - 角色下拉是選單(搜尋)
                if (rel.data.length > 0) {
                    $("#select_roleId_roleAuth_tab").empty();

                    $.each(rel.data, function (index, val) {
                        $("#select_roleId_roleAuth_tab").append($("<option />").val(val.value).text(val.text));
                    });

                    //預設查詢第一個
                    $("#select_roleId_roleAuth_tab").val($("#select_roleId_roleAuth_tab option:first").val()).trigger('change');

                    //更新角色權限DataTable
                    if (selected_tab == "#tab-role-auth") {
                        roleAuthTable.ajax.reload();
                    }
                } else {
                    $("#select_roleId_roleAuth_tab").empty();
                    $("#select_roleId_roleAuth_tab").append('<option value="0" disabled>請先新增角色</option>');

                    $("#select_roleId_roleAuth_tab").val($("#select_roleId_roleAuth_tab option:first").val()).trigger('change');
                }
                //#endregion

                //更新角色管理DataTable
                if (selected_tab == "#tab-role-manager") {
                    roleTable.ajax.reload();
                }
                hideLoading();
            });
        }

    </script>
}
