infrastructureModule.controller('docManageController',
    ['$log', '$http', '$q', '$scope', '$translate', '$timeout', 'SweetAlert', '$compile', 'docManageService', '$filter',
        function ($log, $http, $q, $scope, $translate, $timeout, SweetAlert, $compile, docManageService, $filter) {

            $scope.localData = {};
            $scope.pagingOptions = {
                totalItems: 10,  //总数据
            };
            $scope.loadMainData = function () {

                var config = {
                    params: {}
                };
                docManageService.getMainList(config).then(function (data, status, headers) {
                    if (status === 204) {
                        SweetAlert.warning("没有数据可以下载");
                        return;
                    }

                    $scope.dataGridUpdate(data);

                })
            };
            $scope.dataGridUpdate = function (_data) {
                $scope.localData = _data.items;

                $scope.queryStatusType($scope.localData);
                $scope.pagingOptions = {
                    totalItems: $scope.localData.length,  //总数据
                };

                $scope.dataGridOptions = {
                    // dataSource: {
                    //     store: $scope.localData.items,
                    //     reshapeOnPush: true
                    // },
                    bindingOptions: {
                        dataSource: 'localData',
                    },
                    // repaintChangesOnly: true,
                    // twoWayBindingEnabled: true,
                    showBorders: true,
                    paging: {
                        enable: true,
                        pageIndex: 0,
                        pageSize: 10
                    },
                    pager: {
                        allowedPageSizes: 5,
                        infoText: "当前 {0}页 /共 {1}页 ({2} 项)",
                        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: "docManage",//名字
                        ignoreExcelErrors: true,

                    },
                    showRowLines: true,
                    columnAutoWidth: true,
                    allowColumnReordering: true,
                    columns: [
                        {
                            dataField: "id",
                            caption: $translate.instant('SequenceNumber'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    var style = options.data.status == 1 ? '' : 'style="color:#999"';
                                    if (options.data.id) {
                                        $('<span ' + style + '>').text(options.data.id).appendTo(container);
                                    } else {
                                        $('<span>').text("").appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        {
                            dataField: "fileAttr",
                            caption: $translate.instant('DocumentAttr'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    var style = options.data.status == 1 ? '' : 'style="color:#999"';
                                    if (options.data.fileAttr) {
                                        $('<span ' + style + '>').text(options.data.fileAttr).appendTo(container);
                                    } else {
                                        $('<span>').text("").appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        {
                            dataField: "fileType",
                            caption: $translate.instant('DocumentType'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    var style = options.data.status == 1 ? '' : 'style="color:#999"';
                                    if (options.data.fileType) {
                                        $('<span ' + style + '>').text(options.data.fileType).appendTo(container);
                                    } else {
                                        $('<span>').text("").appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        {
                            dataField: "description",
                            caption: $translate.instant('Explain'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    var style = options.data.status == 1 ? '' : 'style="color:#999"';
                                    if (options.data.description) {
                                        $('<span ' + style + '>').text(options.data.description).appendTo(container);
                                    } else {
                                        $('<span>').text("").appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },

                        {
                            dataField: "requiredField",
                            caption: $translate.instant('RequiredFields'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    var style = options.data.status == 1 ? '' : 'style="color:#999"';
                                    if (options.data.requiredField) {
                                        $('<span '+style+'>').text(options.data.requiredField.join(",")).appendTo(container);
                                    } else {
                                        $('<span>').text("").appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },

                        {
                            dataField: "creator",
                            caption: $translate.instant('Creator'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    var style = options.data.status == 1 ? '' : 'style="color:#999"';
                                    if (options.data.creator) {
                                        $('<span ' + style + '>').text(options.data.creator).appendTo(container);
                                    } else {
                                        $('<span>').text("").appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        {
                            dataField: "updateTime",
                            caption: $translate.instant('UpdateTime'),
                            allowHeaderFiltering: true,

                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    var style = options.data.status == 1 ? '' : 'style="color:#999"';
                                    if (options.data.updateTime) {
                                        $('<span '+style+'>').text($filter('date')(options.data.updateTime, 'yyyy-MM-dd')).appendTo(container);
                                    } else {
                                        $('<span>').text('').appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        {
                            dataField: "status",
                            caption: $translate.instant('State'),
                            allowHeaderFiltering: true,
                            cellTemplate: function (container, options) {
                                try {
                                    $scope.queryStatusType(options.data);
                                    if (options.data.status == 1) {
                                        options.data.status = $translate.instant('Enabled');
                                        $('<span>').text(options.data.status).appendTo(container);
                                    } else {
                                        options.data.status = $translate.instant('Disabled');
                                        $('<span style="color:#999">').text($translate.instant('Disabled')).appendTo(container);
                                    }
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        {
                            dataField: "operation",
                            caption: $translate.instant('Operation'),
                            allowHeaderFiltering: false,
                            cellTemplate: function (container, options) {
                                try {
                                    var eventTarget = $('<a style="color:#506bf7;" data-id="'+options.data.id+'" href="javascript:void(0)"><span>'+$translate.instant("Edit")+'</span></a>');
                                    eventTarget.off('click').on('click',function(){
                                        $scope.openEditPop(options.data.id);
                                    });
                                    container.append(eventTarget);
                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        }
                    ],
                    rowAlternationEnabled: true,  //单双行颜色
                };
            };
            $scope.getTableHeight=function(){
                var row_height=$("table").find("tr").height();
                if(row_height){
                    return {
                        height:(row_height*12+100)+"px"
                    }
                }
            };
            $scope.exportEventTrigger = function(){
                $(".dx-datagrid-export-button").click();
            };
            //弹出框
            var openEditPop = function (rowId) {
                if (rowId) {
                    $scope.confirmDocFileType = editDocFileType;
                    $scope.localData.forEach(function (item) {
                        if (item.id == rowId) {
                            $scope.editModel = angular.copy(item);
                            // if($scope.editModel.status != 1 || $scope.editModel.status != 0){
                            //     // 特殊处理状态值,1 = “已启用”, 0 = “已禁用”
                            //     $scope.editModel.status = item.status == $translate.instant("Enabled") ?  1 : 0;
                            // }

                            $scope.queryStatusType($scope.editModel);
                        }
                    });
                }
                else {
                    $scope.confirmDocFileType = createDocFileType;
                    $scope.editModel = {};
                }
                createMultiSelect();
                $('#editPopDialog').modal('show');
            };

            function createMultiSelect() {
                $("#appMultiSelectContainer").html("");
                var htmlTemplate = $('<app-multi-select class="form-control" style="width:320px;"'
                    + ' this-option-map="editRequiredFieldsMap"'
                    + ' this-callback="editRequiredFieldsCallback"'
                    + ' this-default-checked="editModel.requiredField"'
                    + '></app-multi-select>');
                $compile(htmlTemplate)($scope);
                $("#appMultiSelectContainer").append(htmlTemplate);
            }

            //保存 增加档案类型
            var createDocFileType = function () {
                var uploadModel = angular.copy($scope.editModel);
                delete uploadModel.id; //新增文档不需要上传ID

                // 默认status为1
                if(uploadModel.status === undefined
                    || uploadModel.status === null
                    || uploadModel.status === "") uploadModel.status = 1;

                $scope.queryStatusType(uploadModel);
                docManageService.addFileType(uploadModel).then(function (data) {
                    if (data == true) {
                        SweetAlert.success($translate.instant('SaveSuccess'));
                        $scope.loadMainData();
                    } else {
                        SweetAlert.warning($translate.instant('SaveFail'));
                    }
                });
                $('#editPopDialog').modal('hide');
            };

            var editDocFileType = function () {
                var uploadModel = angular.copy($scope.editModel);
                $scope.queryStatusType(uploadModel);
                docManageService.editFileType(uploadModel).then(function (data) {
                    if (data == true) {
                        SweetAlert.success($translate.instant('SaveSuccess'));
                        $scope.loadMainData();
                    } else {
                        SweetAlert.warning($translate.instant('SaveFail'));
                    }
                });
                $('#editPopDialog').modal('hide');
            };

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

            $scope.editModel = {
                "id": null,//主键id
                "fileAttr": null,//档案属性 手写
                "fileTypeId": null,//暂无作用 因档案类型手写
                "fileType": null,//档案类型
                "requiredField": [],//必填字段对应id(先写死) 对应关系以前端为主导
                "requiredFieldJson": null,//后台转换使用
                "description": null,//说明
                "creatorId": null,//创建人id
                "creator": null,//创建人名字
                "createTime": null,//创建时间
                "updateTime": null,//更新时间
                "status": null,//'状态(0代表停用,1代表启用)'
                "remarks": null//备注
            };
            $scope.editRequiredFieldsMap = {
                1: "文件生效日期",
                2: "所属期间",
                3: "到期日",
                4: "实物索引号",
                5: "实物存放地点",
                6: "实物保管人",
                7: "税种"
            };
            $scope.editRequiredFieldsCallback = function (keys, values) {
                $scope.editModel.requiredField = values;
                $scope.editModel.requiredFieldJson = JSON.stringify(values);
            }

            // 在入口和出口都对数据的status字段进行过滤
            $scope.queryStatusType = function(model){
                if(Object.prototype.toString.call(model) === "[object Array]"){
                    model.forEach(function(item){
                        if(item.status === $translate.instant('Enabled')){
                            item.status = 1;
                        }else if(item.status === $translate.instant('Disabled')){
                            item.status = 0;
                        }
                    })
                }else{
                    if(model.status === $translate.instant('Enabled')){
                        model.status = 1;
                    }else if(model.status === $translate.instant('Disabled')){
                        model.status = 0;
                    }
                }
            }
            //----------------------taxation----basic-end-------------------------------
            ;(function initialize() {

                $scope.loadMainData();
                //注册方法
                $scope.openEditPop = openEditPop;
                $scope.confirmDocFileType = createDocFileType;
                $scope.cancelDocFileType = cancelDocFileType;

            })();
        }]);

infrastructureModule.directive('exportPlugin',function(){
    return{
        restrict:"EA",
        controller:['$scope','SweetAlert','$translate','docManageService','$q','$log',
            function($scope,SweetAlert,$translate,docManageService,$q,$log){
                $scope.exportTableData = function ()
                {
                    docManageService.exportTableData().then(function (data, status, headers) {
                        if(status===204){
                            SweetAlert.warning("没有数据可以下载");
                            return;
                        }
                        exportToExcel(data, 'docType.xls');
                    },function () {
                        SweetAlert.error($translate.instant('PleaseContactAdministrator'));
                    })
                };

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

                    $('#busy-indicator-container').show();

                    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;
                };
            }]
    }
});