vatModule.controller('VatPreviewDirectMethodCashFlowStatementController', ['$scope', '$log', '$translate', '$timeout', 'SweetAlert', '$q', 'uiGridConstants', '$interval', 'vatPreviewService', 'browserService', 'vatSessionService', 'region', 'enums', 'vatExportService',
    function ($scope, $log, $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]];

        //发票类型
        var invoiceTypeEnum = {
            VATInvoice: $translate.instant('VATInvoice'),
            FreightTransport: $translate.instant('FreightTransport'),
            MotorVehicle: $translate.instant('MotorVehicle'),
            AgriculturalProduct: $translate.instant('AgriculturalProduct')
        };

        $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.cetificationResultList = [
            { id: 999, name: $translate.instant('AllTheItems') },
            { id: 1, name: $translate.instant('CertificationPass') },
            { id: 2, name: $translate.instant('CertificationNotPass') }
        ];

        //发票类型
        $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: '',
                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 loadIncomeInvoiceItemDataFromDB = function (pageIndex) {
            initIncomeInvoiceItemPagination();

            $scope.curIncomeInvoiceItemPage = pageIndex;

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


            vatPreviewService.queryInputInvoiceList($scope.queryParams).success(function (data) {
                if (data) {
                    // minDate = data.
                    var index = 1;
                    data.list.forEach(function (v) {
                        v.index = index++;
                        v.amount = PWC.round(parseFloat(v.hjje.replace(/,/g, "")), 2);
                        v.taxAmount = PWC.round(parseFloat(v.hjse.replace(/,/g, "")), 2);
                    });
                    $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 / $scope.pageSize);
                totalPage = $scope.queryIncomeInvoiceItemResult.pageInfo.totalCount % $scope.pageSize == 0 ? totalPage : totalPage + 1;

                //计算本页记录数
                if ($scope.queryIncomeInvoiceItemResult.pageInfo.pageNum === totalPage) {
                    $scope.curPageItemCount = $scope.queryIncomeInvoiceItemResult.pageInfo.total % $scope.pageSize;
                }
                else {
                    $scope.curPageItemCount = $scope.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;
        };

        //将选择了的查询条件显示在grid上方
        var doDataFilter = function (removeData) {
            if ($scope.queryParams.periodStart > $scope.queryParams.periodEnd) {
                $scope.queryParams.periodEnd = $scope.queryParams.periodStart;
            }

            //设置需要去掉的查询条件的值为空
            if (!PWC.isNullOrEmpty(removeData)) {
                var removeItem = removeData.split("|");
                removeItem.forEach(function (v) {
                    $scope.queryParams[v] = null;

                    //如果去掉了发票代码的查询条件,则将查询条件设置为'',因为是字符串,设置为null会导致查询结果错误
                    if ($scope.queryParams.invoiceCode === null) {
                        $scope.queryParams.invoiceCode = '';
                    }
                    //如果去掉了发票号码的查询条件,则将查询条件设置为'',因为是字符串,设置为null会导致查询结果错误
                    if ($scope.queryParams.invoiceNumber === null) {
                        $scope.queryParams.invoiceNumber = '';
                    }
                    //如果去掉了供货方税号的查询条件,则将查询条件设置为'',因为是字符串,设置为null会导致查询结果错误
                    if ($scope.queryParams.sellerTaxNumber === null) {
                        $scope.queryParams.sellerTaxNumber = '';
                    }


                    if ($scope.queryParams.invoiceType === null) {
                        $scope.InvoiceType.selected = undefined;
                    }

                    if ($scope.queryParams.certificationStatus === null) {
                        $scope.CertificationStatus.selected = undefined;
                    }
                });
            }

            //设置发票类型和认证结果
            if ($scope.InvoiceType.selected !== undefined)
                $scope.queryParams.invoiceType = $scope.InvoiceType.selected.id;
            else
                $scope.queryParams.invoiceType = null;
            if ($scope.CertificationStatus.selected !== undefined)
                $scope.queryParams.certificationStatus = $scope.CertificationStatus.selected.id;
            else
                $scope.queryParams.certificationStatus = null;

            // 将查询条件加入到grid上方
            var crits = $scope.queryParams;

            //定义查询条件数组用于存放已选的查询条件
            $scope.criteriaList = [];

            var crit = [];

            //认证日期
            if (!PWC.isNullOrEmpty(crits.certificationDateStart) && !PWC.isNullOrEmpty(crits.certificationDateEnd)) {
                if (new Date(crits.certificationDateStart.replace(/[\.-]/g, '/')) > new Date(crits.certificationDateEnd.replace(/[\.-]/g, '/'))) {
                    $scope.criteriaList = [];
                    SweetAlert.warning($translate.instant('InvoiceDateQueryError'));
                    return;
                }
                crit = new Object;
                crit.name = $translate.instant('InvoiceRZRQQuery') + crits.certificationDateStart + "-" + crits.certificationDateEnd;;
                crit.fullName = $translate.instant('InvoiceRZRQQuery') + crits.certificationDateStart + "-" + crits.certificationDateEnd;
                crit.valueFrom = crits.certificationDateStart;
                crit.valueTo = crits.certificationDateEnd;
                crit.propertyName = "certificationDateStart|certificationDateEnd";

                $scope.criteriaList.push(crit);
            } else if (!PWC.isNullOrEmpty(crits.certificationDateStart) && PWC.isNullOrEmpty(crits.invoiceDateEnd)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceRZRQQuery') + crits.certificationDateStart + $translate.instant('After');
                crit.fullName = $translate.instant('InvoiceRZRQQuery') + crits.certificationDateStart + $translate.instant('After');
                crit.valueFrom = crits.certificationDateStart;
                crit.valueTo = crits.certificationDateEnd;
                crit.propertyName = "certificationDateStart|certificationDateEnd";

                $scope.criteriaList.push(crit);
            }
            else if (PWC.isNullOrEmpty(crits.certificationDateStart) && !PWC.isNullOrEmpty(crits.certificationDateEnd)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceRZRQQuery') + crits.certificationDateEnd + $translate.instant('Before');
                crit.fullName = $translate.instant('InvoiceRZRQQuery') + crits.certificationDateEnd + $translate.instant('Before');
                crit.valueFrom = crits.certificationDateStart;
                crit.valueTo = crits.certificationDateEnd;
                crit.propertyName = "certificationDateStart|certificationDateEnd";
                $scope.criteriaList.push(crit);
            }


            //发票代码
            if (!PWC.isNullOrEmpty(crits.invoiceCode)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceFPDMQuery') + PWC.limitString(crits.invoiceCode, 10);
                crit.fullName = $translate.instant('InvoiceFPDMQuery') + crits.invoiceCode;
                crit.valueFrom = crits.invoiceCode;
                crit.propertyName = "invoiceCode";

                $scope.criteriaList.push(crit);
            }

            //发票号码
            if (!PWC.isNullOrEmpty(crits.invoiceNumber)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceFPHMQuery') + PWC.limitString(crits.invoiceNumber, 10);
                crit.fullName = $translate.instant('InvoiceFPHMQuery') + crits.invoiceNumber;
                crit.valueFrom = crits.invoiceNumber;
                crit.propertyName = "invoiceNumber";

                $scope.criteriaList.push(crit);
            }

            //销方识别号
            if (!PWC.isNullOrEmpty(crits.sellerTaxNumber)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceGHFSHQuery') + PWC.limitString(crits.sellerTaxNumber, 10);
                crit.fullName = $translate.instant('InvoiceGHFSHQuery') + crits.sellerTaxNumber;
                crit.valueFrom = crits.sellerTaxNumber;
                crit.propertyName = "sellerTaxNumber";

                $scope.criteriaList.push(crit);
            }

            //金额
            if (!PWC.isNullOrEmpty(crits.amountStart) && !PWC.isNullOrEmpty(crits.amountEnd)) {
                if (Number(crits.amountStart) > Number(crits.amountEnd)) {
                    SweetAlert.warning($translate.instant('AmountQueryError'));
                    return;
                }
                crit = new Object;
                crit.name = $translate.instant('InvoiceJEQuery') + PWC.limitString(crits.amountStart, 5) + ' - ' + PWC.limitString(crits.amountEnd, 5);
                crit.fullName = $translate.instant('InvoiceJEQuery') + crits.amountStart + ' - ' + crits.amountEnd;
                crit.valueFrom = crits.amountStart;
                crit.valueTo = crits.amountEnd;
                crit.propertyName = "amountStart|amountEnd";
                $scope.criteriaList.push(crit);
            }
            else if (!PWC.isNullOrEmpty(crits.amountStart) && PWC.isNullOrEmpty(crits.amountEnd)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceJEQuery') + PWC.limitString(crits.amountStart, 5) + $translate.instant('MoreThan');
                crit.fullName = $translate.instant('InvoiceJEQuery') + crits.amountStart + $translate.instant('MoreThan');
                crit.valueFrom = crits.amountStart;
                crit.valueTo = crits.amountEnd;
                crit.propertyName = "amountStart|amountEnd";
                $scope.criteriaList.push(crit);
            }
            else if (PWC.isNullOrEmpty(crits.amountStart) && !PWC.isNullOrEmpty(crits.amountEnd)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceJEQuery') + PWC.limitString(crits.amountEnd, 5) + $translate.instant('LessThan');
                crit.fullName = $translate.instant('InvoiceJEQuery') + crits.amountEnd + $translate.instant('LessThan');
                crit.valueFrom = crits.amountStart;
                crit.valueTo = crits.amountEnd;
                crit.propertyName = "amountStart|amountEnd";
                $scope.criteriaList.push(crit);
            }


            //税额
            if (!PWC.isNullOrEmpty(crits.taxAmountStart) && !PWC.isNullOrEmpty(crits.taxAmountEnd)) {
                if (Number(crits.taxAmountStart) > Number(crits.taxAmountEnd)) {
                    SweetAlert.warning($translate.instant('TaxAmountQueryError'));
                    return;
                }
                crit = new Object;
                crit.name = $translate.instant('InvoiceSEQuery') + PWC.limitString(crits.taxAmountStart, 5) + ' - ' + PWC.limitString(crits.taxAmountEnd, 5);
                crit.fullName = $translate.instant('InvoiceSEQuery') + crits.taxAmountStart + ' - ' + crits.taxAmountEnd;
                crit.valueFrom = crits.taxAmountStart;
                crit.valueTo = crits.taxAmountEnd;
                crit.propertyName = "taxAmountStart|taxAmountEnd";

                $scope.criteriaList.push(crit);
            }
            else if (!PWC.isNullOrEmpty(crits.taxAmountStart) && PWC.isNullOrEmpty(crits.taxAmountEnd)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceSEQuery') + PWC.limitString(crits.taxAmountStart, 5) + $translate.instant('MoreThan');
                crit.fullName = $translate.instant('InvoiceSEQuery') + crits.taxAmountStart + $translate.instant('MoreThan');
                crit.valueFrom = crits.taxAmountStart;
                crit.valueTo = crits.taxAmountEnd;
                crit.propertyName = "taxAmountStart|taxAmountEnd";

                $scope.criteriaList.push(crit);
            }
            else if (PWC.isNullOrEmpty(crits.taxAmountStart) && !PWC.isNullOrEmpty(crits.taxAmountEnd)) {
                crit = new Object;
                crit.name = $translate.instant('InvoiceSEQuery') + PWC.limitString(crits.taxAmountEnd, 5) + $translate.instant('LessThan');
                crit.fullName = $translate.instant('InvoiceSEQuery') + crits.taxAmountEnd + $translate.instant('LessThan');
                crit.valueFrom = crits.taxAmountStart;
                crit.valueTo = crits.taxAmountEnd;
                crit.propertyName = "taxAmountStart|taxAmountEnd";

                $scope.criteriaList.push(crit);
            }

            //发票类型
            if (!PWC.isNullOrEmpty(crits.invoiceType)) {
                crit = new Object;
                crit.valueFrom = _.find($scope.invoiceTypeList, function (v) {
                    return v.id === crits.invoiceType;
                }).name;

                crit.name = $translate.instant('InvoiceFPLXQuery') + crit.valueFrom;
                crit.fullName = $translate.instant('InvoiceFPLXQuery') + crit.valueFrom;
                crit.propertyName = "invoiceType";

                $scope.criteriaList.push(crit);
            }

            //认证结果
            if (!PWC.isNullOrEmpty(crits.certificationStatus)) {
                crit = new Object;
                crit.valueFrom = _.find($scope.cetificationResultList, function (v) {
                    return v.id === crits.certificationStatus;
                }).name;
                crit.name = $translate.instant('InvoiceRZJGQuery') + crit.valueFrom;
                crit.fullName = $translate.instant('InvoiceRZJGQuery') + crit.valueFrom;
                crit.propertyName = "certificationStatus";

                $scope.criteriaList.push(crit);
            }

            // add to Criteria List for display on top of the grid:
            //********************************************************************************

            var criteria = JSON.stringify($scope.queryParams);
            if (browserService.isIE() || browserService.isEdge())
                criteria = encodeURIComponent(criteria);
            countTotal();
            loadIncomeInvoiceItemDataFromDB(1);
            if ($scope.criteriaList.length > 6) {
                $scope.criteriaListFirstRow = $scope.criteriaList.slice(0, 6);
                $scope.criteriaListSecondRow = $scope.criteriaList.slice(6, $scope.criteriaList.length);
            }
            else {
                $scope.criteriaListFirstRow = $scope.criteriaList.slice(0, $scope.criteriaList.length);
            }
            $('.filter-button').popover("hide");
        };

        //去掉所有的查询条件,重新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();
            loadIncomeInvoiceItemDataFromDB(1);
            $('.filter-button').popover("hide");
        };

        var prepareSummary = function () {
            // do something before show popover
        };

        //在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.typeToString = function (strType) {
            var type = invoiceTypeEnum.VATInvoice;
            switch (strType) {
                case 1:
                    type = invoiceTypeEnum.VATInvoice;
                    break;
                case 2:
                    type = invoiceTypeEnum.FreightTransport;
                    break;
                case 3:
                    type = invoiceTypeEnum.MotorVehicle;
                    break;
                case 4:
                    type = invoiceTypeEnum.AgriculturalProduct;
                    break;
                default:
                    type = "";
            }
            return type;
        };

        //导出进项发票数据
        var downloadInputInvoice = function () {
            vatPreviewService.getExportInputInvoiceList($scope.queryParams).success(function (data, status, headers) {
                if(status===204){
                    SweetAlert.warning("没有数据可以下载");
                    return;
                }
                vatExportService.exportToExcel(data, status, headers, '进项发票信息');
            });
        };


        (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 = startMonth;
                 $scope.queryParams.periodEnd = endMonth;
                 countTotal();
                 loadIncomeInvoiceItemDataFromDB(1);
             });


            $scope.gridOptions = {
                rowHeight: constant.UIGrid.rowHeight,
                selectionRowHeaderWidth: constant.UIGrid.rowHeight,
                expandableRowTemplate: '<div ui-grid="row.entity.subGridOptions" style="height:150px;"></div>',
                virtualizationThreshold: 50,//默认加载50条数据,避免在数据展示时,只显示前面4条
                enableSorting: false,
                enableColumnMenus: false,
                columnDefs: [
                 { name: $translate.instant('VatInvoiceRecordNoCol'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.index}}<span></div>' },
                 // { name: $translate.instant('InvoiceQJ'), width: '8%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.periodID}}<span></div>' },
                 { name: $translate.instant('BillingBody'),  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.kprq | date:"yyyy-MM-dd"}}<span></div>' },
                 { name: $translate.instant('CustomerCompanyName'),  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.fpdm}}">{{row.entity.fpdm}}</span></div>' },
                 { name: $translate.instant('RecordInvoiceType'),  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.fphm}}">{{row.entity.fphm}}</span></div>' },
                 { name: $translate.instant('RecordBillingContent'),  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.xfsh}}">{{row.entity.xfsh}}</span></div>' },
                 { name: $translate.instant('InvoiceAmount'),  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.fplx}}">增值税专票</span></div>' },
                 { name: $translate.instant('Applicant'), cellTemplate: '<div class="ui-grid-cell-contents right"><span style="float:right">{{row.entity.hjje}}</span></div>' },
                 { name: $translate.instant('OAApplicationNum'), cellTemplate: '<div class="ui-grid-cell-contents right"><span style="float:right">{{row.entity.hjse}}</span></div>' },
                 { name: $translate.instant('ContractNo'),  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzsj  | date:"yyyy-MM-dd"}}</span></div>' },
                 { name: $translate.instant('ContractAmount'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('Department'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('ApplicationDate'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('RecordBillingDate'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('BillingMonth'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('RecordInvoiceCode'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('RecordInvoiceNum'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('InvoiceNum'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('CustomerCompanyTaxNum'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('CustomerSourceSystem'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('RecordTaxRate'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('TaxAmount'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('InvoiceStatus'),cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('InvoiceSource'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' },
                 { name: $translate.instant('InvoiceRemarks'), cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.rzjg}}</span></div>' }
                 ],
                onRegisterApi: function (gridApi) {
                                   $scope.gridApi = gridApi;

                                   //定义子table属性
                                   gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
                                       if (row.isExpanded) {
                                           row.entity.subGridOptions = {
                                               rowHeight: constant.UIGrid.rowHeight,
                                               selectionRowHeaderWidth: constant.UIGrid.rowHeight,
                                               virtualizationThreshold: 50,//默认加载50条数据,避免在数据展示时,只显示前面4条
                                               enableSorting: false,
                                               enableColumnMenus: false,
                                               columnDefs: [
                                               // { name: $translate.instant('ImportErrorPopUpNoCol'), width: '10%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.index}}<span></div>' },
                                               { name: $translate.instant('InvoiceHWMC'), headerCellClass:'right', width: '20%', cellTemplate: '<div class="ui-grid-cell-contents"><span style="float:right" title="{{row.entity.spmc}}">{{row.entity.spmc}}<span></div>' },
                                               { name: $translate.instant('InvoiceJE'), headerCellClass:'right', width: '13%', cellTemplate: '<div class="ui-grid-cell-contents"><span style="float:right">{{row.entity.je}}<span></div>' },
                                               { name: $translate.instant('InvoiceSL'), headerCellClass:'right', width: '13%', cellTemplate: '<div class="ui-grid-cell-contents"><span style="float:right">{{row.entity.slv}}%<span></div>' },
                                               { name: $translate.instant('InvoiceSE'), headerCellClass:'right', width: '13%', cellTemplate: '<div class="ui-grid-cell-contents"><span style="float:right">{{row.entity.se}}<span></div>' }
                                               ]
                                           };

                                           //获取子table数据
                                           vatPreviewService.queryInputInvoiceItemList(row.entity.id).success(function (data) {
                                               if (data) {
                                                   var index = 1;
                                                   data.forEach(function (v) {
                                                       v.index = index++;
                                                       v.je = PWC.round(v.je, 2);
                                                       v.se = PWC.round(v.se, 2);
                                                   });
                                                   row.entity.subGridOptions.data = data;
                                               }
                                           });
                                       }
                                   });

                    $interval(function () {
                        $scope.gridApi.core.handleWindowResize();
                    }, 500, 60 * 60 * 8);
                }
            };

            $scope.doDataFilter = doDataFilter;
            $scope.doDataFilterReset = doDataFilterReset;
            $scope.prepareSummary = prepareSummary;
            $scope.showPopover = showPopover;
            $scope.downloadInputInvoice = downloadInputInvoice;

            initPeriods();
            initIncomeInvoiceItemPagination();
            //初始化查询条件-期间范围
            $scope.queryParams.periodStart = vatSessionService.month;
            $scope.queryParams.periodEnd = vatSessionService.month;
            countTotal();
            loadIncomeInvoiceItemDataFromDB(1);

        })();
    }
]);