/**
 * Created by Administrator on 2019/2/28 0028.
 */
frameworkModule.controller('appUsrOperateLogController',
    ['$log', '$q', '$scope', '$translate', '$timeout', '$compile', 'usrOperateLogService','$filter','SweetAlert',
        function ($log, $q, $scope, $translate, $timeout,  $compile, usrOperateLogService, $filter,SweetAlert) {
            // thisModuleName:"@",
            // thisTitle:"@",
            // thisParams:"=",
            $scope.localData = null;

            $scope.loadMainData = function () {
                $scope.thisModuleId = $scope.thisModuleId ? $scope.thisModuleId : [];
                if($scope.thisModuleId.length===0){
                    $("input[name='dataGridCheckBox']").each(function (index, item) {
                        if (item.checked) {
                            var cellId = $(item).attr("data-id");
                            $scope.thisModuleId.push(cellId);
                        }
                    });
                }
                if($("body[ng-controller='AppController']").length==1 && $scope.thisModuleId.length===0){
                    SweetAlert.warning($translate.instant("NeedChecked"));
                    return;
                }
                var config = {
                    // params: {
                    "ids":$scope.thisModuleId
                    // }
                };
                usrOperateLogService[$scope.thisModuleName](config).then(function (data) {
                    if (status === 204) {
                        SweetAlert.warning("没有数据可以下载");
                        return;
                    }
                    $scope.dataGridUpdate(data);
                    $scope.thisModuleId=[];//清空查询id
                })
                if(!$("#usrOperateLogPop").length){
                    var usrOperateLogPopTemp = $($("#usrOperateLogPopContainer").html());
                    $("body").append($compile(usrOperateLogPopTemp)($scope));
                }
                $("#usrOperateLogPop").modal("show");
            };
            // $scope.sniffHelpPopRadio = function(){
            //     taxDocumentListService.getDocumentsAttrAndType({params: {}}).then(function (data) {
            //         $scope.FileAttrAndTypeCache = data.items;
            //         //根据文件属性来匹配出 文件类型下拉列表
            //         $scope.syncFileType($scope.editFieldModel.fileAttr);
            //         $scope.editFieldModel.fileType = checkedItem.getAttribute("data-fileType");
            //         $scope.syncRequiredFields($scope.editFieldModel);
            //     });
            //
            //     $("#helpPopDialog").modal("hide");
            // };
            // comment: "767"
            // createTime: "2019-01-28T11:38:31.000+08:00"
            // id: "1"
            // ip: "87"
            // moduleName: "32424"
            // operationAction: "465"
            // operationContent: "32332"
            // operationObject: "4355"
            // operationUser: "868"
            // originalState: "7657"
            // updateState: "768"
            $scope.dataGridUpdate = function (_data) {
                $scope.localData = _data.items;
                $scope.dataGridOptions = {
                    bindingOptions:{
                        dataSource: 'localData',
                    },
                    showBorders: true,
                    paging: {
                        enable: true,
                        pageIndex: 0,
                        pageSize: 10
                    },
                    pager: {
                        allowedPageSizes: 5,
                        infoText:$translate.instant('Page {0} of {1} ({2} items)'),
                        showInfo: true,
                        showNavigationButtons: true,
                        showPageSizeSelector: true,
                        visible: true
                    },
                    searchPanel: {//查询
                        highlightCaseSensitive: true,
                        highlightSearchText: true,
                        searchVisibleColumnsOnly: false,
                        text: "",
                        width: 518,
                        visible: true,
                        placeholder: $translate.instant('Search'),
                    },
                    sorting: {//排序
                        ascendingText: "Sort Ascending",
                        clearText: "Clear Sorting",
                        descendingText: "Sort Descending",
                        mode: "single"
                    },
                    // 'export': {
                    //     allowExportSelectedData: false,//允许选择导出
                    //     customizeExcelCell: null,
                    //     enabled: true,//允许导出
                    //     excelFilterEnabled: false,
                    //     excelWrapTextEnabled: false,
                    //     fileName: "usrlog",//名字
                    //     ignoreExcelErrors: true,
                    //
                    // },
                    showRowLines: true,
                    columnAutoWidth: true,
                    allowColumnReordering: true,
                    columns: [
                        {
                            dataField: "id",
                            caption: $translate.instant('LogIndex'),
                            allowHeaderFiltering: true,

                            cellTemplate: function (container, options) {
                                var target = $('<span data-name="logCheckedItem" type="checkbox" ' +
                                    'data-id="' + options.data.id + '" ' +
                                    '>' + options.data.id + '</span>');
                                container.append(target);
                                var table = $("#appUsrLogTable").find("table");
                                $(table).off("click").on("click",function(e){
                                    var target = $(e.target);
                                    if(target.parents("tr").length)
                                        target.parents("tr").find("td").toggleClass('log-export-checked-item');
                                })
                            }
                        },
                        {
                            dataField: "createTime",
                            caption: $translate.instant('LogOperationTime'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    if (options.data.createTime) {
                                        $('<span>').text($filter('date')(options.data.createTime, 'yyyy-MM-dd hh:mm')).appendTo(container);
                                    } else {
                                        $('<span>').text('').appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        // {
                        //     dataField: "operationObject",
                        //     caption: $translate.instant('LogOperateObject'),
                        //     allowHeaderFiltering: true,
                        // },
                        {
                            dataField: "operationAction",
                            caption: $translate.instant('LogOperationDescription'),
                            allowHeaderFiltering: true,
                        },

                        // {
                        //     dataField: "operationContent",
                        //     caption: $translate.instant('OperationContent'),
                        //     allowHeaderFiltering: true,
                        // },

                        // {
                        //     dataField: "originalState",
                        //     caption: $translate.instant('LogOriginalState'),
                        //     allowHeaderFiltering: true,
                        // },
                        {
                            dataField: "updateState",
                            caption: $translate.instant('OperationContent'),
                            allowHeaderFiltering: true,
                        },
                        {
                            dataField: "operationUser",
                            caption: $translate.instant('LogOperationUser'),
                            allowHeaderFiltering: true,
                        },
                        {
                            dataField: "comment",
                            caption: $translate.instant('LogComments'),
                            allowHeaderFiltering: false,
                        }
                    ],
                    rowAlternationEnabled: true,  //单双行颜色
                };
            };

            $scope.openUsrOperateLogPop = function(){
                $scope.loadMainData();
            };
            $scope.hideUsrOperateLogPop = function(){
                $("#usrOperateLogPop").modal("hide");
            };

            //取消
            var cancelDocFileType = function () {
                console.log("cancelDocFileType")
            };


        }]);
frameworkModule.directive('usrLogExportPlugin',function(){
    return{
        restrict:"EA",
        controller:['$scope','SweetAlert','$translate','usrOperateLogService','$q','$log',
            function($scope,SweetAlert,$translate,usrOperateLogService,$q,$log){
                $scope.exportTableData = function ()
                {
                    // var checkedItems = $(".log-export-checked-item");
                    var ids = [];
                    /*if(checkedItems.length)
                        checkedItems.find("span[data-name='logCheckedItem']")
                        .each(function(index,checkedItem){
                            var idLike = checkedItem.getAttribute('data-id');
                            if(idLike || idLike == 0){
                                ids.push(idLike);
                            }
                        });*/
                    var datas=$scope.localData;
                    for(var i=0;i<datas.length;i++){
                        if(datas[i].id){
                            ids.push(datas[i].id);
                        }
                    }
                    usrOperateLogService[$scope.thisModuleName + "Export"]({
                        "ids":ids
                    }).then(function (data, status, headers) {
                        if(status===204){
                            SweetAlert.warning("没有数据可以下载");
                            return;
                        }
                        exportToExcel(data, $scope.thisModuleName + '.xls');
                    },function () {
                        SweetAlert.error($translate.instant('PleaseContactAdministrator'));
                    })
                };

                //下载服务器上的xls文件
                var exportToExcel = function (data, filename) {

                    var defer = $q.defer();
                    // var octetStreamMime = 'application/vnd.ms-excel';
                    var success = false;

                    // Get the headers
                    // headers = headers();

                    // Get the filename from the x-filename header or default to "download.bin"
                    // var filename = decodeURI(headers['x-file-name']) + defaultFileName;

                    // Determine the content type from the header or default to "application/octet-stream"
                    // var contentType = headers['content-type'] || octetStreamMime;

                    try {
                        // Try using msSaveBlob if supported
                        //console.log("Trying saveBlob method ...");
                        var blob = new Blob([data], { type: "arraybuffer" });
                        if (navigator.msSaveBlob)
                            navigator.msSaveBlob(blob, filename);
                        else {
                            // Try using other saveBlob implementations, if available
                            var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                            if (saveBlob === undefined) throw "Not supported";
                            saveBlob(blob, filename);
                        }
                        //console.log("saveBlob succeeded");
                        success = true;
                    } catch (ex) {
                        $log.debug("saveBlob method failed with the following exception:");
                        $log.debug(ex);
                    }

                    if (!success) {
                        // Get the blob url creator
                        var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
                        if (urlCreator) {
                            // Try to use a download link
                            var link = document.createElement('a');
                            if ('download' in link) {
                                // Try to simulate a click
                                try {
                                    // Prepare a blob URL
                                    //console.log("Trying download link method with simulated click ...");
                                    var blobdownload = new Blob([data], { type: "arraybuffer" });
                                    var urldownload = urlCreator.createObjectURL(blobdownload);
                                    link.setAttribute('href', urldownload);

                                    // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                                    link.setAttribute("download", filename);

                                    // Simulate clicking the download link
                                    var event = document.createEvent('MouseEvents');
                                    event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                                    link.dispatchEvent(event);
                                    //console.log("Download link method with simulated click succeeded");
                                    success = true;

                                } catch (ex) {
                                    $log.debug("Download link method with simulated click failed with the following exception:");
                                    $log.debug(ex);
                                    $q.reject();
                                }
                            }

                            if (!success) {
                                // Fallback to window.location method
                                try {
                                    // Prepare a blob URL
                                    // Use application/octet-stream when using window.location to force download
                                    //console.log("Trying download link method with window.location ...");
                                    var blobsuccess = new Blob([data], { type: "arraybuffer" });
                                    var urlsuccess = urlCreator.createObjectURL(blobsuccess);
                                    window.location = urlsuccess;
                                    //console.log("Download link method with window.location succeeded");
                                    success = true;
                                } catch (ex) {
                                    //console.log("Download link method with window.location failed with the following exception:");
                                    $log.debug(ex);
                                    $q.reject();
                                }
                            }
                        }
                    }

                    if (!success) {
                        // Fallback to window.open method
                        $log.debug("No methods worked for saving the arraybuffer, using last resort window.open");
                        window.open(httpPath, '_blank', '');
                    }

                    //Delete the file
                    // deleteFile(encodeURI(filename));
                    defer.resolve('success');
                    $('#busy-indicator-container').hide();
                    return defer.promise;
                };
            }]
    }
});