vatModule.controller('VatPreviewRedLetterInfoTabController', ['$rootScope','$scope', '$log','$filter', '$translate', '$timeout', 'SweetAlert', '$q', 'uiGridConstants', '$interval', 'vatPreviewService', 'browserService', 'vatSessionService', 'region', 'enums', 'vatExportService',
    function ($rootScope,$scope, $log,$filter, $translate, $timeout, SweetAlert, $q, uiGridConstants, $interval, vatPreviewService, browserService, vatSessionService, region, enums, vatExportService) {
        'use strict';

        $scope.startDate = new Date(vatSessionService.project.year, 0, 1);
        $scope.endDate = new Date(vatSessionService.project.year, 11, 31);
        $scope.dateFormat = $translate.instant('dateFormat4YearMonthDay');
        $scope.startMonth = vatSessionService.month;
        $scope.endMonth = vatSessionService.month;
        $scope.totalMoneyAmount = 0;
        $scope.totalTaxAmount = 0;
        $scope.pageSize = constant.vatPagesize;

        var minDate = [1, vatSessionService.project.year];
        // var minDate = moment().startOf('month').subtract(0, 'months');
        var maxDate = [12, vatSessionService.project.year];
        var setDate = [
            [vatSessionService.month, vatSessionService.project.year],
            [vatSessionService.month, vatSessionService.project.year]];

        $scope.monthList = [$translate.instant('Month01'),
                            $translate.instant('Month02'),
                            $translate.instant('Month03'),
                            $translate.instant('Month04'),
                            $translate.instant('Month05'),
                            $translate.instant('Month06'),
                            $translate.instant('Month07'),
                            $translate.instant('Month08'),
                            $translate.instant('Month09'),
                            $translate.instant('Month10'),
                            $translate.instant('Month11'),
                            $translate.instant('Month12')
        ];

        //初始化期间
        var initPeriods = function () {
            var curMonth = new Date().getMonth() + 1;


            $scope.queryParams = {
                pageInfo: {},
                periodStart: '',
                periodEnd: '',
                certificationDateStart: null,
                certificationDateEnd: null,
                invoiceCode: '',
                invoiceNumber: '',
                sellerTaxNumber: '',
                amountStart: null,
                amountEnd: null,
                invoiceType: null,
                taxAmountStart: null,
                taxAmountEnd: null,
                certificationStatus: null
            };
        };

        /*var countTotal = function(){
            $scope.queryParams.pageInfo = {
                totalCount: -1,
                pageIndex: 1,
                pageSize: -1,
                totalPage: 0,
            };
            vatPreviewService.queryInputInvoiceAllList($scope.queryParams).success(function (data) {
                if (data) {
                    var totalMoneyAmount = 0;
                    var totalTaxAmount = 0;
                    _.each(data, function (x) {
                        totalMoneyAmount = totalMoneyAmount + parseFloat(x.hjje.replace(/,/g, ""));
                        totalTaxAmount = totalTaxAmount + parseFloat(x.hjse.replace(/,/g, ""));
                    })
                    $scope.totalMoneyAmount = totalMoneyAmount.toLocaleString();
                    $scope.totalTaxAmount = totalTaxAmount.toLocaleString();
                }
            });
        };*/

        //从数据库中load数据
        var loadRedLetterInfoTabItemDataFromDB = function (pageIndex) {
            initRedLetterInfoTabItemPagination();

            $scope.curRedLetterInfoTabItemPage = pageIndex;

            //初始化查询信息
            $scope.queryParams.pageInfo = {
                totalCount: $scope.queryRedLetterInfoTabItemResult.pageInfo.totalCount,
                pageIndex: pageIndex,
                pageSize: $scope.queryRedLetterInfoTabItemResult.pageInfo.pageSize,
                totalPage: 0
            };
            $scope.getDataFromDatabase($scope.queryParams);
        };

        $scope.getDataFromDatabase = function (queryParams){
            vatPreviewService.getRLITDataForDisplay(queryParams).success(function (data) {
                if (data) {
                    // minDate = data.
                    var index = 1;
                    data.list.forEach(function (v) {
                        v.index = index++;
                    });
                    $scope.gridOptions.data = data.list;
                    $scope.queryRedLetterInfoTabItemResult.pageInfo = data;
                    computeRedLetterInfoTabPage();
                    $scope.ledgerName = data.list[0].ledgerName;
                    $scope.currencyCode = data.list[0].ledgerCurrencyCode;
                    $scope.status = data.list[0].status;
                    $scope.importDate = $filter('date')(data.list[0].date, "yyyy-MM-dd hh:mm:ss");
                }
            });
        };

        //点击任意一页加载数据事件
        var loadRedLetterInfoTabDataByPage = function (pageIndex) {
            loadRedLetterInfoTabItemDataFromDB(pageIndex);
        };

        //计算页数,创建分页栏
        var computeRedLetterInfoTabPage = function () {

            if ($scope.queryRedLetterInfoTabItemResult.pageInfo && $scope.queryRedLetterInfoTabItemResult.pageInfo.total > 0) {

                var totalPage = parseInt($scope.queryRedLetterInfoTabItemResult.pageInfo.total / $scope.pageSize);
                totalPage = $scope.queryRedLetterInfoTabItemResult.pageInfo.totalCount % $scope.pageSize == 0 ? totalPage : totalPage + 1;

                //计算本页记录数
                if ($scope.queryRedLetterInfoTabItemResult.pageInfo.pageNum === totalPage) {
                    $scope.curPageItemCount = $scope.queryRedLetterInfoTabItemResult.pageInfo.total % $scope.pageSize;
                }
                else {
                    $scope.curPageItemCount = $scope.pageSize;
                }

                $scope.queryRedLetterInfoTabItemResult.pageInfo.totalPage = totalPage;

                var createPage = $("#totalInvoicePage").createPage({
                    pageCount: totalPage,
                    current: $scope.curRedLetterInfoTabItemPage,
                    backFn: function (p) {
                        //单击回调方法,p是当前页码
                        loadRedLetterInfoTabDataByPage(p);
                    }
                });

                $('#totalInvoicePage').css('display', 'inline-block');
            } else {
                //如果查询结果为0,则直接设置本页记录数为0
                $scope.curPageItemCount = 0;
                var createPage = $("#totalInvoicePage").createPage({
                    pageCount: 0,
                    current: $scope.curRedLetterInfoTabItemPage,
                    backFn: function (p) {
                        //单击回调方法,p是当前页码
                        loadRedLetterInfoTabDataByPage(p);
                    }
                });

                $('#totalInvoicePage').css('display', 'inline-block');
            }
        };

        //初始化分页信息
        var initRedLetterInfoTabItemPagination = function () {
            $scope.queryRedLetterInfoTabItemResult = {
                list: [],
                pageInfo: {
                    totalCount: -1,
                    pageIndex: 1,
                    pageSize: constant.pagesize,
                    totalPage: 0
                }
            }

            $scope.curRedLetterInfoTabItemPage = 1;
        };

        //去掉所有的查询条件,重新load数据
        var doDataFilterReset = function () {
            $scope.queryParams = {
                pageInfo: {},
                periodStart: '',
                periodEnd: '',
                certificationDateStart: null,
                certificationDateEnd: null,
                invoiceCode: '',
                invoiceNumber: '',
                sellerTaxNumber: '',
                amountStart: null,
                amountEnd: null,
                invoiceType: null,
                taxAmountStart: null,
                taxAmountEnd: null,
                certificationStatus: null
            };
            $scope.criteriaList = [];
            $scope.queryParams.periodStart = $scope.startMonth;
            $scope.queryParams.periodEnd = $scope.endMonth;
            // countTotal();
            loadRedLetterInfoTabItemDataFromDB(1);
            $('.filter-button').popover("hide");
        };

        //在popover打开时执行事件
        var showPopover = function () {
            $timeout(function () {
                initDatePickers();
            }, 500);
        };

        //初始化时间控件
        var initDatePickers = function () {
            //认证开始时间
            var ele1 = $("#certificationDateStart");
            ele1.datepicker({
                startDate: $scope.startDate,
                endDate: $scope.endDate,
                language: region,
                autoclose: true,//选中之后自动隐藏日期选择框
                clearBtn: true,//清除按钮
                todayBtn: false,//今日按钮
                format: $scope.dateFormat//日期格式,详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
            });
            ele1.datepicker("setDate", $scope.queryParams.certificationDateStart);
            //认证结束时间
            var ele2 = $("#certificationDateEnd");
            ele2.datepicker({
                startDate: $scope.startDate,
                endDate: $scope.endDate,
                language: region,
                autoclose: true,//选中之后自动隐藏日期选择框
                clearBtn: true,//清除按钮
                todayBtn: false,//今日按钮
                format: $scope.dateFormat//日期格式,详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
            })
            ele2.datepicker("setDate", $scope.queryParams.certificationDateEnd);


            //初始化已选择的发票类型和认证结果
            $scope.InvoiceType.selected = _.find($scope.invoiceTypeList, function (v) {
                return v.id == $scope.queryParams.invoiceType;
            })

            $scope.CertificationStatus.selected = _.find($scope.cetificationResultList, function (v) {
                return v.id == $scope.queryParams.certificationStatus;
            })
        };

        var downloadRLIT = function () {
            var localDate = $filter('date')(new Date(), 'yyyyMMddHHmmss');
            var fileName = constant.exportExcelFileName.redLetterInfoTab + localDate;
            vatPreviewService.initExportRLITData($scope.queryParams, fileName).then(function (data) {
                if (data) {
                    ackMessageBox.success(translate('FileExportSuccess'));
                }
            });
        };


        (function initialize() {
            $log.debug('VatPreviewInputInvoiceController.ctor()...');
            $('#input-invoice-period-picker').focus(function () {
                $('.filter-button').popover("hide");
            });
            //初始化month-picker
            $('#input-invoice-period-picker').rangePicker({
                minDate: minDate,
                maxDate: maxDate,
                setDate: setDate,
                months: $scope.monthList,//['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                ConfirmBtnText: $translate.instant('Confirm'),
                CancelBtnText: $translate.instant('ButtonCancel')
            })
             .on('datePicker.done', function (e, result) {
                 //开始月份
                 var startMonth = result[0][0];
                 //结束月份
                 var endMonth = result[1][0];
                 $scope.startMonth = startMonth;
                 $scope.endMonth = endMonth;

                 $scope.queryParams.periodStart = vatSessionService.year * 100 + vatSessionService.month;
                 $scope.queryParams.periodEnd = vatSessionService.year * 100 + vatSessionService.month;
                 // countTotal();
                 $scope.queryParams.orgId = vatSessionService.project.organizationID;
                 loadRedLetterInfoTabItemDataFromDB(1);
             });


            $scope.gridOptions = {
                rowHeight: constant.UIGrid.rowHeight,
                selectionRowHeaderWidth: constant.UIGrid.rowHeight,
                virtualizationThreshold: 50,//默认加载50条数据,避免在数据展示时,只显示前面4条
                enableSorting: false,
                enableColumnMenus: false,
                columnDefs: [
                 { name: $translate.instant('SubjectNum'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.subjectNum}}<span></div>' },
                 // { name: $translate.instant('InvoiceQJ'), width: '8%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.periodID}}<span></div>' },
                 { name: $translate.instant('SubjectName'),  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.subjectName}}<span></div>' },
                 { name: $translate.instant('RedLetterInvoiceInfoTableNum'),  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.redLetterInvoiceInfoTableNum}}</span></div>' },
                 { name: $translate.instant('FillInDate'),  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.fphm}}">{{row.entity.fillInDate | date:"yyyy-MM-dd"}}</span></div>' },
                 { name: $translate.instant('RedLetterInfoSalesTaxNum'),  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.xfsh}}">{{row.entity.salesTaxNumber}}</span></div>' },
                 { name: $translate.instant('SalespersonName'),  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.fplx}}">{{row.entity.salespersonName}}</span></div>' },
                 {
                     name: $translate.instant('RedLetterInfoTotalAmount'),
                     headerCellClass:'rightHeader',
                     cellTemplate: '<div class="ui-grid-cell-contents right"><span style="float:right">{{row.entity.totalAmount | number:2}}</span></div>'
                 },
                 {
                     name: $translate.instant('RedLetterInfoTotalTaxAmount'),
                     headerCellClass:'rightHeader',
                     cellTemplate: '<div class="ui-grid-cell-contents right"><span style="float:right">{{row.entity.totalTaxAmount | number:2}}</span></div>'
                 },
                 { name: $translate.instant('ApplicationSelectionDescription'),  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.applicationDescription}}</span></div>' },
                 { name: $translate.instant('ApplicantsManager'),  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.applicantManager }}</span></div>' },
                 { name: $translate.instant('InvoiceCode'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.invoiceCode}}</span></div>' },
                 { name: $translate.instant('RedLetterInfoInvoiceNum'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.invoiceNumber}}</span></div>' }
                 ]
            };

            $scope.doDataFilterReset = doDataFilterReset;
            $scope.showPopover = showPopover;
            $scope.downloadRLIT = downloadRLIT;

            initPeriods();
            initRedLetterInfoTabItemPagination();
            //初始化查询条件-期间范围
            if($rootScope.currentLanguage === 'en-us'){
                $('.periodInput')[0].style.left = "350px";
            }else{
                $('.periodInput')[0].style.left = "150px";
            }
            $scope.queryParams.periodStart = vatSessionService.year * 100 + vatSessionService.month;
            $scope.queryParams.periodEnd = vatSessionService.year * 100 + vatSessionService.month;
            $scope.queryParams.orgId = vatSessionService.project.organizationID;
            // countTotal();
            loadRedLetterInfoTabItemDataFromDB(1);

        })();
    }
]);