vatModule.controller('vatPreviewOutputoffInvoiceController', ['$scope', '$log', '$translate', '$timeout', 'SweetAlert', '$q', 'uiGridConstants', '$interval', 'vatPreviewService', 'vatSessionService', 'browserService', 'enums','region','vatExportService',
    function ($scope, $log, $translate, $timeout, SweetAlert, $q, uiGridConstants, $interval, vatPreviewService, vatSessionService, browserService, enums, region, 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.curPageItemCount = 0;
        $scope.totalMoneyAmount = 0;
        $scope.totalTaxAmount = 0;
        var startMonth = vatSessionService.month;
        var endMonth = vatSessionService.month;
        var minDate = [1, vatSessionService.project.year];
        var maxDate = [12, vatSessionService.project.year];
        var setDate = [
            [vatSessionService.month, vatSessionService.project.year],
            [vatSessionService.month, vatSessionService.project.year]];
        //发票类型
        var invoiceTypeEnum = {
            Normal: $translate.instant('Normal'),
            Special:  $translate.instant('Special'),
            ElectronicReceipt:  '电子发票'
        };
        //区间
        $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.outputInvoiceType.Normal, name: $translate.instant('Normal') },
            { id: enums.outputInvoiceType.Special, name: $translate.instant('Special') },
        ];

        $scope.PeriodStart = {};
        $scope.PeriodEnd = {};
        $scope.InvoiceType = {};

        //初始化期间
        var initPeriods = function () {
            $scope.queryParams = {
                pageInfo: {},
                periodStart: '',
                periodEnd: '',
                invoiceDateStart: null,
                invoiceDateEnd: null,
                classCode: '',
                invoiceNumber: '',
                buyerName: '',
                productName:'',
                amountStart: null,
                amountEnd: null,
                invoiceType: null,
                taxAmountStart: null,
                taxAmountEnd: null,
                tag: 'off'
            };
            $scope.queryParams.periodStart = vatSessionService.month;
            $scope.queryParams.periodEnd = vatSessionService.month;
        };

        var countTotal = function(){
            var totalMoneyAmount = 0;
            var totalTaxAmount = 0;
            vatPreviewService.queryOutputInvoiceAllList($scope.queryParams).success(function (data) {
                if (data) {
                    _.each(data, function (x) {
                        totalMoneyAmount += parseFloat(x.hjje.replace(/,/g, ""));
                        totalTaxAmount += parseFloat(x.hjse.replace(/,/g, ""));
                    })
                }
                $scope.totalMoneyAmount = totalMoneyAmount.toLocaleString();
                $scope.totalTaxAmount = totalTaxAmount.toLocaleString();
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        }

        //从数据库中load数据
        var loadOutputInvoiceDataFromDB = function (pageIndex) {
            initOutputInvoicePagination();

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



            vatPreviewService.queryOutputInvoiceList($scope.queryParams).success(function (data) {
                if (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.queryOutputInvoiceResult.pageInfo = data;
                    computeOutputInvoiceItemPage();
                    countTotal();
                }
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        }

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

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

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

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

                if ($scope.queryOutputInvoiceResult.pageInfo.pageNum === totalPage) {
                    $scope.curPageItemCount = $scope.queryOutputInvoiceResult.pageInfo.total % $scope.queryOutputInvoiceResult.pageInfo.pageSize;
                }
                else {
                    $scope.curPageItemCount = $scope.queryOutputInvoiceResult.pageInfo.pageSize;
                }

                $scope.queryOutputInvoiceResult.pageInfo.totalPage = totalPage;

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

                $('#totalInvoicePage').css('display', 'inline-block');
            } else {
                var createPage = $("#totalInvoicePage").createPage({
                    pageCount: 0,
                    current: $scope.curOutputInvoiceItemPage,
                    backFn: function (p) {
                        //单击回调方法,p是当前页码
                        loadOutputInvoiceDataByPage(p);
                    }
                });
                $scope.curPageItemCount = 0;
                $('#totalInvoicePage').css('display', 'inline-block');
            }
        };


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

        //发票类型转换'发票类型代码 004专票007普票026电子发票'
        $scope.typeToString = function (strType) {
            var type = invoiceTypeEnum.Normal;
            switch (strType) {
                case '007':
                    type = invoiceTypeEnum.Normal;
                    break;
                case '004':
                    type = invoiceTypeEnum.Special;
                    break;
                case '026':
                    type = invoiceTypeEnum.ElectronicReceipt;
                    break;
                default:
                    type = "";
            }
            return type;
        }

        //将选择了的查询条件显示在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;

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

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

            // 将查询条件加入到grid上方
            var crits = $scope.queryParams;
            //定义查询条件数组用于存放已选的查询条件
            $scope.criteriaList = [];

            var crit = [];

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

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

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

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

                $scope.criteriaList.push(crit);
            }

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

                $scope.criteriaList.push(crit);
            }

            //购方名称
            if (!PWC.isNullOrEmpty(crits.buyerName)) {
                crit = new Object;
                crit.name = $translate.instant('BuyerName') + ":" + PWC.limitString(crits.buyerName, 10);
                crit.valueFrom = crits.buyerName;
                crit.propertyName = "buyerName";

                $scope.criteriaList.push(crit);
            }

            //产品名称
            if (!PWC.isNullOrEmpty(crits.productName)) {
                crit = new Object;
                crit.name = $translate.instant('ProductName') + ":" + PWC.limitString(crits.productName, 10);
                crit.valueFrom = crits.productName;
                crit.propertyName = "productName";

                $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('InvoiceType') + ":" + crit.valueFrom;
                crit.propertyName = "invoiceType";

                $scope.criteriaList.push(crit);
            }

            //金额
            if (!PWC.isNullOrEmpty(crits.amountStart) && !PWC.isNullOrEmpty(crits.amountEnd)) {
                if (Number(crits.amountStart) > Number(crits.amountEnd)) {
                    $scope.criteriaList = [];
                    SweetAlert.warning($translate.instant('AmountQueryError'));
                    return;
                }
                crit = new Object;
                crit.name = $translate.instant('Amount') + ":" + PWC.limitString(crits.amountStart, 5) + "-" + PWC.limitString(crits.amountEnd, 5);
                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('Amount') + ":" + PWC.limitString(crits.amountStart, 5) + $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('Amount') + ":" + PWC.limitString(crits.amountEnd, 5) + $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)) {
                    $scope.criteriaList = [];
                    SweetAlert.warning($translate.instant('TaxAmountQueryError'));
                    return;
                }
                crit = new Object;
                crit.name = $translate.instant('TaxAmount') + ":" + PWC.limitString(crits.taxAmountStart, 5) + "-" + PWC.limitString(crits.taxAmountEnd, 5);
                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('TaxAmount') + ":" + PWC.limitString(crits.taxAmountStart, 5) + $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('TaxAmount') + ":" + PWC.limitString(crits.taxAmountEnd, 5) + $translate.instant('LessThan');
                crit.valueFrom = crits.taxAmountStart;
                crit.valueTo = crits.taxAmountEnd;
                crit.propertyName = "taxAmountStart|taxAmountEnd";

                $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();
            loadOutputInvoiceDataFromDB(1);
            $('.filter-button').popover("hide");
        };

        //去掉所有的查询条件,重新load数据
        var doDataFilterReset = function () {
            $scope.queryParams = {
                pageInfo: {},
                periodStart: '',
                periodEnd: '',
                invoiceDateStart: null,
                invoiceDateEnd: null,
                classCode: '',
                invoiceNumber: '',
                buyerName: '',
                productName: '',
                amountStart: null,
                amountEnd: null,
                invoiceType: null,
                taxAmountStart: null,
                taxAmountEnd: null,
                tag: 'off'
            };
            $scope.criteriaList = [];
            $scope.queryParams.periodStart = startMonth;
            $scope.queryParams.periodEnd = endMonth;
            countTotal();
            loadOutputInvoiceDataFromDB(1);
            $('.filter-button').popover("hide");
        };

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

        //初始化时间控件
        var initDatePickers = function () {
            //开票开始时间
            var ele1 = $("#invoiceDateStart");
            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.invoiceDateStart);
            //开票结束时间
            var ele2 = $("#invoiceDateEnd");
            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.invoiceDateEnd);


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

        //转换百分比
        $scope.decimalToPercent = function (data) {
            return (data * 100).toFixed(0) + "%";
        }

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

        //$scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
        //    export_table_to_excel('exportTable', 'OutputInvoice', 'xlsx', '');
        //});

        $scope.gridOptionsColumnDefs = [
            {
                name: $translate.instant('ImportErrorPopUpNoCol'), width: '5%',
                cellTemplate: '<div class="ui-grid-cell-contents" ><span>{{row.entity.index}}<span></div>'
            },
              // {
              //     name: $translate.instant('PeriodId'), width: '5%',
              //     cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.periodID}}"><span>{{row.entity.periodID}}<span></div>'
              // },
               {
                   name: $translate.instant('InvoiceDate'), width: '10%',
                   cellTemplate: '<div class="ui-grid-cell-contents" ><span>{{row.entity.kprq | date:"yyyy-MM-dd"}}</span></div>'
               },
                 {
                     name: $translate.instant('InvoiceType'), width: '10%',
                     cellTemplate: '<div class="ui-grid-cell-contents" title="{{grid.appScope.typeToString(row.entity.fplxdm)}}"><span>{{grid.appScope.typeToString(row.entity.fplxdm)}}<span></div>'
                 },
              {
                  name: $translate.instant('ClassCode'), width: '10%',
                  cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.fpdm}}"><span>{{row.entity.fpdm}}<span></div>'
              },
              {
                  name: $translate.instant('InvoiceNumber'), width: '10%',
                  cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.fphm}}"><span>{{row.entity.fphm}}</span></div>'
              },
              {
                  name: $translate.instant('BuyerName'), width: '18%',
                  cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.gfmc}}"><span>{{row.entity.gfmc}}</span></div>'
              },
              {
                  name: $translate.instant('BuyerTaxNumber'), width: '18%',
                  cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.gfsh}}"><span>{{row.entity.gfsh}}</span></div>'
              },
              //{
              //    name: $translate.instant('BankAccount'), width: '10%',
              //    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.bankAccount}}"><span>{{row.entity.bankAccount}}</span></div>'
              //},
              //{
              //    name: $translate.instant('PhoneNum'), width: '8%',
              //    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.phoneNum}}"><span>{{row.entity.phoneNum}}</span></div>'
              //},
           {
               name: $translate.instant('Amount'), width: '8%', headerCellClass: 'right',
               cellTemplate: '<div class="ui-grid-cell-contents right" title="{{row.entity.hjje}}"><span>{{row.entity.hjje}}</span></div>'
           },
            {
                name: $translate.instant('TaxAmount'), width: '8%', headerCellClass: 'right',
                cellTemplate: '<div class="ui-grid-cell-contents right"  title="{{row.entity.hjse}}"><span>{{row.entity.hjse}}</span></div>'
            }
        ];

        $scope.subGridOptionsColumnDefs = [
                // {
                // name: $translate.instant('ImportErrorPopUpNoCol'), width: '5%',
                //     cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.seqNo}}</span></div>'
                // },
                {
                    name: $translate.instant('ProductName'),
                    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.spmc}}"><span>{{row.entity.spmc}}</span></div>'
                },
                {
                    name: $translate.instant('Quantity'),   headerCellClass: 'right',
                    cellTemplate: '<div class="ui-grid-cell-contents right" title="{{row.entity.sl}}"><span>{{row.entity.sl}}</span></div>'
                },
                {
                    name: $translate.instant('UnitPrice'),   headerCellClass: 'right',
                    cellTemplate: '<div class="ui-grid-cell-contents right" title="{{row.entity.dj}}"><span>{{row.entity.dj}}</span></div>'
                },
                {
                    name: $translate.instant('Amount'),   headerCellClass: 'right',
                    cellTemplate: '<div class="ui-grid-cell-contents right" title="{{row.entity.je}}"><span>{{row.entity.je}}</span></div>'
                },
                {
                    name: $translate.instant('TaxRate'),  headerCellClass: 'right',
                    cellTemplate: '<div class="ui-grid-cell-contents right" title="{{row.entity.slv}}"><span>{{row.entity.slv * 100 + "%"}}</span></div>'
                },
                {
                    name: $translate.instant('TaxAmount'),  headerCellClass: 'right',
                    cellTemplate: '<div class="ui-grid-cell-contents right" title="{{row.entity.se}}"><span>{{row.entity.se}}</span></div>'
                },
             //{
             //    name: $translate.instant('CodeVersion'), width: '8%',
             //    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.codeVersion}}"><span>{{row.entity.codeVersion}}</span></div>'
             //},
             //{
             //    name: $translate.instant('DocumentNum'), width: '8%',
             //    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.documentNum}}"><span>{{row.entity.documentNum}}</span></div>'
             //},

             //{
             //    name: $translate.instant('ProductStandar'), width: '8%',
             //    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.productStandard}}"><span>{{row.entity.productStandard}}</span></div>'
             //},
             //{
             //    name: $translate.instant('Unit'), width: '8%',
             //    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.unit}}"><span>{{row.entity.unit}}</span></div>'
             //},
             //{
             //    name: $translate.instant('TaxClassCode'), width: '15%',
             //    cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.taxClassCode}}"><span>{{row.entity.taxClassCode}}</span></div>'
             //}
        ];

        (function initialize() {
            $log.debug('vatPreviewOutputoffInvoiceController.ctor()...');
            $scope.periodId = vatSessionService.month;

            //初始化month-picker
            $('#output-invoice-period-picker').rangePicker({
                minDate: minDate,
                maxDate: maxDate,
                setDate: setDate,
                months: $scope.monthList,
                ConfirmBtnText: $translate.instant('Confirm'),
                CancelBtnText: $translate.instant('ButtonCancel')
            })
             .on('datePicker.done', function (e, result) {
                 //开始月份
                 startMonth = result[0][0];
                 //结束月份
                 endMonth = result[1][0];
                 $scope.queryParams.periodStart = startMonth;
                 $scope.queryParams.periodEnd = endMonth;
                 countTotal();
                 loadOutputInvoiceDataFromDB(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: $scope.gridOptionsColumnDefs,

                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: $scope.subGridOptionsColumnDefs,
                            };
                            //获取子table数据
                            vatPreviewService.queryOutputInvoiceItemList(row.entity.id, 'off').success(function (data) {
                                if (data) {
                                    data.forEach(function (v) {
                                        v.dj = PWC.round(v.dj, 2);
                                        v.je = PWC.round(v.je, 2);
                                        v.slv = PWC.round(v.slv, 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.doExport = doExport;
            $scope.showPopover = showPopover;
            initPeriods();
            initOutputInvoicePagination();
            countTotal();
            loadOutputInvoiceDataFromDB(1);
        })();
    }
]);