@{
    ViewData["MainNum"] = "7";
    ViewData["SubNum"] = "1";
    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-hdr">
                <div class="panel-hdr color-warning-800">
                    <h2></h2>
                </div>
                <div class="panel-toolbar ml-2">
                    <div class="d-flex position-relative ml-auto" style="max-width: 8rem;">
                        <div class="form-group">
                            <select class="form-control" id="company_select">
                                <option value="0" selected>全部</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="panel-toolbar ml-2">
                    <div class="d-flex position-relative ml-auto" style="max-width: 8rem;">
                        <input type="text" id="company_name" class="form-control form-control-sm" placeholder="名稱" autocomplete="off">
                    </div>
                </div>
                <div class="panel-toolbar ml-2">
                    <div class="d-flex position-relative ml-auto" style="max-width: 8rem;">
                        <input type="text" id="company_phone" class="form-control form-control-sm" placeholder="電話" autocomplete="off">
                    </div>
                </div>
                <div class="panel-toolbar ml-2">
                    <div class="d-flex position-relative ml-auto" style="max-width: 8rem;">
                        <input type="text" id="company_taxIDNumber" class="form-control form-control-sm" placeholder="統編" autocomplete="off">
                    </div>
                </div>
                <button type="button" class="btn btn-primary btn-sm waves-effect waves-themed ml-2" onclick="SearchCompany()">搜尋</button>

            </div>
            <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="AddCompany()">
                            <span class="fal fa-plus mr-1"></span>
                            新增
                        </button>
                    }
                    <div class="frame-wrap">
                        <table id="company_table" class="table table-bordered table-hover m-0 text-center">
                            <thead class="thead-themed">
                                <tr>
                                    <th>#</th>
                                    <th>logo</th>
                                    <th>名稱</th>
                                    <th>統編</th>
                                    <th>電話</th>
                                    <th>地址</th>
                                    <th>註冊/上限人數</th>
                                    <th>電站數量</th>
                                    <th>建立時間</th>
                                    <th>功能</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!--公司資料-->
<div class="modal fade" id="company-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="company-form" id="company-form" enctype="multipart/form-data">
                    <div class="row">
                        <div class="form-group col-lg-6">
                            <label class="form-label" for="company_name_modal"><span class="text-danger">*</span>名稱</label>
                            <input type="text" id="company_name_modal" name="company_name_modal" class="form-control">
                        </div>

                        <div class="form-group col-lg-6">
                            <label class="form-label" for="company_taxIDNumber_modal"><span class="text-danger">*</span>統編</label>
                            <input type="text" id="company_taxIDNumber_modal" name="company_taxIDNumber_modal" class="form-control">
                        </div>

                        <div class="form-group col-lg-6">
                            <label class="form-label" for="company_phone_modal">電話</label>
                            <input type="text" id="company_phone_modal" name="company_phone_modal" class="form-control">
                        </div>

                        <div class="form-group col-lg-6">
                            <label class="form-label" for="company_address_modal">地址</label>
                            <input type="text" id="company_address_modal" name="company_address_modal" class="form-control">
                        </div>

                        <div class="form-group col-lg-6">
                            <label class="form-label" for="company_registerUpperLimit_modal">註冊上限人數</label>
                            <input type="number" id="company_registerUpperLimit_modal" name="company_registerUpperLimit_modal" class="form-control" min="0" oninput="value=value.replace(/\D+/g, '')">
                        </div>

                        <div class="form-group col-lg-6">
                            <label class="form-label" for="company_logo_modal">公司Logo(建議尺寸 200 * 40px)</label>
                            <input type="file" id="company_logo_modal" name="company_logo_modal" class="form-control" accept="image/*">
                        </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="SaveComapny()">確定</button>
            </div>
        </div>
    </div>
</div>
<!--/.公司資料-->
<!-- 公司權限池 -->
<div class="modal fade" id="company-auth-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">
                <table id="company_auth_table" class="table table-bordered text-center">
                    <thead class="thead-themed">
                        <tr>
                            <th>
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="select-all-company-auth">
                                    <label class="custom-control-label" for="select-all-company-auth">全選</label>
                                </div>
                            </th>
                            @*<th>編號</th>*@
                            <th>功能大項</th>
                            <th>功能名稱</th>
                            <th>功能細項名稱</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="SaveComapnyAuth()">確定</button>
            </div>
        </div>
    </div>
</div>
<!-- /.公司權限池 -->

@section Scripts{
    <script>
        var companyTable; var companyAuthTable;
        var selected_id = 0;

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

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

        $(function () {
            //#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;
                }

                $("#company_select").empty();
                $("#company_select").append($("<option />").val(0).text("全部"));

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

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

            //#region 公司管理列表 DataTable
            companyTable = $("#company_table").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                "order": [[8, "desc"]],
                "columns": [{
                    "data": "id"
                }, {
                    "data": "logo"
                }, {
                    "data": "name"
                }, {
                    "data": "taxIDNumber"
                }, {
                    "data": "phone"
                }, {
                    "data": "address"
                }, {
                    "data": "registerRatio"
                }, {
                    "data": "spStationAmount"
                }, {
                    "data": "createdAt"
                }, {
                    "data": "function",
                }],
                "columnDefs": [{
                    'targets': 1,
                    'searchable': false,
                    'orderable': false,
                    'className': 'dt-body-center',
                    'render': function (data, type, full, meta) {
                        return '<img src="' + data + '?v=' + Date.now() + '" width="200px" height="40px">';
                    }
                }, {
                    'targets': 8,
                    'visible': false
                }],
                "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": "/Company/CompanyList",
                    "type": "POST",
                    "data": function (d) {
                        d.SelectedCompanyId = $('#system_admin_account').val();
                        d.Name = $('#company_name').val();
                        d.Phone = $('#company_phone').val();
                        d.TaxIDNumber = $('#company_taxIDNumber').val();
                    },
                    "dataSrc": function (rel) {
                        if (rel.data.code == "9999") {
                            toast_error(rel.data.msg);
                            return;
                        }

                        data = rel.data.data;

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

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

            //#region 公司權限池列表 DataTable
            companyAuthTable = $("#company_auth_table").DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                // "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 = "";
                        var disabled = "";
                        check_html += '<div class="custom-control custom-checkbox">';
                        if (full.checkAuth > 0) {
                            if (data == 'A') {
                                disabled = "disabled";
                            }
                            check_html += '<input type="checkbox" class="custom-control-input" name="selectedAuthPage[]" id="auth-page-' + data + '" value="' + data + '" checked ' + disabled + ' /> ';
                        } else {
                            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-authCode', data.authCode);
                },
                "ajax": {
                    "url": "/Company/GetCompanyAuthByCompanyId",
                    "type": "POST",
                    "data": function (d) {
                        d.Id = selected_id;
                    },
                    "dataSrc": function (rel) {
                        if (rel.data.code == "9999") {
                            toast_error(rel.data.msg);
                            return;
                        }

                        data = rel.data.data;

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

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

            //#region 公司權限池全選
            $("#select-all-company-auth").change(function () {

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

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

        //#region 搜尋公司列表
        function SearchCompany() {
            companyTable.ajax.reload();
        }
        //#endregion

        //#region 新增公司基本資料
        function AddCompany() {

            selected_id = 0;
            $("#company-modal .modal-title").html("公司基本資料 - 新增");
            $("#company-form").trigger("reset");

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

        //#region 編輯公司資料
        $('#company_table').on("click", "button.edit-btn", function () {

            $("#company-modal .modal-title").html("公司基本資料 - 編輯");

            selected_id = $(this).parents('tr').attr('data-id');
            showLoading();
            //取得單一公司基本資料
            var url = "/Company/GetOneCompany/";

            var send_data = {
                id: selected_id
            }

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

                $("#company_name_modal").val(rel.data.name);
                $("#company_taxIDNumber_modal").val(rel.data.taxIDNumber);
                $("#company_phone_modal").val(rel.data.phone);
                $("#company_address_modal").val(rel.data.address);
                $("#company_registerUpperLimit_modal").val(rel.data.registerUpperLimit);

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

        });
        //#endregion

        //#region 公司資料表單驗證
        $("#company-form").validate({
            rules: {
                company_name_modal: {
                    required: true,
                },
                company_taxIDNumber_modal: {
                    required: true,
                    maxlength: 8,
                },
            },
        });
        //#endregion

        //#region 儲存公司資料
        function SaveComapny() {

            if ($("#company-form").valid()) {
                showLoading();
                var url = "/Company/SaveCompany";

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

                formData.append("Id", selected_id);
                formData.append("Name", $("#company_name_modal").val());
                formData.append("TaxIDNumber", $("#company_taxIDNumber_modal").val());
                formData.append("Phone", $("#company_phone_modal").val());
                formData.append("Address", $("#company_address_modal").val());
                formData.append("RegisterUpperLimit", $("#company_registerUpperLimit_modal").val());
                if (logos.length > 0) {
                    formData.append("LogoFile", logos[0])
                }

                $.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;
                        }
                        hideLoading();
                        toast_ok(rel.msg);
                        $('#company-modal').modal('hide');

                        companyTable.ajax.reload();
                    }
                });
            }
        }
        //#endregion

        //#region 刪除公司
        $('#company_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 = "/Company/DeleteOneCompany/";
                        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;
                            }
                            hideLoading();
                            toast_ok(rel.msg);
                            companyTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 編輯公司權限池
        $('#company_table').on("click", "button.company-auth-btn", function () {

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

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

            companyAuthTable.ajax.reload();

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

        //#region 儲存公司權限池
        function SaveComapnyAuth() {

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

            showLoading();
            var url = "/Company/SaveCompanyAuth";

            var send_data = {
                SelectedCompanyId: selected_id,
                CheckAuths: checkAuths
            }

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

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

                companyAuthTable.ajax.reload();
                hideLoading();
            }, 'json');
        }
            //#endregion
    </script>
}