@{
    ViewData["MainNum"] = "7";
    ViewData["SubNum"] = "1";
    ViewData["Title"] = "系統變數";
}
<ol class="breadcrumb page-breadcrumb">
    <li class="breadcrumb-item"><a href="javascript:void(0);">系統變數管理</a></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="row mb-5">
    <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="select_system_type">
                </select>
            </div>
        </div>
    </div>
</div>
<div class="row mb-3">
    <div class="col-12 d-flex justify-content-end">
        <a href="javascript:;" class="btn btn-success waves-effect waves-themed mb-3" onclick="AddVariable()"><span class="fal fa-plus mr-1"></span>新增系統變數</a>
    </div>
</div>
<div class="row">
    <div class="col-12">
        <!-- datatable start -->
        <table id="variable_table" class="table table-bordered table-hover m-0 text-center">
            <thead class="thead-themed">
                <tr>
                    <th>ID</th>
                    <th>system_type</th>
                    <th>system_key</th>
                    <th>system_value</th>
                    <th>備註</th>
                    <th>順序</th>
                    <th>關聯父層ID</th>
                    <th>功能</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal 系統變數 -->
<div class="modal fade" id="variable-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal" 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="variable-form" id="variable-form">
                    <div class="row">
                        <div class="form-group col-12">
                            <label class="form-label" for="variable_id_modal">ID</label>
                            <h6 id="variable_id"></h6>
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="variable_system_type_modal"><span class="text-danger">*</span>system_type</label>
                            <input type="text" id="variable_system_type_modal" class="form-control" name="variable_system_type_modal">
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="variable_system_key_modal"><span class="text-danger">*</span>system_key</label>
                            <input type="text" id="variable_system_key_modal" class="form-control" name="variable_system_key_modal">
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="variable_system_value_modal"><span class="text-danger">*</span>system_value</label>
                            <input type="text" id="variable_system_value_modal" class="form-control" name="variable_system_value_modal">
                        </div>
                        <div class="form-group col-12" hidden>
                            <label class="form-label" for="variable_picture_path">圖檔</label>
                            <input type="file" id="variable_picture_path" class="form-control" name="variable_picture_path" onchange="changeImage(this)">
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="variable_system_remark_modal">備註</label>
                            <textarea id="variable_system_remark_modal" class="form-control" name="variable_system_remark_modal"></textarea>
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="variable_system_priority_modal"><span class="text-danger">*</span>順序</label>
                            <input type="text" id="variable_system_priority_modal" class="form-control" name="variable_system_priority_modal">
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="variable_system_parent_id_modal"><span class="text-danger">*</span>關聯父層ID(無關聯,請填 0)</label>
                            <input type="text" id="variable_system_parent_id_modal" class="form-control" name="variable_system_parent_id_modal">
                        </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" id="save-variable-btn" onclick="SaveVariable()">確定</button>
            </div>
        </div>
    </div>
</div>
<!-- /.系統變數 -->

@section Scripts {
    <script>
        var variableTable;
        var variableFile = null;

        $(function () {
            GetSystemTypeList()

            //#region 系統變數 DataTable
            variableTable = $("#variable_table").DataTable({
                "columns": [
                    {
                        "data": "id"
                    },
                    {
                        "data": "system_type"
                    },
                    {
                        "data": "system_key"
                    },
                    {
                        "data": "system_value"
                    },
                    {
                        "data": "system_remark"
                    },
                    {
                        "data": "system_priority"
                    },
                    {
                        "data": "system_parent_id"
                    },
                    {
                        "data": null,
                        "render": function (data, type, row, meta) {
                            var name = row.system_type == "logo" ? "pic_edit_btn" : "edit_btn ";
                            return `<button name="`+ name +`" class="btn btn-primary edit-btn">修改</button> <button class="btn btn-danger del-btn">刪除</button>`;
                        }
                    }
                ],
                //"order": [[2, "desc"]],
                'createdRow': function (row, data, dataIndex) {
                    $(row).attr('data-id', data.id);
                },
                "ajax": {
                    "url": "/Variable/VariableInfoList",
                    "type": "POST",
                    "data": function (d) {
                        d.SelectedSystemType = $('#select_system_type').val();
                    },
                    "dataSrc": function (rel) {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                            return;
                        }

                        data = rel.data;

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

                        return data;
                    }
                }
            });
            //#endregion

            //#region 選擇system_type
            $("#select_system_type").change(function () {
                variableTable.ajax.reload();
            });
            //#endregion


            //#region 編輯系統變數
            $('#variable_table').on("click", "button.edit-btn", function () {

                $("#variable-modal .modal-title").html("系統變數 - 編輯");

                selected_id = $(this).parents('tr').attr('data-id');
                name = $(this).prop('name');
                //取得單一系統變數
                var url = "/Variable/GetOneVariable/";

                var send_data = {
                    id: selected_id
                }

                if (name == 'pic_edit_btn') {
                    $('#variable_picture_path').parent().attr('hidden', false);
                    $('#variable_system_type_modal').attr('disabled', true);
                    $('#variable_system_key_modal').attr('disabled', true);
                    $('#variable_system_value_modal').attr('disabled', true);
                }
                else {
                    $('#variable_picture_path').parent().attr('hidden', true);
                    $('#variable_system_type_modal').attr('disabled', false);
                    $('#variable_system_key_modal').attr('disabled', false);
                    $('#variable_system_value_modal').attr('disabled', false);
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    
                    $("#variable_id").html(rel.data.id);
                    $("#variable_system_type_modal").val(rel.data.system_type);
                    $("#variable_system_key_modal").val(rel.data.system_key);
                    $("#variable_system_value_modal").val(rel.data.system_value);
                    $("#variable_system_remark_modal").val(rel.data.system_remark);
                    $("#variable_system_priority_modal").val(rel.data.system_priority);
                    $("#variable_system_parent_id_modal").val(rel.data.system_parent_id);

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

            });
            //#endregion

            //#region 刪除系統變數
            $('#variable_table').on("click", "button.del-btn", function () {
                selected_id = $(this).parents('tr').attr('data-id');
                Swal.fire(
                    {
                        title: "刪除",
                        html: "你確定是否刪除此筆資料?<br>請確定該變數未被使用,否則可能導致系統錯誤。",
                        type: "warning",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: "是",
                        cancelButtonText: "否"
                    }).then(function (result) {
                        if (result.value) {
                            var url = "/Variable/DeleteOneVariable";
                            var send_data = {
                                id: selected_id
                            }
                            $.post(url, send_data, function (rel) {
                                if (rel.code != "0000") {
                                    toast_error(rel.msg);
                                    return;
                                }

                                toast_ok(rel.msg);

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

        //#region 取得SystemType列表
        function GetSystemTypeList() {
            var url = "/Variable/SystemTypeList";
            $.post(url, null, function (rel) {
                $("#select_system_type").empty();
                $('#select_system_type').append($("<option />").val("").text("全部"))
                $.each(rel.data, function (index, val) {
                    $('#select_system_type').append($("<option />").val(val.value).text(val.name));
                });
            }, "json");
        }
        //#endregion

        //#region 新增系統變數
        function AddVariable() {
            selected_id = "0";
            VariableValidate.resetForm();
            $("#variable-modal .modal-title").html("系統變數 - 新增");
            $("#variable-form").trigger("reset");

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

        //#region 系統變數表單驗證
        var VariableValidate = $("#variable-form").validate({
            rules: {
                variable_system_type_modal: {
                    required: true,
                },
                variable_system_key_modal: {
                    required: true,
                },
                variable_system_value_modal: {
                    required: true,
                },
                variable_system_priority_modal: {
                    required: true,
                },
                variable_system_parent_id_modal: {
                    required: true,
                }
            },
        });
        //#endregion

        //#region 儲存系統變數
        function SaveVariable() {
            if ($("#variable-form").valid()) {

                $("#save-variable-btn").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>').attr("disabled", true);

                var url = "/Variable/SaveVariable";
                var formData = new FormData();
                formData.append("Id", selected_id);
                formData.append("System_type", $("#variable_system_type_modal").val());
                formData.append("System_key", $("#variable_system_key_modal").val());
                formData.append("system_value", $("#variable_system_value_modal").val());
                formData.append("system_remark", $("#variable_system_remark_modal").val());
                formData.append("system_priority", $("#variable_system_priority_modal").val());
                formData.append("system_parent_id", $("#variable_system_parent_id_modal").val());

                if (variableFile != null)
                {
                    formData.append("file", variableFile);
                    formData.append("extName", variableFile.name.split('.')[1]);
                }

                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (rel) {
                        $("#save-variable-btn").html('確定').attr("disabled", false);
                        if (rel.code != "0000") {
                            if (rel.code == "9998") {
                                toast_warning(rel.msg);
                                return;
                            }
                            toast_error(rel.msg);
                            return;
                        }
                        toast_ok(rel.msg);
                        $('#variable-modal').modal('hide');
                        variableTable.ajax.reload();

                        variableFile = null;
                        GetSystemTypeList()
                    },
                    fail: function (xhr, status, error) {
                        $("#save-variable-btn").html('確定').attr("disabled", false);
                    }
                });
            }
        }
        //#endregion

        //#region weblogo
        function changeImage(input) {
            $(`#variable_picture_path`).attr("data-src", window.URL.createObjectURL(input.files[0]));
            variableFile = input.files[0];
            console.log(variableFile);
            $('#variable_system_key_modal').val(variableFile.name.split('.')[0]);
            $('#variable_system_value_modal').val(variableFile.name);
        }
        //#endregion
    </script>
}