commonModule.controller('previewTrialBalanceController', ['$scope', '$log', '$translate', '$timeout', 'apiInterceptor', 'Upload', 'dataImportService', 'SweetAlert', '$q', 'uiGridConstants', 'projectService', 'uiGridGroupingConstants', 'vatImportService', 'i18nService', 'browserService', '$interval', 'region', 'citSessionService', 'enums', 'vatSessionService',
    function ($scope, $log, $translate, $timeout, apiInterceptor, Upload, dataImportService, SweetAlert, $q, uiGridConstants, projectService, uiGridGroupingConstants, vatImportService, i18nService, browserService, $interval, region, citSessionService, enums, vatSessionService) {
        'use strict';

        $scope.serviceType = $scope.project.serviceTypeID;       
        $scope.startDate = new Date($scope.project.year, 0, 1);
        $scope.endDate = new Date($scope.project.year, 11, 31);
        $scope.dateFormat = $translate.instant('dateFormat4YearMonthDay');
        $scope.isReadOnly = false;
        $scope.totalBegDebitBal = 0;
        $scope.totalBegCreditBal = 0;
        $scope.totalDebitBal = 0;
        $scope.totalCreditBal= 0;
        $scope.totalEndDebitBal = 0;
        $scope.totalEndCreditBal= 0;


        var minDate = [1, $scope.project.year];
        var maxDate = [12, $scope.project.year];
        var setDate = [
              [$scope.month, $scope.project.year],
              [$scope.month, $scope.project.year]];
       
        $scope.treeData = null;
        $scope.stupidData = null;
        $scope.isShowParentCodePop = false;
        $scope.isToClearSelection = false;

        $scope.isRunningTheFirstTime = true;
        $scope.isToPrint = false;
        $scope.switchedToCIT = false; 

        //Date range picker:
        // **********************************************************************
        $scope.filterDataCriteria = "";
        $scope.filterData = {
            periodFrom: $scope.month,
            periodTo: $scope.month,
            accountCode: null,
            accountName: null,
            debitOpeningBalanceFrom: null,
            debitOpeningBalanceTo: null,
            creditOpeningBalanceFrom: null,
            creditOpeningBalanceTo: null,
            accumulatedDebitAmountFrom: null,
            accumulatedDebitAmountTo: null,
            accumulatedCreditAmountFrom: null,
            accumulatedCreditAmountTo: null,
            debitClosingBalanceFrom: null,
            debitClosingBalanceTo: null,
            creditClosingBalanceFrom: null,
            creditClosingBalanceTo: null,
            hideAllZeroRecords: false
        };

        //CIT
        if ($scope.serviceType === '6') {
            $scope.isReadOnly = true;
            setDate = [[1, $scope.project.year], [12, $scope.project.year]];
            $scope.filterData.periodFrom = 1;
            $scope.filterData.periodTo = 12;
        }

        $scope.criteriaList = [];

        // current CATEGORY:

        $scope.categoryList = [{ id: 'CIT', name: $translate.instant('CITProject') }, {
            id: 'STD', name: $translate.instant('STANDARDProject')
        }];
        $scope.currentCategory = {
        };
        $scope.currentCategory.selected = {
            id: 'CIT', name: $translate.instant('CITProject')
        };


        $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.subtotals = {
            TitleName: '',
            BegDebitBal: '0.00',
            BegCreditBal: '0.00',
            EndDebitBal: '0.00',
            EndCreditBal: '0.00',
            YearDebitBal: '0.00',
            YearCreditBal: '0.00'
        }; 


        $scope.confirmCodes = function (confirmedRecords) {

            var codes = "";
            $scope.filterData.accountCode = "";
            confirmedRecords.forEach(function (item) {
                codes = codes + " " + item.subjectCode + " ";
            });

            $scope.filterData.accountCode = codes;
            $timeout(function () {
                $("#filterButton").click();
            }, 500);
        }

        $scope.cancelCodes = function () {
            $timeout(function () {
                $("#filterButton").click();
            }, 500);
        }
         
        //************ EXCEL EXPORT FUNCTION ***************/
        $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
            if ($scope.isToPrint)
                export_table_to_excel('exportTable', '试算平衡表', 'xlsx', '');
            $scope.isToPrint = false;
        });

        $scope.doExport = function (fileName, type, fn) {
            $scope.isToPrint = true;
            $scope.getDataFromDatabase($scope.currentCategory.selected.id, $scope.filterData.periodFrom, $scope.filterData.periodTo, $scope.filterDataCriteria, true);

        };

        $scope.queryGlBalance = function () {
            vatImportService.queryGlBalance($scope.filterData.periodFrom, $scope.filterData.periodTo, vatSessionService.project.organizationID)
                .success(function (res) {

                });
        };

        // function to get data from Backend
        $scope.getDataFromDatabase = function (category, from, to, criteria, isExportOnly) {
            vatImportService.getBalanceDataForDisplay(category, from, to, criteria, vatSessionService.project.organizationID).success(function (trialBalance) {
                var treeData = trialBalance;
                writeoutNode(treeData.list, 0, newTree);

                //check to see if user switch to STD subject:
                if ($scope.switchedToCIT && (!treeData || !treeData.length)) {
                    var selectedDisplaySubjectName = $translate.instant('SwitchToSTANDARDProject');
                    // give a  notice:
                    swal({ title: "", text: selectedDisplaySubjectName, type: "warning", confirmButtonText: "确定" });
                    $scope.switchedToCIT = false;
                }

                if (isExportOnly !== null && isExportOnly) {
                    $scope.exportDataList = newTree;
                    _.each($scope.exportDataList, function(exportData){
                        if(exportData.begDebitBal && parseFloat(exportData.begDebitBal.replace(/,/g, "")).toString() != "NaN") {
                            $scope.totalBegDebitBal += parseFloat(exportData.begDebitBal.replace(/,/g, ""));
                            exportData.begDebitBal = parseFloat(exportData.begDebitBal.replace(/,/g, "")).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                        }
                        if(exportData.begCreditBal && parseFloat(exportData.begCreditBal.replace(/,/g, "")).toString() != "NaN"){
                            $scope.totalBegCreditBal += parseFloat(exportData.begCreditBal.replace(/,/g, ""));
                            exportData.begCreditBal = parseFloat(exportData.begCreditBal.replace(/,/g, "")).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                        }
                        if(exportData.debitBal && parseFloat(exportData.debitBal.replace(/,/g, "")).toString() != "NaN"){
                            $scope.totalDebitBal += parseFloat(exportData.debitBal.replace(/,/g, ""));
                            exportData.debitBal = parseFloat(exportData.debitBal.replace(/,/g, "")).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                        }
                        if(exportData.creditBal && parseFloat(exportData.creditBal.replace(/,/g, "")).toString() != "NaN") {
                            $scope.totalCreditBal += parseFloat(exportData.creditBal.replace(/,/g, ""));
                            exportData.creditBal = parseFloat(exportData.creditBal.replace(/,/g, "")).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                        }
                        if(exportData.endDebitBal && parseFloat(exportData.endDebitBal.replace(/,/g, "")).toString() != "NaN") {
                            $scope.totalEndDebitBal += parseFloat(exportData.endDebitBal.replace(/,/g, ""));
                            exportData.endDebitBal = parseFloat(exportData.endDebitBal.replace(/,/g, "")).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                        }
                        if(exportData.endCreditBal && parseFloat(exportData.endCreditBal.replace(/,/g, "")).toString() != "NaN") {
                            $scope.totalEndCreditBal += parseFloat(exportData.endCreditBal.replace(/,/g, ""));
                            exportData.endCreditBal = parseFloat(exportData.endCreditBal.replace(/,/g, "")).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                        }
                    });
                    $scope.totalEndCreditBal = $scope.totalEndCreditBal.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                    $scope.totalEndDebitBal = $scope.totalEndDebitBal.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                    $scope.totalCreditBal = $scope.totalCreditBal.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                    $scope.totalDebitBal = $scope.totalDebitBal.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                    $scope.totalBegCreditBal = $scope.totalBegCreditBal.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                    $scope.totalBegDebitBal = $scope.totalBegDebitBal.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                }
                else {
                    $scope.gridOptions.data = newTree;

                    //populate standard parents code:
                    if ($scope.isRunningTheFirstTime) {

                        var formedNewTree;
                        var formedNewTrees = [];
                        var debit = $translate.instant('AccountVoucher_Direction_Debit'), credit = $translate.instant('AccountVoucher_Direction_Credit');

                        newTree.forEach(function (item) {
                            formedNewTree = new Object();
                            formedNewTree.$$treeLevel = item.$$treeLevel;
                            formedNewTree.subjectCode = item.accountCode;
                            formedNewTree.subjectName = item.accountName;
                            formedNewTree.acctProp = item.acctProp;
                            formedNewTree.direction = item.direction === "1" ? debit : credit;

                            formedNewTrees.push(formedNewTree);
                        });
                        $scope.stupidData = formedNewTrees;

                        $scope.isRunningTheFirstTime = false;
                    }


                    newTree = [];

                    if (treeData && treeData.calculateData) {
                        treeData.calculateData.TitleName = $translate.instant('Total');
                        $scope.subtotals = treeData.calculateData;
                        var tmp = parseInt($scope.subtotals.begDebitBal.replace(/\,/g, '')) - parseInt($scope.subtotals.begCreditBal.replace(/\,/g, ''))
                            + parseInt($scope.subtotals.debitBal.replace(/\,/g, '')) - parseInt($scope.subtotals.creditBal.replace(/\,/g, ''))
                            - parseInt($scope.subtotals.endDebitBal.replace(/\,/g, '')) + parseInt($scope.subtotals.endCreditBal.replace(/\,/g, ''));
                        if (0 !== tmp) {
                            swal({
                                title: $translate.instant('WarningTitle'),
                                text: '试算平衡表金额不平衡!差异:' + tmp,
                                type: "warning",
                                confirmButtonText: $translate.instant('Confirm')
                            });
                        }
                    }

                    $('.filter-button').popover("hide");
                    setTimeout(function () {
                        SetUiGridHeader();
                    }, 900);
                }
                $scope.isToClearSelection = false;
            });
        };
         
        // Write UI GRID TREE NOTES:
        var newTree = [];
        var id = "0";
        var writeoutNode = function (childArray, currentLevel, dataArray) {
            childArray.forEach(function (childNode) {
                if (childNode.children.length > 0) {
                    childNode.$$treeLevel = currentLevel;
                    id = childNode.accountCode;
                }
                else {
                    childNode.$$treeLevel = currentLevel;
                }
                dataArray.push(childNode);
                writeoutNode(childNode.children, currentLevel + 1, dataArray);
            });
        }; 
        //************************EXCEL EXPORT FUNCTION **********************************
        
        $scope.initGridOption = function () {
            
            $scope.gridOptions = {
                rowHeight: 50,
                showGridFooter: false,
                showColumnFooter: true,
                selectionRowHeaderWidth: 50,
                enableFullRowSelection: false,
                enableRowSelection: false,
                enableSorting: false,
                enableFiltering: false,
                enableColumnMenus: false,
                enableRowHeaderSelection: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                showTreeExpandNoChildren: false,
                enableGridMenu: false,
                enableSelectAll: false,
                //exporterLinkLabel: 'get it here',
                //exporterCsvFilename: 'GL.csv',
                exporterOlderExcelCompatibility: true,
                virtualizationThreshold: 50,
                exporterHeaderFilter: function (displayName) {
                    var headerName = "";

                    if (displayName === $translate.instant('Debitor'))
                        headerName = $translate.instant('DebitOpeningBalance');

                    else if (displayName === $translate.instant('Creditor'))
                        headerName = $translate.instant('CreditOpeningBalance');

                    else if (displayName === $translate.instant('Debitor') + ' ')
                        headerName = $translate.instant('AccumulatedDebitAmount');

                    else if (displayName === $translate.instant('Creditor') + ' ')
                        headerName = $translate.instant('AccumulatedCreditAmount');

                    else if (displayName === $translate.instant('Debitor') + '  ')
                        headerName = $translate.instant('DebitClosingBalance');

                    else if (displayName === $translate.instant('Creditor') + '  ')
                        headerName = $translate.instant('CreditClosingBalance');

                    else
                        headerName = displayName;

                    return headerName;
                },
                exporterHeaderFilterUseName: true,
                exportCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
                onRegisterApi: function (gridApi) {
                    //$scope.gridApi = gridApi;

                    $scope.gridApiTotal = gridApi;
                    //$timeout(function () {
                    //    $scope.gridApiTotal.core.handleWindowResize();
                    //});

                    var counterx = 1;
                    $interval(function () {
                        if (counterx === 1) {
                            $scope.gridApiTotal.core.handleWindowResize();
                            counterx++;
                        }
                    }, 500, 60 * 60 * 8);
                },

                columnDefs: [
                {
                    field: 'acctCode', name: $translate.instant('AccountCode'), headerCellClass: 'dataColumn1',
                    cellTemplate:
                    '<div ng-if="row.entity.$$treeLevel==0" class=""><span>{{row.entity.acctCode}}<span></div>' +
                              '<div ng-if="row.entity.$$treeLevel==1" class="text-align-left-padding"><span>&nbsp;&nbsp;{{row.entity.acctCode}}<span></div>' +
                              '<div ng-if="row.entity.$$treeLevel==2" class="text-align-left-padding"><span>&nbsp;&nbsp;&nbsp;&nbsp;{{row.entity.acctCode}}<span></div>' +
                '<div ng-if="row.entity.$$treeLevel==3" class="text-align-left-padding"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{row.entity.acctCode}}<span></div>' +
        '<div ng-if="row.entity.$$treeLevel==4" class="text-align-left-padding"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{row.entity.acctCode}}<span></div>'
                },
                {
                    field: 'accountName', width: 200, name: $translate.instant('AccountName'), headerCellClass: 'dataColumn2',

                    cellTemplate: '<div class=""><span>{{row.entity.accountName}}<span></div>'

                , footerCellTemplate: '<div class=" alignRight margin-right5 margin-top5" >合计: </div>'
                },

                {
                    field: 'begDebitBal', name: $translate.instant('Debitor'), headerCellClass: 'alignCenter dataColumn3',

                    cellTemplate: '<div class="alignRight margin-right5"><span>{{row.entity.begDebitBal || "0.00"}}</span></div>'
                , footerCellTemplate: '<div class=" alignRight margin-right5 margin-top5" >{{grid.appScope.subtotals.begDebitBal || "0.00"}}</div>'
                },

                {
                    field: 'begCreditBal', name: $translate.instant('Creditor'), headerCellClass: 'alignCenter dataColumn4',

                    cellTemplate: '<div class=" alignRight margin-right5"><span>{{row.entity.begCreditBal || "0.00"}}</span></div>'
                , footerCellTemplate: '<div class=" alignRight margin-right5 margin-top5" >{{grid.appScope.subtotals.begCreditBal || "0.00"}}</div>'

                },

                {
                    field: 'debitBal', name: $translate.instant('Debitor') + ' ', headerCellClass: 'alignCenter dataColumn5',

                    cellTemplate: '<div class=" alignRight margin-right5"><span>{{row.entity.debitBal || "0.00"}}</span></div>'
                , footerCellTemplate: '<div class=" alignRight margin-right5 margin-top5" >{{grid.appScope.subtotals.debitBal || "0.00"}}</div>'

                },

                {
                    field: 'creditBal', name: $translate.instant('Creditor') + ' ', headerCellClass: 'alignCenter dataColumn6',

                    cellTemplate: '<div class=" alignRight margin-right5"><span>{{row.entity.creditBal || "0.00"}}</span></div>'
                , footerCellTemplate: '<div class=" alignRight margin-right5 margin-top5" >{{grid.appScope.subtotals.creditBal || "0.00"}}</div>'

                },

                {
                    field: 'endDebitBal', name: $translate.instant('Debitor') + '  ', headerCellClass: 'alignCenter dataColumn7',
                    cellTemplate: '<div class=" alignRight margin-right5"><span>{{row.entity.endDebitBal || "0.00"}}</span></div>'
                , footerCellTemplate: '<div class="alignRight margin-right5 margin-top5" >{{grid.appScope.subtotals.endDebitBal || "0.00"}}</div>'

                },

                {
                    field: 'endCreditBal', name: $translate.instant('Creditor') + '  ', headerCellClass: 'alignCenter dataColumn8',
                    cellTemplate: '<div class=" alignRight margin-right5"><span>{{row.entity.endCreditBal || "0.00"}}</span></div>'
                , footerCellTemplate: '<div class="alignRight margin-right5 margin-top5" >{{grid.appScope.subtotals.endCreditBal || "0.00"}}</div>'
                }
                ]
            };

            // Get initial Data from Backend to fill the UI grid Tree:
            $scope.getDataFromDatabase($scope.currentCategory.selected.id, $scope.filterData.periodFrom, $scope.filterData.periodTo, "");

        };
         
        $scope.doDataFilterReset = function () {
            var from = $scope.filterData.periodFrom;
            var to = $scope.filterData.periodTo;

            $scope.filterData = {
                periodFrom: from,
                periodTo: to,
                accountCode: null,
                accountName: null,
                debitOpeningBalanceFrom: null,
                debitOpeningBalanceTo: null,
                creditOpeningBalanceFrom: null,
                creditOpeningBalanceTo: null,
                accumulatedDebitAmountFrom: null,
                accumulatedDebitAmountTo: null,
                accumulatedCreditAmountFrom: null,
                accumulatedCreditAmountTo: null,
                debitClosingBalanceFrom: null,
                debitClosingBalanceTo: null,
                creditClosingBalanceFrom: null,
                creditClosingBalanceTo: null,
                hideAllZeroRecords: false
            };

            // $scope.criteriaList = [];

            //$scope.getDataFromDatabase($scope.currentCategory.selected.id, from, to, "");
            $scope.isToClearSelection = true;
        }

        $scope.doDataFilter = function (removeData) {

            if ($scope.filterData.periodFrom > $scope.filterData.periodTo) {
                $scope.filterData.periodTo = $scope.filterData.periodFrom;
            }

            // Filter validations:
            if (!PWC.isNullOrEmpty($scope.filterData.debitOpeningBalanceFrom) && !PWC.isNullOrEmpty($scope.filterData.debitOpeningBalanceTo) &&
                $scope.filterData.debitOpeningBalanceFrom > $scope.filterData.debitOpeningBalanceTo) {
                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: "确定" },
                    function (isConfirm) {
                        if (isConfirm) {
                            $("#filterButton").click();
                        }

                    });
            }

            else if (!PWC.isNullOrEmpty($scope.filterData.creditOpeningBalanceFrom) && !PWC.isNullOrEmpty($scope.filterData.creditOpeningBalanceTo) &&
                $scope.filterData.creditOpeningBalanceFrom > $scope.filterData.creditOpeningBalanceTo) {

                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                    function (isConfirm) {
                        if (isConfirm) {
                            $("#filterButton").click();
                        }

                    });
            }

            else if (!PWC.isNullOrEmpty($scope.filterData.accumulatedDebitAmountFrom) && !PWC.isNullOrEmpty($scope.filterData.accumulatedDebitAmountTo) &&
            $scope.filterData.accumulatedDebitAmountFrom > $scope.filterData.accumulatedDebitAmountTo) {

                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                     function (isConfirm) {
                         if (isConfirm) {
                             $("#filterButton").click();
                         }

                     });
            }



            else if (!PWC.isNullOrEmpty($scope.filterData.accumulatedCreditAmountFrom) && !PWC.isNullOrEmpty($scope.filterData.accumulatedCreditAmountTo) &&
        $scope.filterData.accumulatedCreditAmountFrom > $scope.filterData.accumulatedCreditAmountTo) {

                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                     function (isConfirm) {
                         if (isConfirm) {
                             $("#filterButton").click();
                         }

                     });
            }

            else if (!PWC.isNullOrEmpty($scope.filterData.debitClosingBalanceFrom) && !PWC.isNullOrEmpty($scope.filterData.debitClosingBalanceTo) &&
        $scope.filterData.debitClosingBalanceFrom > $scope.filterData.debitClosingBalanceTo) {

                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                     function (isConfirm) {
                         if (isConfirm) {
                             $("#filterButton").click();
                         }

                     });
            }


            else if (!PWC.isNullOrEmpty($scope.filterData.creditClosingBalanceFrom) && !PWC.isNullOrEmpty($scope.filterData.creditClosingBalanceTo) &&
   $scope.filterData.creditClosingBalanceFrom > $scope.filterData.creditClosingBalanceTo) {

                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                     function (isConfirm) {
                         if (isConfirm) {
                             $("#filterButton").click();
                         }

                     });
            } 

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


                //********************************************************************************
                // add to Criteria List for display on top of the grid:
                var crits = $scope.filterData;

                $scope.criteriaList = [];

                var crit = [];
                if (!PWC.isNullOrEmpty(crits.accountCode)) {
                    crit = new Object;
                    crit.name = $translate.instant('AccountCode');
                    crit.valueFrom = crits.accountCode;
                    crit.propertyName = "accountCode";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.accountName)) {
                    crit = new Object;
                    crit.name = $translate.instant('AccountName');
                    crit.valueFrom = crits.accountName;
                    crit.propertyName = "accountName";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.debitOpeningBalanceFrom) || !PWC.isNullOrEmpty(crits.debitOpeningBalanceTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('DebitOpeningBalance');
                    crit.valueFrom = crits.debitOpeningBalanceFrom;
                    crit.valueTo = crits.debitOpeningBalanceTo;
                    crit.propertyName = "debitOpeningBalanceFrom|debitOpeningBalanceTo";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.creditOpeningBalanceFrom) || !PWC.isNullOrEmpty(crits.creditOpeningBalanceTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('CreditOpeningBalance');
                    crit.valueFrom = crits.creditOpeningBalanceFrom;
                    crit.valueTo = crits.creditOpeningBalanceTo;
                    crit.propertyName = "creditOpeningBalanceFrom|creditOpeningBalanceTo";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.accumulatedDebitAmountFrom) || !PWC.isNullOrEmpty(crits.accumulatedDebitAmountTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('AccumulatedDebitAmount');
                    crit.valueFrom = crits.accumulatedDebitAmountFrom;
                    crit.valueTo = crits.accumulatedDebitAmountTo;
                    crit.propertyName = "accumulatedDebitAmountFrom|accumulatedDebitAmountTo";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.accumulatedCreditAmountFrom) || !PWC.isNullOrEmpty(crits.accumulatedCreditAmountTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('AccumulatedCreditAmount');
                    crit.valueFrom = crits.accumulatedCreditAmountFrom;
                    crit.valueTo = crits.accumulatedCreditAmountTo;
                    crit.propertyName = "accumulatedCreditAmountFrom|accumulatedCreditAmountTo";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.debitClosingBalanceFrom) || !PWC.isNullOrEmpty(crits.debitClosingBalanceTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('DebitClosingBalance');
                    crit.valueFrom = crits.debitClosingBalanceFrom;
                    crit.valueTo = crits.debitClosingBalanceTo;
                    crit.propertyName = "debitClosingBalanceFrom|debitClosingBalanceTo";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.creditClosingBalanceFrom) || !PWC.isNullOrEmpty(crits.creditClosingBalanceTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('CreditClosingBalance');
                    crit.valueFrom = crits.creditClosingBalanceFrom;
                    crit.valueTo = crits.creditClosingBalanceTo;
                    crit.propertyName = "creditClosingBalanceFrom|creditClosingBalanceTo";

                    $scope.criteriaList.push(crit);
                }
                // add to Criteria List for display on top of the grid:
                //********************************************************************************
 
                var criteria = JSON.stringify($scope.filterData); 

                $scope.filterDataCriteria = criteria;

                $scope.getDataFromDatabase($scope.currentCategory.selected.id, $scope.filterData.periodFrom, $scope.filterData.periodTo, criteria, false);
            }
        };  

        $scope.popTheParentCode = function () {
            $scope.isShowParentCodePop = true;
            $scope.isToClearSelection = false;

            $('.filter-button').popover("hide");
        }

        $scope.hideAllZeroRecords = function () {
            $scope.filterData.hideAllZeroRecords = $("#ckbHideAllZeroRecords").is(":checked");

            var criteria = JSON.stringify($scope.filterData);
             
            $scope.getDataFromDatabase($scope.currentCategory.selected.id, $scope.filterData.periodFrom, $scope.filterData.periodTo, criteria, false);
        };

        //过滤条件变化
        $scope.doCategoryChange = function () {
            $scope.doDataFilterReset();
            $scope.criteriaList = [];
            $scope.isRunningTheFirstTime = true;
            $scope.filterData.hideAllZeroRecords = false;
            $("#ckbHideAllZeroRecords").prop('checked', false);

            $scope.doDataFilter('');
            var selectedSubjectName = $scope.currentCategory.selected.id; 
            if (selectedSubjectName === "CIT")
                $scope.switchedToCIT = true; 
        };

        // ************************************************************************************************
        // Control how the Header looks:
        function SetUiGridHeader() {
            var column1 = $("#tbDataPreviewGrid .ui-grid-header-cell").first();
            var column2 = $("#tbDataPreviewGrid .dataColumn1");
            var column3 = $("#tbDataPreviewGrid .dataColumn2");
            var column4 = $("#tbDataPreviewGrid .dataColumn3");
            var column5 = $("#tbDataPreviewGrid .dataColumn4");
            var column6 = $("#tbDataPreviewGrid .dataColumn5");
            var column7 = $("#tbDataPreviewGrid .dataColumn6");
            var column8 = $("#tbDataPreviewGrid .dataColumn7");
            var column9 = $("#tbDataPreviewGrid .dataColumn8");



            var col1 = column1.width();
            var col2 = column2.width();
            var col3 = column3.width();
            var col4 = column4.width();
            var col5 = column5.width();
            var col6 = column6.width();
            var col7 = column7.width();
            var col8 = column8.width();
            var col9 = column9.width();

            var marginSize = "-20px";
            var marginSizeForIcon = "-17px";

            if (browserService.isIE() || browserService.isEdge()) {
                $("#UIHeaderCol001").width(col1 - 1);
                $("#UIHeaderCol01").width(col2);
                $("#UIHeaderCol1").width(col3);

                $("#UIHeaderCol2").width(col4 + col5 + 1);
                $("#UIHeaderCol3").width(col6 + col7 + 1);
            }
            else if (browserService.isFirefox()) {
                $("#UIHeaderCol001").width(col1);
                $("#UIHeaderCol01").width(col2);
                $("#UIHeaderCol1").width(col3);

                $("#UIHeaderCol2").width(col4 + col5 + 1);
                $("#UIHeaderCol3").width(col6 + col7 + 1);

                marginSize = "-16px";
                marginSizeForIcon = "-16px";
            }

            else if (browserService.isChrome()) {
                $("#UIHeaderCol001").width(col1 - 1);
                $("#UIHeaderCol01").width(col2);
                $("#UIHeaderCol1").width(col3);

                $("#UIHeaderCol2").width(col4 + col5 + 1);
                $("#UIHeaderCol3").width(col6 + col7 + 1);

                marginSize = "-15px";
                marginSizeForIcon = "-15px";
            }


            var treeExpanderIcon = $("#tbDataPreviewGrid .ui-grid-tree-base-row-header-buttons").first();

            treeExpanderIcon.css("margin-top", marginSizeForIcon);


            var subjectCode = column2.find('span');
            var subjectName = column3.find('span');



            subjectCode.css("margin-top", 0);
            subjectName.css("margin-top", 0);

            setTimeout(function () {
                subjectName.css("position", "absolute");
                subjectName.css("margin-top", marginSize);
                subjectCode.css("position", "absolute");
                subjectCode.css("margin-top", marginSize);

            }, 900);


        };

        //开始
        (function initialize() {
                      
            //初始化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.show', function (ev, picker) {
                    $('.filter-button').popover("hide");
                })
             .on('datePicker.done', function (e, result) {
                 //开始月份
                 var startMonth = result[0][0];
                 //结束月份
                 var endMonth = result[1][0];
                 $scope.filterData.periodFrom = startMonth;
                 $scope.filterData.periodTo = endMonth;

                 var criteria = JSON.stringify($scope.filterData);
                  
                 $scope.getDataFromDatabase($scope.currentCategory.selected.id, $scope.filterData.periodFrom, $scope.filterData.periodTo, criteria);


             });

            $scope.initGridOption();

            $scope.$on(enums.vatEvent.layoutChanged, function () {
                $scope.gridApiTotal.core.handleWindowResize();
                SetUiGridHeader();
            }); 

            // Reposition Header when the window is resized
            $(window).on('resize', function () {
                $scope.gridApiTotal.core.handleWindowResize();
                SetUiGridHeader();
            });
        })();
    }
]);