var mainTable;
var mainRowID;
var mainPos;

$(document).ready(function () {
    loadDataTable();
    initMainPhotoUpload();
    $('#newsNewModal').on('click', function () {

        loadTagsInput();

        cleanModalData();

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

        $('#clientNewModal').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") {
                        $('#kol_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 cleanModalData() {
    $("#method").val("");
    $("#news_uid").val("");
    $("#news_title").val("");
    $("#news_subtitle").val("");
    $("#news_date").val("");
    $('#news_tags').empty();
    $('#news_tags').val(null).trigger('change');

    $('#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();
    });
    $('#kol_tags').empty();
    $('#kol_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
    // =============================================================
}