vatModule.controller('VatPreviewCashFlowController', ['$rootScope','$scope', '$log', '$translate', '$timeout', 'SweetAlert', '$q', 'uiGridConstants', '$interval', 'vatPreviewService', 'browserService', 'vatSessionService', 'region', 'enums', 'vatExportService','$filter',
    function ($rootScope,$scope, $log, $translate, $timeout, SweetAlert, $q, uiGridConstants, $interval, vatPreviewService, browserService, vatSessionService, region, enums, vatExportService,$filter) {
        '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.ledgerNameFirst = '';
        $scope.ledgerCurrencyCodeFirst = '';
        $scope.ledgerStatusFirst = '';

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

        //发票类型
        $scope.invoiceTypeList = [
            { id: 999, name: $translate.instant('AllTheItems') },
            { id: enums.invoiceType.VATInvoice, name: $translate.instant('VATInvoice') },
            { id: enums.invoiceType.FreightTransport, name: $translate.instant('FreightTransport') },
            { id: enums.invoiceType.MotorVehicle, name: $translate.instant('MotorVehicle') },
            { id: enums.invoiceType.AgriculturalProduct, name: $translate.instant('AgriculturalProduct') }
        ];

        $scope.InvoiceType = {};
        $scope.CertificationStatus = {};

        //初始化期间
        var initPeriods = function () {
            var curMonth = new Date().getMonth() + 1;
            $scope.queryParams = {
                pageInfo: {},
                periodStart: '',
                periodEnd: '',
                orgId:''
            };
        };

        //从数据库中load数据
        var loadIncomeInvoiceItemDataFromDB = function (pageIndex) {
            initIncomeInvoiceItemPagination();

            $scope.curIncomeInvoiceItemPage = pageIndex;

            //初始化查询信息
            $scope.queryParams.pageInfo = {
                totalCount: $scope.queryIncomeInvoiceItemResult.pageInfo.total,
                pageIndex: pageIndex,
                pageSize: constant.pagesize,
                totalPage: 0,
            };

            vatPreviewService.getCFDataForDisplay($scope.queryParams).success(function (data) {
                if (data) {
                    if(data.list.length>0){
                        var itemFirst=data.list[0];
                        $scope.ledgerNameFirst = itemFirst.ledgerName;
                        $scope.ledgerCurrencyCodeFirst = itemFirst.ledgerCurrencyCode;
                        $scope.ledgerStatusFirst = itemFirst.status;
                    }
                    $scope.gridOptions.data = data.list;
                    $scope.queryIncomeInvoiceItemResult.pageInfo = data;
                    computeIncomeInvoiceItemPage();
                }
            });
        };

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

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

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

                var totalPage = parseInt($scope.queryIncomeInvoiceItemResult.pageInfo.total / constant.pagesize);
                totalPage = $scope.queryIncomeInvoiceItemResult.pageInfo.total % constant.pagesize == 0 ? totalPage : totalPage + 1;

                //计算本页记录数
                if ($scope.queryIncomeInvoiceItemResult.pageInfo.pageNum === totalPage) {
                    var pageItemCount=$scope.queryIncomeInvoiceItemResult.pageInfo.total % constant.pagesize;
                    $scope.curPageItemCount = pageItemCount == 0 ? constant.pagesize : pageItemCount;
                }
                else {
                    $scope.curPageItemCount = constant.pagesize;
                }

                $scope.queryIncomeInvoiceItemResult.pageInfo.totalPage = totalPage;

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

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

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

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

        //在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;
            })
        };

        //导出现金流量信息
        $scope.downloadCashFlow = function () {
            var localDate=$filter('date')(new  Date(), 'yyyyMMddHHmmss');
            var fileName="现金流量信息";
            vatPreviewService.initExportCFData($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][1] * 100 + result[0][0];
                 //结束月份
                 var endMonth = result[1][1] * 100 + result[1][0];
                 $scope.startMonth = startMonth;
                 $scope.endMonth = endMonth;

                 $scope.queryParams.periodStart = startMonth;
                 $scope.queryParams.periodEnd = endMonth;
                 loadIncomeInvoiceItemDataFromDB(1);
             });

            $scope.gridOptions = {
                rowHeight: constant.UIGrid.rowHeight,
                selectionRowHeaderWidth: constant.UIGrid.rowHeight,
                virtualizationThreshold: 50,//默认加载50条数据,避免在数据展示时,只显示前面4条
                enableSorting: false,
                enableColumnMenus: false,
                columnDefs: [
                 { name: $translate.instant('CashFlowEntry'), width: '32%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.itemName}}<span></div>' },
                 { name: $translate.instant('Item'), width: '38%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.itemName2}}<span></div>' },
                 {
                     name: $translate.instant('CurrentPeriodAmount'),
                     headerCellClass:'rightHeader',
                     width: '15%',
                     cellTemplate: '<div class="ui-grid-cell-contents" style="text-align: right"><span>{{row.entity.periodAmt | number:2}}<span></div>'
                 },
                 {
                     name: $translate.instant('ThisYearAccumulatedAmount'),
                     headerCellClass:'rightHeader',
                     width: '15%',
                     cellTemplate: '<div class="ui-grid-cell-contents" style="text-align: right"><span>{{row.entity.ytdAmt | number:2}}<span></div>'
                 }
                ]
            };

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

        })();
    }
]);