vatModule.controller('VatRevenueConfMappingController', ['$scope', '$log', '$translate', '$timeout', 'SweetAlert', '$q',
    '$interval','dxDataGridService','$http','apiConfig','Upload','apiInterceptor','templateService',
    function ($scope, $log, $translate, $timeout, SweetAlert, $q, $interval,dxDataGridService,$http,apiConfig,Upload,
              apiInterceptor,templateService) {
        'use strict';

        //表格配置
        $scope.revenueGridOptions = $.extend(true, {}, dxDataGridService.BASIC_GRID_OPTIONS, {
            columns: [
                {dataField: 'id', caption: '', visible: false},
                {dataField: 'orgId', caption: $translate.instant('RevenueColOrg'), fixed: true, allowHeaderFiltering: true, minWidth: '300px',
                    calculateCellValue: function(data) {
                        return _.find($scope.selectOrgList, function(o) {
                            return o.id === data.orgId;
                        }).name;
                    }},
                {dataField: 'ouName', caption: $translate.instant('RevCMApplyBU'), fixed: true, allowHeaderFiltering: true, width: '100px'},
                {dataField: 'content', caption: $translate.instant('RevCMInvoiceCTX'), fixed: true, allowHeaderFiltering: true, width: '120px'},
                {dataField: 'taxRate', caption: $translate.instant('RevenueColTaxRate'), fixed: true, allowHeaderFiltering: true, width: '50px',
                    calculateCellValue: function(data) {
                        return (data.taxRate * 100) + '%';
                    }},

                {dataField: 'revenueTypeName', caption: $translate.instant('RevSearchType'), fixed: true, allowHeaderFiltering: true, minWidth: '300px'},
                {dataField: 'startDate', caption: $translate.instant('RevenueColEnable'), fixed: true, allowHeaderFiltering: true, width: '120px'},
                {dataField: 'endDate', caption: $translate.instant('RevenueColDisable'), fixed: true, allowHeaderFiltering: true, width: '120px'},
                {dataField: 'statusStr', caption: $translate.instant('RevenueColStatus'), fixed: true, allowHeaderFiltering: true, width: '50px'},
                {dataField: '', caption: $translate.instant('RevenueColEdit'), fixed: true,width: '80px', alignment: 'center',
                    cellTemplate: function (container, options) {
                        try {
                            $('<i class="fa fa-pencil-square-o" style="cursor: pointer"></i>&nbsp;&nbsp;')
                                .on('click', function () {
                                    $scope.editConfig(options.data);
                                }).appendTo(container);
                            $('<i class="fa fa-trash" style="cursor: pointer;margin-left: 5px;"></i>')
                                .on('click', function () {
                                    $scope.delConfig([options.data.id]);
                                }).appendTo(container);
                        }
                        catch (e) {
                            $log.error(e);
                        }
                    }},
            ],
            bindingOptions: {
                dataSource: 'pageConfDataSource',
            },
            selection: {
                mode: 'multiple',
                showCheckBoxesMode: 'always',
                allowSelectAll: true
            },
            onSelectionChanged: function (data) {
                $scope.selectedItems = data.selectedRowsData;
                $scope.selectedRecourdCount = data.selectedRowsData.length;
            },
        });

        //刷新页面
        $scope.refreshConfigGrid = function () {
            $http.post('/revenueConfMapping/queryPage',{pageInfo: $scope.pagingOptions}, apiConfig.createVat())
                .success(function (res) {
                    if (res && res.list) {
                        $scope.pageConfDataSource = res.list;
                        $scope.pagingOptions.totalItems = res.pageInfo.totalCount;
                    }else {
                        SweetAlert.error($translate.instant('SystemError'));
                    }
                })
        };

        //添加配置
        $scope.addConfig = function () {
            $scope.isEdit = false;
            $scope.isOrgReadOnly = false;
            $($scope.revenueConfAddDiv).modal('show');
        };

        $scope.batchDelConfig = function () {
            if (!!$scope.selectedRecourdCount) {
                $scope.delConfig(_.map($scope.selectedItems, function(item){ return item.id; }));
            }else {
                SweetAlert.warning($translate.instant('PleaseSelectAtLeastOneItem'));
            }
        };

        ///删除配置
        $scope.delConfig = function (idList) {
            $http.post('/revenueConfMapping/del',idList, apiConfig.createVat())
                .success(function (res) {
                    if (res && 0 === res.code) {
                        SweetAlert.success($translate.instant('RevenueDelSuccess'));
                        $scope.refreshConfigGrid();
                    }else {
                        SweetAlert.error($translate.instant('SystemError'));
                    }
                })
        };

        //添加配置
        $scope.saveConfig = function () {
            if ($scope.isEdit) {
                $http.post('/revenueConfMapping/update',$scope.formParam, apiConfig.createVat())
                    .success(function (res) {
                        if (res && 0 === res.code) {
                            SweetAlert.success($translate.instant('RevenueAddSuccess'));
                            $scope.refreshConfigGrid();
                            $($scope.revenueConfAddDiv).modal('hide');
                            $scope.cancelModal();
                        }else {
                            SweetAlert.error($translate.instant('SystemError'));
                        }
                    })
            }else {
                $http.post('/revenueConfMapping/add',$scope.formParam, apiConfig.createVat())
                    .success(function (res) {
                        if (res && 0 === res.code) {
                            SweetAlert.success($translate.instant('RevenueAddSuccess'));
                            $scope.refreshConfigGrid();
                            $($scope.revenueConfAddDiv).modal('hide');
                            $scope.cancelModal();
                        }else {
                            SweetAlert.error($translate.instant('SystemError'));
                        }
                    })
            }
        };

        //关闭配置框
        $scope.cancelModal = function () {
            $scope.formParam = {
                startDate: null,
                endDate: null,
            };
            $('#configForm')[0].reset();
        };

        //编辑
        $scope.editConfig = function (data) {
            $scope.isEdit = true;
            $scope.isOrgReadOnly = true;
            $scope.formParam = data;
            $scope.formParam.orgList = [data.orgId];
            $($scope.revenueConfAddDiv).modal('show');
        };

        //获取机构列表
        function getMyOrgList() {
            $http.get('/org/getMyOrgList',apiConfig.createVat())
                .success(function (res) {
                    if (res && 0 === res.code) {
                        $scope.selectOrgList = res.data;
                        $scope.refreshConfigGrid();
                    }else {
                        SweetAlert.error($translate.instant('RevenueGetOrgError'));
                    }
                })
        }

        $scope.upload = function(uploadType) {

            if (!$scope.uploadFile || !$scope.uploadFile.file.name) {
                SweetAlert.warning($translate.instant('SelectUploadFileRequired'));
                return;
            }
            $('#busy-indicator-container').show();
            var deferred = $q.defer();
            Upload.upload({
                url: apiInterceptor.webApiHostUrl + '/revenueConfMapping/upload',
                data: {
                    type: uploadType,
                },
                file: $scope.uploadFile.file,
                // resumeChunkSize: resumable ? $scope.chunkSize : null,
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken(),
                    withCredentials: true
                },
                withCredentials: true
            }).then(function(res) {
                $('#busy-indicator-container').hide();
                deferred.resolve();
                if (res && res.data && 0 === res.data.code) {
                    SweetAlert.success($translate.instant('ImportSuccess'));
                    $scope.refreshConfigGrid();
                } else {
                    SweetAlert.error($translate.instant('SystemError'));
                }

            }, function(resp) {
                deferred.resolve();
                if (resp.statusText === 'HttpRequestValidationException') {
                    SweetAlert.warning($translate.instant('HttpRequestValidationException'));
                } else {
                    SweetAlert.warning($translate.instant('SaveFail'));
                }
                $('#busy-indicator-container').hide();
            }, function(evt) {
                deferred.resolve();
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                $log.debug('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            });
        };

        $scope.downloadTemplate = function () {
            templateService.downloadTemplate(constant.importFileType.RevenueMapping).success(function (data, status, headers) {
                var octetStreamMime = 'application/octet-stream';
                var contentType = headers('content-type') || octetStreamMime;
                if (window.navigator.msSaveBlob) {
                    var blob = new Blob([data], {
                        type: contentType
                    });
                    navigator.msSaveBlob(blob, "开票记录与收入类型映射模板");
                } else {
                    var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
                    if (urlCreator) {
                        var a = document.createElement('a');
                        var blob = new Blob([data], {
                            type: contentType
                        });
                        var url = urlCreator.createObjectURL(blob);
                        a.href = url;
                        a.target = '_blank';
                        a.download = "开票记录与收入类型映射模板.xlsx";
                        document.body.appendChild(a);
                        a.click();
                    }
                }
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        };


        (function initialize() {

            //分页的设置
            $scope.pagingOptions = {
                pageIndex: 1,  //当前页码
                totalItems: 0,  //总数据
                pageSize: 20,  //每页多少条数据
            };

            $scope.formParam = {

            };

            $scope.isOrgReadOnly = false;

            //机构下拉设置
            $scope.selectOrgOptions = {
                displayExpr: 'name',
                valueExpr: 'id',
                width: '95%',
                bindingOptions: {
                    value: 'formParam.orgList',
                    dataSource: 'selectOrgList',
                    readOnly: 'isOrgReadOnly'
                },
                height: '30px',
                placeholder: '',
                showClearButton: true,
                searchEnabled: true,
                noDataText: $translate.instant('RevenueNoOrgData'),
                showSelectionControls: true
            };

            //税率下拉框
            $scope.selectTaxRateOptions = {
                displayExpr: 'key',
                valueExpr: 'val',
                bindingOptions: {
                    value: 'formParam.taxRate'
                },
                dataSource: [
                    {'key': '0%', 'val': 0},
                    {'key': '1.5%', 'val': 0.015},
                    {'key': '3%', 'val': 0.03},
                    {'key': '5%', 'val': 0.05},
                    {'key': '6%', 'val': 0.06},
                    {'key': '10%', 'val': 0.1},
                    {'key': '16%', 'val': 0.16},
                ]
            };


            $scope.selectStatusOptions = {
                displayExpr: 'key',
                valueExpr: 'val',
                bindingOptions: {
                    value: 'formParam.status'
                },
                dataSource: [
                    {'key': '启用', 'val': 0},
                    {'key': '停用', 'val': 1},
                ]
            };

            $scope.dateBoxStart = {
                width: '100%',
                acceptCustomValue: false,
                openOnFieldClick: true,
                displayFormat: 'yyyy-MM',
                maxZoomLevel: "year",
                dateSerializationFormat: 'yyyy-MM',
                bindingOptions: {
                    value: 'formParam.startDate'
                }
            };

            $scope.dateBoxEnd = {
                width: '100%',
                acceptCustomValue: false,
                openOnFieldClick: true,
                displayFormat: 'yyyy-MM',
                maxZoomLevel: "year",
                dateSerializationFormat: 'yyyy-MM',
                bindingOptions: {
                    value: 'formParam.endDate'
                }
            };


            $scope.revenueConfAddDiv = ".vat-revenue-conf-mapping #revenueTypeAddDiv";

            function init() {
                getMyOrgList();

            }
            init()

        })();
    }
]);