
var tmpNestableObj;
var tmpNestableItem;
var tmpGroupNameItem;
$(document).ready(function () {
    deptList();

    $('#search_btn').on('click', function () {
        groupList();
    });

    $('#memberAddSaveBtn').on('click', function () {
        var userArray = [];
        var html = '';
        $.each($('input[type=checkbox][name="memberChkList[]"]:checked'), function () {
            var item = {
                user_uid: $(this).val(),
                user_name: $(this).parent().find('span').eq(0).text().trim()
            }
            userArray.push(item);
            html += optionItemHtml(item);
        });

        $('#nestableMember .dd-list').append(html);

        $('#memberModal').modal('toggle');
    });

    $('#groupNewModal').on('click', function () {
        $('#group_method').val('add');
        $('#dept_uid').val($('#dept_select').val());
        $('#nestableMember .dd-list').children().remove();
        //$('#nestableMember').nestable();
        $('#groupModal').modal('toggle');
    });

    $('#groupDialogSaveBtn').on('click', function () {
        var method = $('#group_method').val();
        var group_uid = $('#group_uid').val();
        var dept_uid = $('#dept_uid').val();
        var group_name = $('#group_name').val();
        var userArray = [];

        if (group_name == '') {
            alert('請輸入群組名稱!');
            return;
        }

        $.each($('#nestableMember .dd-list li'), function () {
            var tmp_uid = $(this).attr('data-user-uid');
            var tmp_name = $(this).find("[data-name='option_name']").text();
            var item = {
                user_uid: tmp_uid,
                user_name: tmp_name
            }
            userArray.push(item);
        });

        if (userArray.length == 0) {
            alert('群組內至少需要一名成員!');
            return;
        }

        var users_json = JSON.stringify(userArray);

        var formData = {
            dept_uid: dept_uid,
            group_name: group_name,
            users_json: users_json
        }

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

                    var obj = data.groups;

                    $.each(obj, function (index, item) {
                        $('#group_div').append(cardHtml(item));
                        $('#' + item.group_uid).nestable();

                        //$('#' + item.optionItem_uid).on('change', function () {
                        //    nestableChange(this);
                        //});
                    });

                    if (data.message != '') {
                        alert(data.message);
                    }

                    $('#groupModal').modal('toggle');
                } else {
                    alert(data.message);

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

    $('#groupMemberAddSaveBtn').on('click', function () {
        var userArray = [];
        var dept_uid = $('#client_group_dept_uid').val();
        var group_uid = $('#client_group_group_uid').val();

        $.each($('input[type=checkbox][name="memberChkList2[]"]:checked'), function () {
            var item = {
                user_uid: $(this).val(),
                user_name: $(this).parent().find('span').eq(0).text().trim()
            }
            userArray.push(item);
        });

        

        if (userArray.length == 0) {
            alert('沒有勾選欲加入群組的成員!');
            return;
        }

        var users_json = JSON.stringify(userArray);
        

        var formData = {
            dept_uid: dept_uid,
            group_uid: group_uid,
            users_json: users_json
        }

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



                    var obj = data.users;

                    $.each(obj, function (index, item) {
                        $('#' + group_uid + ' .dd-list').append(optionItemHtml(item));

                    });

                    if (data.message != '') {
                        alert(data.message);
                    }

                    $('#groupNewUserModal').modal('toggle');
                } else {
                    alert(data.message);

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

    $('#groupNameEditBtn').on('click', function () {
        var group_uid = $('#client_groupname_group_uid').val();
        var group_name = $('#clientGroupName').val().trim();

        if (group_name == '') {
            alert('群組名稱不得為空白!');
            return;
        }

        var formData = {
            group_uid: group_uid,
            group_name: group_name
        }

        $.ajax({
            url: "/AuthApi/editGroupName",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    tmpGroupNameItem.text(group_name);
                    $('#clientGroupNameEditModal').modal('toggle');
                } else {
                    alert(data.message);

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

    });
});


function newMemberClick() {
    var formData = {
        dept_uid: $('#dept_select').val()
    }

    $.ajax({
        url: "/AuthApi/noGroupUserList",
        type: "post",
        data: formData,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                $('#nogroup_memberlist').html('<div class="list-group-header"> 勾選要加入群組的成員 </div>');

                var obj = data.userList;
                var items = "";
                $.each(obj, function (i, item) {
                    var isExist = 'N';

                    $.each($('#nestableMember .dd-list li'), function () {
                        var tmp_uid = $(this).attr('data-user-uid');
                        if (tmp_uid == item.user_uid) {
                            isExist = 'Y';
                        }
                    });

                    if (isExist == 'N') {
                        items += '<label class="list-group-item custom-control custom-checkbox mb-0"><input id="chk_' + item.user_uid + '" name="memberChkList[]" type="checkbox"  value="' + item.user_uid + '" class="custom-control-input"> <span class="custom-control-label">' + item.user_name + '</span></label>';
                    }

                    
                });

                $('#nogroup_memberlist').append(items);

                $('#memberModal').modal('toggle');
            } else {
                alert(data.message);

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

function groupList() {
    var dept_uid = $('#dept_select').val();
    var formData = {
        dept_uid: dept_uid
    }
    $.ajax({
        url: "/AuthApi/groupList",
        type: "post",
        data: formData,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                $('#group_div').children().remove();

                var obj = data.groups;
                var items = "";
                $.each(obj, function (i, item) {
                    $('#group_div').append(cardHtml(item));
                    $('#' + item.group_uid).nestable();
                });
            } else {
                alert(data.message);

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


                    $("#dept_select").append($("<option>", {
                        value: item.dept_uid,
                        text: item.dept_name
                    }));


                });

                groupList();
            } 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 += '<li class="dd-item dd-nodrag" data-name="user_item" data-id="1" data-user-uid="'+ item.user_uid +'">';
    html += '    <div class="dd-handle">';
    html += '            <span class="dd-nodrag drag-indicator"></span>';
    html += '                       <div data-name="option_name"> ' + item.user_name + ' </div>';
    html += '                       <div class="dd-nodrag btn-group ml-auto">';
    html += '                                   <button type="button" class="btn btn-sm btn-secondary" onclick="delMemberBtnClick(this);"><i class="far fa-trash-alt"></i></button>';
    html += '                       </div>';
    html += '    </div>';
    html += '</li > ';
    return html;
}

function delMemberBtnClick(obj) {
    if (confirm('再次確認要移除此成員?')) {
        tmpNestableItem = $(obj).parent().parent().find("[data-name='option_name']");
        var optionItem_name = $(obj).parent().parent().find("[data-name='option_name']").text();
        var user_uid = $(obj).parent().parent().parent().attr("data-user-uid");
        var group_uid = $(obj).parent().parent().parent().parent().parent().attr("data-type");
        delItem = $(obj).parent().parent().parent();

        if (group_uid == '') {
            delItem.remove();
        } else {
            var formData = {
                dept_uid: $('#dept_select').val(),
                group_uid: group_uid,
                user_uid: user_uid
            }

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

                        delItem.remove();
                    } else {
                        alert(data.message);

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

function cardHtml(groupOption) {
    var html = "";
    html += "<!-- grid column -->";
    html += "<div class=\"col-lg-6\">";
    html += "    <!-- .card -->";
    html += "    <div class=\"card card-fluid\">";
    html += "        <div class=\"card-header border-bottom-0 btn-group\" data-group-uid=\"" + groupOption.group_uid + "\"> " + groupOption.group_name + " <div class=\"dd-nodrag btn-group ml-auto\"><button class=\"btn btn-sm btn-secondary\" type=\"button\" onclick=\"editGroupClick(this);\"><i class=\"fas fa-pencil-alt\"></i></button> <button class=\"btn btn-sm btn-secondary\" type=\"button\" onclick=\"delGroupClick(this);\"><i class=\"far fa-trash-alt\"></i></button></div></div><!-- .nestable -->";
    html += "        <div id=\"" + groupOption.group_uid + "\" class=\"dd\" data-toggle=\"sortable\" data-max-depth=\"1\" data-type=\"" + groupOption.group_uid + "\">";
    html += "            <!-- .dd-list -->";
    html += "            <ol class=\"dd-list\">";
    //html += "                <li></li>";

    $.each(groupOption.users, function (index, item) {
        html += optionItemHtml(item);
    });


    html += "            </ol><!-- /.dd-list -->";
    html += "        </div><!-- /.nestable -->";
    html += "        <!-- .card-footer -->";
    html += "        <div class=\"card-footer\">";
    html += "            <a href=\"javascript: void(0);\" onclick=\"addUserItem(this);\" data-type=\"" + groupOption.group_uid + "\" class=\"card-footer-item justify-content-start\"><span><i class=\"fa fa-plus-circle mr-1\"></i> 新增成員 </span></a>";
    html += "        </div><!-- /.card-footer -->";
    html += "    </div><!-- /.card -->";
    html += "</div><!-- /grid column -->";

    return html;
}

function editGroupClick(obj) {
    tmpGroupNameItem = $(obj).parent().parent();
    var group_name = $(obj).parent().parent().text().trim();
    var grid_obj = $(obj).parent().parent().parent().parent();
    var group_uid = $(obj).parent().parent().attr("data-group-uid");

    $('#client_groupname_group_uid').val(group_uid);
    $('#clientGroupName').val(group_name).trigger('change');

    $('#clientGroupNameEditModal').modal('toggle');
 
}

function delGroupClick(obj) {
    var group_name = $(obj).parent().parent().text().trim();
    var grid_obj = $(obj).parent().parent().parent().parent();
    var group_uid = $(obj).parent().parent().attr("data-group-uid");

    if (confirm('請確認是否要刪除此群組?')) {
        var formData = {
            group_uid: group_uid
        }

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

                    grid_obj.remove();
                } else {
                    alert(data.message);

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

function addUserItem(obj) {
    var group_uid = $(obj).attr("data-type");
    tmpNestableObj = $(obj).parent().parent().parent();

    $('#client_group_group_uid').val(group_uid);
    $('#client_group_dept_uid').val($('#dept_select').val());

    var formData = {
        dept_uid: $('#dept_select').val()
    }

    $.ajax({
        url: "/AuthApi/noGroupUserList",
        type: "post",
        data: formData,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                $('#lastgroup_memberlist').html('<div class="list-group-header"> 勾選要加入群組的成員 </div>');

                var obj = data.userList;
                var items = "";
                $.each(obj, function (i, item) {
                    var isExist = 'N';
                 
                    $.each($('#' + group_uid + ' .dd-list li'), function () {
                        var tmp_uid = $(this).attr('data-user-uid');
                        if (tmp_uid == item.user_uid) {
                            isExist = 'Y';
                        }
                    });

                    if (isExist == 'N') {
                        items += '<label class="list-group-item custom-control custom-checkbox mb-0"><input id="chk_' + item.user_uid + '" name="memberChkList2[]" type="checkbox"  value="' + item.user_uid + '" class="custom-control-input"> <span class="custom-control-label">' + item.user_name + '</span></label>';
                    }


                });

                $('#lastgroup_memberlist').append(items);

                $('#groupNewUserModal').modal('toggle');
            } else {
                alert(data.message);

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