function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

// DataTables Demo
// =============================================================
var DataTablesResponsive = /*#__PURE__*/function () {
    function DataTablesResponsive() {
        _classCallCheck(this, DataTablesResponsive);

        this.init();
    }

    _createClass(DataTablesResponsive, [{
        key: "init",
        value: function init() {
            // event handlers
            this.table = this.table();
        }
    }, {
        key: "table",
        value: function table() {
            $('#dt-responsive').DataTable({
                ajax: {
                    url: '/AuthApi/userList',
                    type: 'POST',                  
                    dataSrc: 'userList'
                },
                rowId: 'user_uid',
                responsive: true,
                dom: "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>\n        <'table-responsive'tr>\n        <'row align-items-center'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 d-flex justify-content-end'p>>",
                language: {
                    paginate: {
                        previous: '<i class="fa fa-lg fa-angle-left"></i>',
                        next: '<i class="fa fa-lg fa-angle-right"></i>'
                    }
                },
                columns: [{
                    data: 'user_name'
                }, {
                    data: 'user_id'
                }, {
                    data: 'user_type'
                }, {
                    data: 'user_perm'
                }, {
                    data: 'user_lastlogintime'
                }, {
                    data: 'user_uid'
                    }],
                columnDefs: [
                    {
                        targets: 2,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            if (row.user_type == 'N') {
                                return 'E白板帳號';
                            } else {
                                return '自建帳號';
                            }
                        }
                    },
                    {
                        targets: 3,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            if (row.user_perm == 'user') {
                                return '一般使用者';
                            } else {
                                return '系統使用者';
                            }
                        }
                    }, {
                        targets: 5,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            return "<a class=\"btn btn-sm btn-icon btn-secondary\" data-method=\"edit\" href=\"javascript: void(0);\" data-uid=\"".concat(row.user_uid, "\"><i class=\"fa fa-pencil-alt\"></i></a>\n          <a class=\"btn btn-sm btn-icon btn-secondary\" data-method=\"del\" href=\"javascript: void(0);\"  data-uid=\"").concat(row.user_uid, "\"><i class=\"far fa-trash-alt\"></i></a>");
                        }
                    }

                ],
                initComplete: function () {
                    userTable = $('#dt-responsive').dataTable();

                    $('#dt-responsive').on('click', 'a', function () {
                        buttonClick(this);
                    });

                    $('#dt-responsive').on('click', 'input[name="selectedRow[]"]', function () {
                        checkboxClick(this);
                    });
                }
            });
        }
    }]);

    return DataTablesResponsive;
}();

/**
 * Keep in mind that your scripts may not always be executed after the theme is completely ready,
 * you might need to observe the `theme:load` event to make sure your scripts are executed after the theme is ready.
 */
var userTable;
var userRowID;
var userRowPos;
$(document).on('theme:init', function () {
    new DataTablesResponsive();
});
function buttonClick(obj) {

    var type = obj.getAttribute('data-method');
    var uid = obj.getAttribute('data-uid');
    
 
    userRowID = $('#' + uid);

    userRowPos = userTable.fnGetPosition($('#' + uid)[0]);

    if (type == "edit") {
        var formData = {
            method: 'get',
            user_uid: uid
        }

        $.ajax({
            url: "/AuthApi/addEditGetUser",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.user;

                    $("#method").val('edit');
                    $("#user_uid").val(obj.user_uid);
                    $("#user_type").val(obj.user_type).trigger('change');
                    $("#user_perm").val(obj.user_perm).trigger('change');
                    $("#user_engName").val(obj.user_engName).trigger('change');
                    if (obj.user_type == "N") {
                        $("#user_elabName").val(obj.user_id).trigger('change');
                        
                    } else {
                        $("#user_name").val(obj.user_name).trigger('change');
                        $("#user_id").val(obj.user_id).trigger('change');
                        $("#user_email").val(obj.user_email).trigger('change');
                    }

                    $("input:checkbox[name='dept[]']").prop('checked', false);

                    $.each(obj.Depts, function (key, value) {
                        $("input:checkbox[name='dept[]'][value='" + value.dept_uid + "']").prop('checked', true);
                    });

                    
                    modalStatus("Y");
                    $('#clientNewModal').modal('toggle');
                } else {
                    alert(data.message);

                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });


    }

    if (type == "del") {
        if (confirm('確定刪除此筆資料?')) {
            var formData = {
                method: 'del',
                user_uid: uid
            }

            $.ajax({
                url: "/AuthApi/addEditGetUser",
                type: "post",
                data: formData,
                success: function (data, textStatus, jqXHR) {
                    if (data.ret == "yes") {
                        var row = userTable.api().row(userRowID).remove().draw(false);
                        alert('刪除成功');
                     
                    } else {
                        alert(data.message);

                        if (data.err_code == "99999") {
                            location.href = "/Root/Login";
                        }
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('網路或伺服器發生錯誤，請稍後重試!');
                }
            });
        }
    }
}

function modalStatus(readonly) {
    if (readonly == "Y") {
        $("#user_type").prop("disabled", true);
        $("#user_elabName").prop("disabled", true);
        $("#user_id").prop("readonly", true);
    } else {
        $("#user_type").prop("disabled", false);
        $("#user_elabName").prop("disabled", false);
        $("#user_id").prop("readonly", false);
    }
}

$(document).ready(function () {
   
    loadElabList();
    userTypeStatus();

    loadDept();

    $("#saveBtn").on('click', function () {
        var user_uid = $("#user_uid").val();
        var user_type = $("#user_type").val();
        var method = $("#method").val();
        var user_id = $("#user_id").val();
        var user_elabName = $("#user_elabName").val();
        var user_name = $("#user_name").val();
        var user_engName = $("#user_engName").val();
        var user_pwd = $("#user_pwd").val();
        var user_chkpwd = $("#user_chkpwd").val();
        var user_email = $("#user_email").val();
        var user_perm = $("#user_perm").val();
        var user_depts = "";

        $.each($('input[name="dept[]"]:checked'), function () {
            user_depts = user_depts + $(this).val() + ",";
        });

        var err_msg = "";

        if (user_type == "N") {
            if ($("#user_elabName").val() == "") {
                err_msg += "請選擇要加入系統用戶的E白板帳號!\n";
            }
        } else {
            if (user_id == "") {
                err_msg += "請輸入帳號!\n";
            }

            if (user_name == "") {
                err_msg += "請輸入使用者名稱!\n";
            }

            if (user_email.isEmail == false) {
                err_msg += "請輸入正確的Email!\n";
            }

            if (method == "add") {
                if (user_pwd == "") {
                    err_msg += "請輸入密碼!\n";
                }
            }

            if (user_pwd != user_chkpwd) {
                err_msg += "請確認兩次密碼是否輸入正確!\n";
            }

            if (method == "edit" && user_pwd == "") {
                user_pwd = "";
            } else {
                user_pwd = sha256_digest(user_pwd);
            }
        }

        if (user_perm == "") {
            err_msg += "請選擇此使用者的使用權限!\n";
        }

        if (user_depts == "") {
            err_msg += "請勾選所屬單位!\n";
        }

        if (err_msg != "") {
            alert(err_msg);
            return;
        }

        var formData = {
            user_uid: user_uid,
            user_type: user_type,
            method: method,
            user_id: user_id,
            user_elabName: user_elabName,
            user_name: user_name,
            user_engName: user_engName,
            user_email: user_email,
            user_pwd: user_pwd,
            user_perm: user_perm,
            user_depts: user_depts
        }

        $.ajax({
            url: "/AuthApi/AddEditGetUser",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.user;

                    if (method == "add") {
                        userTable.fnAddData(obj);
                        alert("新增完成");

                    }

                    if (method == "edit") { 
                        userTable.fnUpdate(obj, userRowPos);
                        alert("修改完成");
                    }

                    $('#clientNewModal').modal('toggle');
                } else {
                    alert(data.message);
                  
                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {

                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });

    });

    $("#user_type").on('change', function () {
        userTypeStatus();
    });

    $('#userNewModal').on('click', function () {
        $('#method').val('add');
        $("input:checkbox[name='dept[]']").prop('checked', false);
        modalStatus("N");
        $('#clientNewModal').modal('toggle');
    });

    function userTypeStatus() {
        var user_type = $("#user_type").val();

        if (user_type == "Y") {
            $("#user_elab_div").hide();
            $("#user_name_div").show();
            $("#user_engname_div").show();
            $("#user_id_div").show();
            $("#user_pwd_div").show();
            $("#user_chkpwd_div").show();
            $("#user_email_div").show();
        } else {
            $("#user_elab_div").show();
            $("#user_name_div").hide();
            $("#user_engname_div").show();
            $("#user_id_div").hide();
            $("#user_pwd_div").hide();
            $("#user_chkpwd_div").hide();
            $("#user_email_div").hide();
        }
    }

    function loadElabList() {
        $("#user_elabName")
            .find("option")
            .remove()
            .end()
            .append("<option value=\"\"> Choose... </option>");


        $.ajax({
            url: "/AuthApi/elab_UserList",
            type: "post",
            data: {},
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    $.each(data.userList, function (i, item) {
                        $("#user_elabName").append($("<option>", {
                            value: item.userid,
                            text: item.username + " (" + item.mail +")"
                        }));
                    });
                } else {
                    alert(data.message);

                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    }
});

function loadDept() {
    $.ajax({
        url: "/AuthApi/authDeptList",
        type: "post",
        data: null,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.depts;
                var items = "";
                $.each(obj, function (i, item) {
                    

                    items += optionItemHtml(item);

              
                });

                items = "<label class=\"d-block\">所屬單位</label>" + items;

                $('#user_dept_div').children().first().html(items);
            } else {
                alert(data.message);

                if (data.err_code == "99999") {
                    location.href = "/Root/Login";
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('網路或伺服器發生錯誤，請稍後重試!');
        }
    });
}

function optionItemHtml(item) {
    var html = "";

    html += "<div class=\"custom-control custom-control-inline custom-checkbox\">";
    html += "   <input type=\"checkbox\" class=\"custom-control-input\" name=\"dept[]\" value=\"" + item.dept_uid + "\" id=\"" + item.dept_uid + "\"> <label class=\"custom-control-label\" for=\"" + item.dept_uid + "\">" + item.dept_name + "</label>";
    html += "</div>";

    return html;
}