vatModule.controller('VatRevenueConfMappingController', ['$scope', '$log', '$translate', '$timeout', 'SweetAlert', '$q',
    '$interval','dxDataGridService','$http','apiConfig','Upload','apiInterceptor',
    function ($scope, $log, $translate, $timeout, SweetAlert, $q, $interval,dxDataGridService,$http,apiConfig,Upload,apiInterceptor) {
        '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.editConfig(options.data);
                                }).appendTo(container);
                        }
                        catch (e) {
                            $log.error(e);
                        }
                    }},
            ],
            bindingOptions: {
                dataSource: 'pageConfDataSource',
            },
            selection: {
                mode: 'multiple',
                showCheckBoxesMode: 'always',
                allowSelectAll: true
            }
        });

        //刷新页面
        $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.delConfig = function () {
            SweetAlert.info('del');
        };

        //添加配置
        $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');
                        }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');
                        }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;
                    }else {
                        SweetAlert.error($translate.instant('RevenueGetOrgError'));
                    }
                })
        }

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


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

                console.log('Error status: ' + resp.status);
            }, function(evt) {
                deferred.resolve();
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                $log.debug('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            });
        };


        (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();
                $scope.refreshConfigGrid();
            }
            init()

        })();
    }
]);