var mainTable;
var mainRowID;
var mainPos;
var mediaTr;

$(document).ready(function () {
    loadTagsInput();
    loadDataTable();
    initSummernote();
    initMainPhotoUpload();
    initSubPhotoUpload();

    $('#newsSaveBtn').on('click', function () {
        var method = $('#method').val();
        var news_uid = $('#news_uid').val();
        var news_title = $('#news_title').val();
        var news_subtitle = $('#news_subtitle').val();
        var news_content = $('#summernote').summernote('code');

        var src = $('#fileupload-avatar').parent().children('img').prop('src');
        var origin = location.origin;
        src = src.replace(origin, '');

        var news_mainPhoto = src;
        var news_date = $('#news_date').val();
        var tags = $('#news_tags').val();
        var news_tags = "";
        var photoArray = [];
        var photoArrayJson = "";

        $.each(tags, function (key, value) {
            news_tags = news_tags + value + ",";
        });

        $('#media_table tbody tr').each(function () {
            var tmpphoto_path = $(this).find('td').eq(0).find('img').prop('src').trim();
            tmpphoto_path = tmpphoto_path.replace(origin, '');

            var item = {
                photo_title: $(this).find('td').eq(1).text().trim(),
                photo_path: tmpphoto_path.trim()
            }

            photoArray.push(item);
        });

        var err_msg = "";

        if (news_mainPhoto == '/BackEnd/assets/images/avatars/unknown-profile.jpg') {
            err_msg += "請選擇要顯示的圖片!\n";
        }

        if (news_title == "") {
            err_msg += "請輸入標題!\n";
        }

        if (news_subtitle == "") {
            err_msg += "請輸入副標題!\n";
        }

        if (news_content == "") {
            err_msg += "請輸入內容!\n";
        }

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

        mainTable = $('#dt-responsive').dataTable();

        var formData = {
            method: method,
            news_uid: news_uid,
            news_title: news_title,
            news_subtitle: news_subtitle,
            news_content: news_content,
            news_mainPhoto: news_mainPhoto,
            news_date: news_date,
            news_tags: news_tags,
            photoArrayJson: JSON.stringify(photoArray)
        }

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

                    if (method == "add") {
                        mainTable.fnAddData(obj);
                    }

                    if (method == "edit") {
                        mainTable.fnUpdate(obj, mainPos);
                    }

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

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

    $('#socialNewBtn').on('click', function () {
        //var src = $('#fileupload-avatar').parent().children('img').prop('src');
        //var origin = location.origin;
        //src = src.replace(origin, '');
        //alert(src);
        $('#fileupload-subPhoto').parent().children('img').prop('src', '/BackEnd/assets/images/avatars/unknown-profile.jpg');

        $('#photo_method').val('add');
        $('#socialItemModal').modal('toggle');
    });

    $('#newsNewModal').on('click', function () {

        //loadTagsInput();

        cleanModalData();

        $('#summernote').summernote('code', '');

        $('#method').val('add');

        $('#clientNewModal').modal('toggle');

        
    });

    $('#optionItemDialogSaveBtn').on('click', function () {
        var method = $('#photo_method').val();
        var news_uid = $("#news_uid").val();
        var photo_uid = $('#photo_uid').val();
        var photo_title = $('#photo_title').val();
        var sub_photo = "";

        var src = $('#fileupload-subPhoto').parent().children('img').prop('src');
        var origin = location.origin;
        src = src.replace(origin, '');
        sub_photo = src;

        var err_msg = "";

        if (photo_title == "") {
            err_msg += "請輸入圖片說明\n";
        }

        if (src == '/BackEnd/assets/images/avatars/unknown-profile.jpg') {
            err_msg += "請選擇要顯示的圖片!\n";
        }

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

        if (method == "add") {
            var ret = '';
            ret += '<div class="user-avatar user-avatar-xxl">';
            ret += '    <img src="' + sub_photo + '" alt="">';
            ret += '</div>';

            var trHtml = "";
            trHtml += '<tr>';
            trHtml += '     <td class="align-middle">  ' + ret + ' </td>';

            trHtml += '     <td class="align-middle"> ' + photo_title + ' </td>';
            trHtml += '     <td class="align-middle text-right">';
            trHtml += '         <button type="button" data-uid="" media-uid="' + photo_uid + '" data-method="edit" onclick="buttonClick(this);" class="btn btn-sm btn-icon btn-secondary" data-toggle="modal" data-target="#clientContactEditModal"><i class="fa fa-pencil-alt"></i> <span class="sr-only">Edit</span></button>';
            trHtml += '         <button type="button" data-uid="" media-uid="' + photo_uid + '" data-method="del" onclick="buttonClick(this);" class="btn btn-sm btn-icon btn-secondary"><i class="far fa-trash-alt"></i> <span class="sr-only">Remove</span></button>';
            trHtml += '     </td>';
            trHtml += '</tr>';

            $('#media_table tbody').append(trHtml);
            $('#socialItemModal').modal('toggle');

        }

        if (method == "edit") {
            mediaTr.find('td').eq(0).find('img').prop('src', sub_photo);
            mediaTr.find('td').eq(1).text(photo_title);
            
            

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

    function loadDataTable() {
        var dataTables = {
            init: function init() {

                this.bindUIActions();
            },
            bindUIActions: function bindUIActions() {

                // event handlers
                this.table = this.handleDataTables();

                // add buttons
                //this.table.buttons().container().appendTo('#dt-buttons').unwrap();
            },
            handleDataTables: function handleDataTables() {
                //$('#myTable').append("<tfoot><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr></tfoot>");
                return $('#dt-responsive').DataTable({
                    dom: '<\'text-muted\'Bif>\n        <\'table-responsive\'trl>\n        <\'mt-4\'p>',
                    lengthChange: true,
                    lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
                    pageLength: 25,
                    buttons: [
                        //{
                        //    text: '休假設定',
                        //    action: function (e, dt, node, config) {
                        //        vacationBtnFun();

                        //    }
                        //},
                        //'excelHtml5'
                    ],
                    language: {
                        paginate: {
                            previous: '<i class="fa fa-lg fa-angle-left"></i>',
                            next: '<i class="fa fa-lg fa-angle-right"></i>'
                        },
                        buttons: {
                            copyTitle: 'Data copied',
                            copyKeys: 'Use your keyboard or menu to select the copy command'
                        }
                    },
                    autoWidth: false,
                    ajax: {
                        url: '/BackEndApi/newsList',
                        type: 'POST',
                        data: function (d) {
                            Object.assign(d, {
                                bar_area: $('#bar_area').val(),
                                is_lottery: $('#isLottery').val()
                            });

                            return d;
                        },
                        dataSrc: 'newsList'
                    },
                    rowId: 'news_uid',
                    deferRender: true,
                    initComplete: function () {
                        $('#dt-responsive').on('click', 'a', function () {
                            buttonClick2(this);
                        });

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

                        $('#dt-responsive').on('click', 'input[name="selectedRow[]"]', function () {
                            checkboxClick(this);
                        });
                    },
                    order: [[1, 'desc']],
                    info: true,
                    search: "搜尋:",
                    searching: true,
                    columns: [{ data: 'news_mainPhoto', className: 'align-middle', orderable: false, searchable: false },
                        { data: 'news_date', className: 'align-middle text-left', orderable: true, searchable: true },
                        { data: 'news_title', className: 'align-middle text-left', orderable: true, searchable: true },
                    { data: 'news_uid', className: 'align-middle text-left', orderable: false, searchable: true }],
                    columnDefs: [
                        {
                            targets: 0,
                            className: 'align-middle text-center',
                            orderable: false,
                            searchable: false,
                            render: function render(data, type, row, meta) {
                                var ret = '';
                                ret += '<div class="user-avatar user-avatar-xxl">';
                                ret += '    <img src="' + row.news_mainPhoto + '" alt="">';
                                ret += '</div>';
                                return ret;
                                //return row.gift_city + row.gift_area + row.gift_address;
                                //var editRet = '<a id="table-btn" class="btn btn-sm btn-secondary" href="javascript: void(0);" data-method="edit" data-uid="' + row.quotation_serial + '"><i class="fa fa-pencil-alt"></i></a>          <a id="table-btn" class="btn btn-sm btn-secondary" href="javascript: void(0);" data-method="setting" data-uid="' + row.quotation_serial + '"><i class="fas fa-cog"></i></a>';

                                //if (row.quotationUser_perm == "A" || row.quotationUser_perm == "D" || row.quotationUser_perm == "admin" || row.quotationUser_perm == "pro") {
                                //    editRet = editRet + '          <a  id="table-btn" class="btn btn-sm btn-secondary" href="javascript: void(0);" data-method="del" data-uid="' + row.quotation_serial + '"><i class="far fa-trash-alt"></i></a>';
                                //}
                                //return editRet;
                            }
                        }
                        ,  {
                            targets: 3,
                            orderable: false,
                            searchable: false,
                            render: function render(data, type, row, meta) {
                                var ret = '';

                                ret += '<button type="button" data-uid="' + row.news_uid + '" data-method="edit" class="btn btn-sm btn-icon btn-secondary" ><i class="fa fa-pencil-alt"></i> <span class="sr-only">Edit</span></button>';
                                ret += '<button type="button" data-uid="' + row.news_uid + '" data-method="del" class="btn btn-sm btn-icon btn-secondary"><i class="far fa-trash-alt"></i> <span class="sr-only">Remove</span></button>';
                                return ret;
                            }
                        }
                    ],

                });
            },
            handleSearchRecords: function handleSearchRecords() {
                var self = this;

                $('#table-search, #filterBy').on('keyup change focus', function (e) {
                    var filterBy = $('#filterBy').val();
                    var hasFilter = filterBy !== '';
                    var value = $('#table-search').val();

                    self.table.search('').columns().search('').draw();

                    if (hasFilter) {
                        self.table.columns(filterBy).search(value).draw();
                    } else {
                        self.table.search(value).draw();
                    }

                });
            }
        }

        dataTables.init();
    }

    function loadTagsInput() {
        $('#news_tags').select2({
            width: '100%',
            tags: true,
            tokenSeparators: [',', ' '],
            multiple: true,
            minimumInputLength: 2,
            placeholder: '輸入Tag用空白或逗號分隔關鍵字',
            ajax: {
                url: '/BackEndApi/queryTags',
                dataType: 'json',
                delay: 500,
                type: 'post',
                // 要送出的資料
                data: function (params) {
                    // 在伺服器會得到一個 POST 'search' 
                    return {
                        search: params.term
                    };
                },
                processResults: function (data, params) {
                    console.log(data.data)

                    // 一定要返回 results 物件
                    return {
                        results: data.data,

                    }
                }
            },
            createTag: function (params) {
                let term = $.trim(params.term);
                if (term.length < 2) {
                    return null
                }

                return {
                    id: term,
                    text: term,
                    // add indicator:
                    isNew: true
                };


            }
        });

        $('#news_tags').on('select2:select', function (e) {
            let tag = e.params.data;
            var formData = {
                search: tag.text
            }

            $.ajax({
                url: "/BackEndApi/updateTags",
                type: "post",
                data: formData,
                success: function (data, textStatus, jqXHR) {
                    var obj = data.data;
                    if (data.ret == "yes") {
                        $('#news_tags').find('[value="' + tag.text + '"]').replaceWith('<option selected value="' + obj.id + '">' + obj.text + '</option>');


                    } else {
                        alert(data.message);

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

function buttonClick2(obj) {
    var type = obj.getAttribute('data-method');
    var uid = obj.getAttribute('data-uid');

    mainTable = $('#dt-responsive').dataTable();
    mainRowID = $('#' + uid);

    mainPos = mainTable.fnGetPosition($('#' + uid)[0]);

    if (type == "del") {
        if (confirm('確定刪除此筆資料? 刪除後將無任何方法回復!')) {
            var formData = {
                method: "del",
                news_uid: uid
            }

            $.ajax({
                url: "/BackEndApi/newsAddEditDelGet",
                type: "post",
                data: formData,
                success: function (data, textStatus, jqXHR) {
                    if (data.ret == "yes") {
                        var row = mainTable.api().row(mainRowID).remove().draw(false);
                        alert('刪除完成!');

                    } else {
                        alert(data.message);

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

    if (type == "edit") {
        $('#method').val('edit');
        $('#news_uid').val(uid);

        var formData = {
            method: "get",
            news_uid: uid
        }

        $.ajax({
            url: "/BackEndApi/newsAddEditDelGet",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    cleanModalData();

                    var obj = data.data;
                    $('#method').val('edit');
                    $('#news_uid').val(uid);
                    $('#news_title').val(obj.news_title).trigger('change');
                    $('#news_subtitle').val(obj.news_subtitle).trigger('change');
                    $('#fileupload-avatar').parent().children('img').prop('src', obj.news_mainPhoto);
                    $('#news_date').val(obj.news_date).trigger('change');
                    $('#summernote').summernote('code', obj.news_content);

                    $.each(obj.tags, function (key, value) {
                        //var tagObj = {};
                        //tagObj.id = value.tag_uid;
                        //tagObj.text = value.tag_text;

                        //tagArray.push(tagObj);
                        //tagValArray.push(value.tag_uid);

                        var newOption = new Option(value.tag_text, value.tag_uid, true, true);
                        $('#news_tags').append(newOption).trigger('change');
                    });

                    $.each(obj.photos, function (key, value) {
                        var ret = '';
                        ret += '<div class="user-avatar user-avatar-xxl">';
                        ret += '    <img src="' + value.photo_path + '" alt="">';
                        ret += '</div>';

                        var trHtml = "";
                        trHtml += '<tr>';
                        trHtml += '     <td class="align-middle">  ' + ret + ' </td>';

                        trHtml += '     <td class="align-middle"> ' + value.photo_title + ' </td>';
                        trHtml += '     <td class="align-middle text-right">';
                        trHtml += '         <button type="button" data-uid="" media-uid="' + value.photo_uid + '" data-method="edit" onclick="buttonClick(this);" class="btn btn-sm btn-icon btn-secondary" data-toggle="modal" data-target="#clientContactEditModal"><i class="fa fa-pencil-alt"></i> <span class="sr-only">Edit</span></button>';
                        trHtml += '         <button type="button" data-uid="" media-uid="' + value.photo_uid + '" data-method="del" onclick="buttonClick(this);" class="btn btn-sm btn-icon btn-secondary"><i class="far fa-trash-alt"></i> <span class="sr-only">Remove</span></button>';
                        trHtml += '     </td>';
                        trHtml += '</tr>';

                        $('#media_table tbody').append(trHtml);
                        //$("input:checkbox[value='" + value.optionItem_uid + "']").prop('checked', true);
                    });


                    


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

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

function buttonClick(obj) {
    mediaTr = $(obj).closest('tr');

    var dataMethod = obj.getAttribute('data-method');
    var dataUid = obj.getAttribute('data-uid');
    var photo_uid = obj.getAttribute('media-uid');
    var photo_src = mediaTr.find('td').eq(0).find('img').prop('src').trim();
    var photo_title = mediaTr.find('td').eq(1).text().trim();

    var origin = location.origin;
    photo_src = photo_src.replace(origin, '');


    if (dataMethod == 'edit') {
        $('#photo_method').val('edit');
        $('#photo_uid').val(photo_uid);

        $('#fileupload-subPhoto').parent().children('img').prop('src', photo_src);

        $('#photo_title').val(photo_title).trigger('change');
        
        $('#socialItemModal').modal('toggle');
    }

    if (dataMethod == "del") {
        if (confirm('確定刪除此筆資料?')) {
            

            mediaTr.remove();
        }
    }

}

function cleanModalData() {
    $("#method").val("");
    $("#news_uid").val("");
    $("#news_title").val("");
    $("#news_subtitle").val("");
    $("#news_date").val("");
   

    $('#fileupload-avatar').parent().children('img').prop('src', '/BackEnd/assets/images/avatars/unknown-profile.jpg');
    

    var trList = $("#media_table").find("tbody").find("tr");
    $.each(trList, function (index, item) {
        $(item).remove();
    });
    $('#news_tags').empty();
    $('#news_tags').val(null).trigger('change')
}

function initMainPhotoUpload() {
    var url = "/BackEndApi/mainPhotoUpload";

    // =============================================================

    $('#fileupload-avatar').fileupload({
        url: url,
        dropZone: null,
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
        maxFileSize: 5000000
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index;
        var file = data.files[index];
        $('#avatar-warning-container').removeClass('show').text('');

        if (file.error) {
            $('#avatar-warning-container').addClass('show').text(file.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress-avatar').addClass('show').children().css('width', progress + '%');
    }).on('fileuploaddone', function (e, data) {
        var file = data.result.files[0];
        var $img = $(this).parent().children('img');
        var $old = $img.prop('src');

        if (file.url) {
            $img.prop('src', file.url);
        } else if (file.error) {
            $('#avatar-warning-container').addClass('show').text(file.error);
        }

        $('#progress-avatar').removeClass('show').children().css('width', 0);
    }); // File upload using button
    // =============================================================
}

function initSubPhotoUpload() {
    var url = "/BackEndApi/subPhotoUpload";

    // =============================================================

    $('#fileupload-subPhoto').fileupload({
        url: url,
        dropZone: null,
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
        maxFileSize: 5000000
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index;
        var file = data.files[index];
        $('#avatar-warning-container').removeClass('show').text('');

        if (file.error) {
            $('#avatar-warning-container').addClass('show').text(file.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress-avatar').addClass('show').children().css('width', progress + '%');
    }).on('fileuploaddone', function (e, data) {
        var file = data.result.files[0];
        var $img = $(this).parent().children('img');
        var $old = $img.prop('src');

        if (file.url) {
            $img.prop('src', file.url);
        } else if (file.error) {
            $('#avatar-warning-container').addClass('show').text(file.error);
        }

        $('#progress-avatar').removeClass('show').children().css('width', 0);
    }); // File upload using button
    // =============================================================
}

function initSummernote() {
    $('#summernote').summernote({
        height: 250,
        toolbar: [
            // [groupName, [list of button]]
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['font', ['strikethrough', 'superscript', 'subscript']],
            ['insert', ['link']],
            ['para', ['ul', 'paragraph']]
        ],onPaste: function (e) {
            var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
            e.preventDefault();
            document.execCommand('insertText', false, bufferText);
        }
    });
}