commonModule.controller('previewAccountVoucherController', ['$scope', '$log', '$translate', '$timeout', 'apiInterceptor', 'Upload', 'dataImportService', 'SweetAlert', '$q', 'uiGridConstants', 'projectService', 'uiGridGroupingConstants', 'vatImportService', 'i18nService', 'browserService', '$interval', '$uibModal', 'vatPreviewService', '$http', 'region', 'citSessionService', '$state', '$compile',
    function ($scope, $log, $translate, $timeout, apiInterceptor, Upload, dataImportService, SweetAlert, $q, uiGridConstants, projectService, uiGridGroupingConstants, vatImportService, i18nService, browserService, $interval, $uibModal, vatPreviewService, $http, region, citSessionService, $state, $compile) {
        'use strict';

        // Subject Code Popup
        $scope.getCIT = "CIT";
        $scope.serviceType = $scope.project.serviceTypeID;

        $scope.popTheParentCode = function (e) {
            $scope.isShowParentCodePop = true;
            $(e.originalEvent.srcElement).parents(".dx-texteditor:first").dxAutocomplete("instance").option("opened", false);
        }

        $scope.confirmCodes = function (confirmedRecords) {

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

            //$scope.filterData.accountCode = codes;
            $scope.queryParams.inputs.accountCode = codes;
        }

        $scope.cancelCodes = function () {
            
        }
        // Subject Code Popup

        var projectYear = $scope.project.year;
        var startMonth = 1;
        var endMonth = 12;
        //VAT
        if ($scope.serviceType === '2') {
            var startMonth = $scope.month;
            var endMonth = $scope.month;
        }

        var minDate = new Date("2010-01-01");
        var maxDate = new Date("2030-12-31");

        var defaultPeriodDate = {
            from: new Date(projectYear, startMonth-1, 1),
            to: new Date(new Date(projectYear, endMonth, 1) - 10000)
        };

        var pageCanLeave = false;
        $scope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams, options) {
            //根据 Michelle YT Yao 的要求取消跳转提示拦截,但是以下代码保留,可能以后会需要拦截
            //将 pageCanLeave 设为 true 表示可以直接跳转
            pageCanLeave = true;

            if (!pageCanLeave) {
                event.preventDefault();

                var msgboxOptions = {
                    title: $translate.instant('WarningTitle'),
                    text: $translate.instant('AccountVoucher_AlertMsg_Leave'),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#e0301e",
                    confirmButtonText: $translate.instant('ConfirmYes'),
                    cancelButtonText: $translate.instant('ConfirmNo'),
                    closeOnConfirm: true,
                    closeOnCancel: true
                };

                SweetAlert.swal(msgboxOptions, function (isConfirm) {
                    if (isConfirm) {
                        pageCanLeave = true;
                        $state.go(toState, toParams, options);
                    };
                });
            }
            return false;
        });

        $scope.filterMode = {
            //普通查询
            normal: true,
            //高级查询
            advanced: false,
            //自定义查询
            custom: false,
            //借/贷方关联科目查询
            debitCrebitAccountCode: false
        }

        $scope.openAccountCodeModal = function () {
            $uibModal.open({
                animation: true,
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                templateUrl: 'account-code.html',
                controller: 'vatPreviewAccountVoucherAccountCodeCtrl',
                controllerAs: '$accountCodeCtrl',
                size: "520px",
                scope: $scope
            });
        }

        var closeAccountVoucherFilterDialog = function (e) {
            var dialogs = $("div.filter-dialog[id^='filterMode-']:visible");
            //不存在查询窗体事可以离开当前界面
            if (dialogs.length < 1) {
                return;
            }

            if (!(e && e.originalEvent && e.originalEvent.srcElement))
                return;

            var srcElement = e.originalEvent.srcElement;
            /*
             * 不关闭 filterDialog 的情形
             *  1.触发点击事件的控件在 filterDialog 内部时
             *  2.在打开 filterDialog 的菜单中时
             *  3.存在显示的 modal 时
             *  4.点击会计期间控件时
             *  5.点击自动补全控件内容时
             */
            for (var i = 0; i < dialogs.length; i++) {
                if (dialogs[i].contains(srcElement))
                    return;
            }

            if ($("#mainPreviewDiv .filter-menu")[0].contains(srcElement))
                return;

            if ($(".sweet-alert:visible").length > 0 || $(".modal-open").length > 0)
                return;

            var rp = dialogs.find('#period-picker').data("_ranegPicker");
            if (rp && rp.tether && rp.tether.element && rp.tether.element.contains(srcElement)) {
                return;
            }

            //点击的是自动补全控件时不关闭
            if ($(srcElement).parents("md-virtual-repeat-container:first").length > 0)
                return;

            dialogs.hide();
            $(".vat-preview-account-voucher#mainPreviewDiv").off("click", closeAccountVoucherFilterDialog);
        }

        $scope.showFilterDialog = function ($evn, selector) {
            var target = $evn.delegateTarget;
            var fDialog = $(selector);
            if (fDialog.length < 1)
                return;

            var dialogs = $("div.filter-dialog[id^='filterMode-']");
            $.each(dialogs, function (i, n) {
                if (n == fDialog[0])
                    return;

                $(n).hide();
            });

            fDialog.css({ "top": ((target.offsetHeight + target.offsetTop) + "px"), "left": (target.offsetLeft + "px") });
            fDialog.show();
            $(".vat-preview-account-voucher#mainPreviewDiv").on("click", closeAccountVoucherFilterDialog);
            $scope.UpdateDisableStatusManual("accountCode", $scope.queryParams.selectors.accountCode.selected);
            $scope.UpdateDisableStatusManual("accountName", $scope.queryParams.selectors.accountName.selected);

            //初始化month-picker ,以下代码被屏蔽:界面暂时不再使用 rangePicker ,切换到 dx 的 dateBox 控件
            //var rp = fDialog.find('#period-picker').data("_ranegPicker");
            //if (!rp) {
            //    var 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')
            //    ];
            //    fDialog.find('#period-picker').rangePicker({
            //        minDate: [1, citSessionService.project.year],
            //        maxDate: [12, citSessionService.project.year],
            //        setDate: [
            //            [citSessionService.month, citSessionService.project.year],
            //            [citSessionService.month, citSessionService.project.year]
            //        ],
            //        months: monthList,
            //        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.queryParams.inputs.period.from = startMonth;
            //            $scope.queryParams.inputs.period.to = endMonth;
            //        })
            //        .data("_ranegPicker")
            //        .applyDate();
            //}

            if ($scope.accountCodes.length < 1) {
                vatPreviewService.getEnterpriseAccount().success(function (data) {
                    $scope.accountCodes = data;

                    for (var i = 0; i < data.length; i++) {
                        $scope.autocompleteDataSource.store().insert(data[i]);
                    }
                    $scope.autocompleteDataSource.load();
                });
            }
        }
        
        $scope.autocompleteDataSource = new DevExpress.data.DataSource([]);
        $scope.autocompleteAccountCodeSearchMode = "startswith";
        $scope.autocompleteAccountCodePlaceholder = $translate.instant("AccountVoucher_Placeholder_Text");
        $scope.autocompleteAccountNameSearchMode = "startswith";
        $scope.autocompleteAccountNamePlaceholder = $translate.instant("AccountVoucher_Placeholder_Text");

        $scope.UpdateDisableStatusManual = function (type, item) {
            if (!(type && item))
                return;

            //var searchModes = ["contains", "startswith"];
            var input = $("#filterMode-normal div[ng-class*='" + type + "'] input");
            if (item.id && !$scope.isFromReMapping) {
                input.removeAttr("disabled");
                var searchMode = (item.id == "1" || item.id == "2") ? "startswith" : "contains";
                if (type.toLowerCase() === "accountCode".toLowerCase()) {
                    $scope.autocompleteAccountCodeSearchMode = searchMode;
                }
                else {
                    $scope.autocompleteAccountNameSearchMode = searchMode;
                }
            } else {
                input.attr("disabled", "disabled");
            }
        }

        $scope.getVoucherDataFromDatabase = function (mainRelation, allJe, period, vID, group, queryCondition) {
            var deferred = $q.defer();
            vatPreviewService.getVoucherByConditon(mainRelation, allJe, period, vID, group, queryCondition).success(function (dataList) {
                deferred.resolve(dataList);

            }).error(function () {
                deferred.reject();
            });
            return deferred.promise;
        };
       
        var voucherDataLoad = function (pageIndex) {
            $log.debug("vat-preview-accountVoucher-ctrl: voucherDataLoad");
            $scope.curVoucherItemPage = pageIndex;
            $scope.queryParams.pagingInfo.pageIndex = pageIndex;
            $log.debug($scope.queryParams);
            if ($scope.queryParams.isEntryShow) {                             
                vatPreviewService.voucherSelectAdvancedByEntry($scope.queryParams.mainRelation, $scope.queryParams.allJe, $scope.queryParams.pagingInfo, $scope.queryParams.listQueryCondition).success(function (listData) {
                    listData.data.debitSum = PWC.round(listData.data.debitSum, 2);
                    listData.data.creditSum = PWC.round(listData.data.creditSum, 2);
                    listData.data.voucherList.forEach(function (v) {
                        v.debit = PWC.round(v.debit, 2);
                        v.credit = PWC.round(v.credit, 2);
                    });
                    $scope.voucherDataList = listData.data.voucherList;
                    //var dataGrid = $('#gridContainer').dxDataGrid('instance');
                    //dataGrid.refresh();
                    initDataGrid();              
                    vatPreviewService.getSelectWhereString($scope.queryParams.mainRelation, $scope.queryParams.allJe, $scope.queryParams.listQueryCondition).success(function (queryString) {
                        showVoucherCount(listData.data.itemIDCount, listData.data.vidCount, listData.data.debitSum, listData.data.creditSum, queryString);                    
                    });                 
                });
                computeVoucherItemPage(false);
            }
            else {
                vatPreviewService.voucherSelectAdvancedByVoucher($scope.queryParams.mainRelation, $scope.queryParams.allJe, $scope.queryParams.pagingInfo, $scope.queryParams.listQueryCondition).success(function (listData) {
                    listData.data.debitSum = PWC.round(listData.data.debitSum, 2);
                    listData.data.creditSum = PWC.round(listData.data.creditSum, 2);
                    listData.data.voucherMainList.forEach(function (v) {
                        v.debitSum = PWC.round(v.debitSum, 2);
                        v.creditSum = PWC.round(v.creditSum, 2);
                    });
                    $scope.voucherDataList = listData.data.voucherMainList;
                    //var dataGrid = $('#gridContainer').dxDataGrid('instance');
                    //dataGrid.refresh();
                    initDataGrid();                   
                    vatPreviewService.getSelectWhereString($scope.queryParams.mainRelation, $scope.queryParams.allJe, $scope.queryParams.listQueryCondition).success(function (queryString) {
                        showVoucherCount(listData.data.itemIDCount, listData.data.vidCount, listData.data.debitSum, listData.data.creditSum, queryString);
                    });

                });
                computeVoucherItemPage(false);
            }

            
            
        };

        //显示凭证相关信息(分录数、凭证数、借贷方总金额、查询条件)
        var showVoucherCount = function (itemIDCount, vIDCount, debitSum, creditSum, queryString) {
            $scope.vIDCount = vIDCount;
            $scope.itemIDCount = itemIDCount;
            $scope.debitSum = debitSum;
            $scope.creditSum = creditSum;
            $scope.queryString = queryString;
        };

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

            if (!fristLoad) {
                vatPreviewService.voucherSelectAdvancedCount($scope.queryParams.mainRelation, $scope.queryParams.isEntryShow, $scope.queryParams.allJe, $scope.queryParams.listQueryCondition).success(function (data) {
                    if (data && !data.result&&data.resultMsg) {
                        SweetAlert.warning($translate.instant(data.resultMsg));
                        return false;
                    }
                    $scope.queryParams.pagingInfo.totalCount = data.data;

                    if ($scope.queryParams.pagingInfo && $scope.queryParams.pagingInfo.totalCount > 0) {

                        var totalPage = parseInt($scope.queryParams.pagingInfo.totalCount / $scope.queryParams.pagingInfo.pageSize);
                        totalPage = $scope.queryParams.pagingInfo.totalCount % $scope.queryParams.pagingInfo.pageSize == 0 ? totalPage : totalPage + 1;

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

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

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

                $('#totalVoucherPage').css('display', 'inline-block');
            }
            return true;
        };

        $scope.queryParams = {
            //查询模板
            listQueryCondition: [],
            //分页信息
            pagingInfo: { "totalCount": 0, "pageIndex": 1, "pageSize": 100 },
            andOr: 'AND',
            //主条件
            mainRelation: '8',
            //是否显示所有凭证
            allJe: false,
            //是否为分录显示
            isEntryShow: true,
            //二级子查询-期间
            period: '',
            //二级子查询-凭证编号
            vID: '',
            //二级子查询-凭证类型
            group: null
        };

        $scope.queryConditionTemp = {
            conditionName: null,
            searchKeyWord: 0,
            searchValue: null
        };

        var copyArray = function (data) {
            var ret = [];
            data.forEach(function (row) {
                ret.push(row);
            });

            return ret;
        };

        //按凭证显示
        var voucherShow = function () {
            if ($scope.queryParams.isEntryShow) {
                $scope.queryParams.isEntryShow = false;
                if ($scope.queryParams.listQueryCondition && $scope.queryParams.listQueryCondition.length > 0) {
                    $scope.curVoucherItemPage = 1;
                    computeVoucherItemPage(false);
                    voucherDataLoad($scope.curVoucherItemPage);
                }
                else {
                    initDataGrid();
                }

            }
        };

        //按分录显示
        var entryShow = function () {
            if (!$scope.queryParams.isEntryShow) {
                $scope.queryParams.isEntryShow = true;
                if ($scope.queryParams.listQueryCondition && $scope.queryParams.listQueryCondition.length > 0) {
                    $scope.curVoucherItemPage = 1;
                    computeVoucherItemPage(false);
                    voucherDataLoad($scope.curVoucherItemPage);
                }
                else {
                    initDataGrid();
                }
            }
        };

        //查询确定
        var selectVoucher = function () {
            $log.debug("start to selectVoucher");
            $scope.queryParams.listQueryCondition = [];
            //条件间主关系
            if ($scope.queryParams.andOr == "AND") {
                $scope.queryParams.mainRelation = '8';
            } else {
                $scope.queryParams.mainRelation = '7';
            }
            //是否显示所有凭证
            //$scope.queryParams.allJe = $scope.filterParams.isAllJe;
            //是否按分录显示
            //$scope.queryParams.isEntryShow = $scope.filterParams.isEntryShow;
            //$scope.queryParams.pagingInfo = $scope.pagingInfo;

            var selectors = $scope.queryParams.selectors;
            var inputs = $scope.queryParams.inputs;

            //企业科目代码
            if (selectors.accountCode.selected.id) {
                //期望使用该字段参与查询,却不给定查询关键字时,给出提示
                if (!inputs.accountCode) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_AccountCodeEmpty'));
                    return;
                }

                var accountCodeMto = {};
                accountCodeMto.conditionName = $translate.instant('AccountVoucher_AccountCode');
                accountCodeMto.searchKeyWord = selectors.accountCode.selected.id;
                accountCodeMto.searchValue = inputs.accountCode;
                $scope.queryParams.listQueryCondition.push(accountCodeMto);
            }
            //企业科目名称
            if (selectors.accountName.selected.id) {
                if (!inputs.accountName) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_AccountNameEmpty'));
                    return;
                }

                var accountNameMto = {};
                accountNameMto.conditionName = $translate.instant('AccountVoucher_AccountName');
                accountNameMto.searchKeyWord = selectors.accountName.selected.id;
                accountNameMto.searchValue = inputs.accountName;
                $scope.queryParams.listQueryCondition.push(accountNameMto);
            }
            //会计期间
            if (inputs.period.from || inputs.period.to) {
                var from = inputs.period.from;
                var to = inputs.period.to;
                
                if (to && from && to < from) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_PeriodEndMonthTooBig'));
                    return;
                }

                var periodMto = {};
                periodMto.conditionName = $translate.instant('AccountVoucher_Period');
                periodMto.searchKeyWord = 14;
                periodMto.searchValue = (from ? from.getMonth() + 1 : "null") + " " + (to ? to.getMonth() + 1 : "null");
                $scope.queryParams.listQueryCondition.push(periodMto);
            }
            //凭证类型
            if (selectors.group.selected.id) {
                if (!inputs.group) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_GroupEmpty'));
                    return;
                }

                var groupMto = {};
                groupMto.conditionName = $translate.instant('AccountVoucher_Group');
                groupMto.searchKeyWord = selectors.group.selected.id;
                groupMto.searchValue = inputs.group;
                $scope.queryParams.listQueryCondition.push(groupMto);
            }
            //凭证编号
            if (selectors.groupNum.selected.id) {
                if (!inputs.groupNum) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_GroupNumEmpty'));
                    return;
                }

                var groupNumMto = {};
                groupNumMto.conditionName = $translate.instant('AccountVoucher_GroupNum');
                groupNumMto.searchKeyWord = selectors.groupNum.selected.id;
                groupNumMto.searchValue = inputs.groupNum;
                $scope.queryParams.listQueryCondition.push(groupNumMto);
            }
            //凭证摘要
            if (selectors.summary.selected.id) {
                if (!inputs.summary) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_SummaryEmpty'));
                    return;
                }

                if (inputs.summary.toString().length < 3) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_SummaryTooShort'));
                    return;
                }

                var summaryMto = {};
                summaryMto.conditionName = $translate.instant('AccountVoucher_Summary');
                summaryMto.searchKeyWord = selectors.summary.selected.id;
                summaryMto.searchValue = inputs.summary;
                $scope.queryParams.listQueryCondition.push(summaryMto);
            }
            //往来核算代码
            //if (selectors.customerCode.selected.id) {
            //    if (!inputs.customerCode) {
            //        SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_CustomerCodeEmpty'));
            //        return;
            //    }

            //        var customerCodeMto = {};
            //        customerCodeMto.conditionName = $translate.instant('AccountVoucher_CustomerCode');
            //        customerCodeMto.searchKeyWord = selectors.customerCode.selected.id;
            //        customerCodeMto.searchValue = inputs.customerCode;
            //        $scope.queryParams.listQueryCondition.push(customerCodeMto);
            //}
            //往来核算名称
            //if (selectors.customerName.selected.id) {
            //    if (!inputs.customerName) {
            //        SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_CustomerNameEmpty'));
            //        return;
            //    }

            //        var customerNameMto = {};
            //        customerNameMto.conditionName =$translate.instant('AccountVoucher_CustomerName')";
            //        customerNameMto.searchKeyWord = selectors.customerName.selected.id;
            //        customerNameMto.searchValue = inputs.customerName;
            //        $scope.queryParams.listQueryCondition.push(customerNameMto);
            //}
            //凭证日期
            if (inputs.date.from || inputs.date.to) {
                var from = inputs.date.from;
                var to = inputs.date.to;

                if ((from && (from > maxDate || from < minDate)) || (to && (to > maxDate || to < minDate))) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_DateInvalid'));
                    return;
                }

                if (to && from && to < from) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_DateEndDateTooBig'));
                    return;
                }

                var dateMto = {};
                dateMto.conditionName = $translate.instant('AccountVoucher_Date');
                dateMto.searchKeyWord = 14;
                dateMto.searchValue = (from ? moment(from).format("YYYY-MM-DD") : "null") + " " + (to ? moment(to).format("YYYY-MM-DD") : "null");

                $scope.queryParams.listQueryCondition.push(dateMto);
            }
            //借方金额
            if (inputs.debit.from || inputs.debit.to) {
                var from = inputs.debit.from;
                var to = inputs.debit.to;
                from = from == null ? "" : from;
                to = to == null ? "" : to;
                if ((from && isNaN(from)) || (to && isNaN(to))) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_DebitInvalid'));
                    return;
                }

                if (to && from && Number(to) < Number(from)) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_DebitEndAmountTooBig'));
                    return;
                }

                if (!from) {
                    from = "null";
                }
                if (!to) {
                    to = "null";
                }

                var debitMto = {};
                debitMto.conditionName = $translate.instant('AccountVoucher_Debit');
                debitMto.searchKeyWord = 14;
                debitMto.searchValue = from + " " + to;
                $scope.queryParams.listQueryCondition.push(debitMto);
            }
            //贷方金额
            if (inputs.credit.from || inputs.credit.to) {
                var from = inputs.credit.from;
                var to = inputs.credit.to;
                from = from == null ? "" : from;
                to = to == null ? "" : to;
                if ((from && isNaN(from)) || (to && isNaN(to))) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_CreditInvalid'));
                    return;
                }

                if (to && from && Number(to) < Number(from)) {
                    SweetAlert.warning($translate.instant('AccountVoucher_FVMsg_CreditEndAmountTooBig'));
                    return;
                }
                if (!from) {
                    from = "null";
                }
                if (!to) {
                    to = "null";
                }
                var creditMto = {};
                creditMto.conditionName = $translate.instant('AccountVoucher_Credit');
                creditMto.searchKeyWord = 14;
                creditMto.searchValue = from + " " + to;
                $scope.queryParams.listQueryCondition.push(creditMto);
            }           
            setRemapSearchConditions();
            if ($scope.queryParams.listQueryCondition.length == 0) {
                SweetAlert.warning($translate.instant("NotInputTheQueryConditions"));
                return;
            }
            $scope.curVoucherItemPage = 1;
            if (computeVoucherItemPage(false)) {
                $log.debug("start to voucherDataLoad");
                voucherDataLoad($scope.curVoucherItemPage);
                $("div.filter-dialog[id^='filterMode-']:visible").hide();             
            }
        };

        //查询重置
        var resetSelectCondition = function () {
            var obj = { id: "" };

            $scope.queryParams.andOr = "AND";
            $scope.queryParams.allJe = false;
            $scope.queryParams.selectors.accountCode.selected = obj;
            $scope.queryParams.selectors.accountName.selected = obj;
            $scope.queryParams.selectors.period.selected = obj;
            $scope.queryParams.selectors.group.selected = obj;
            $scope.queryParams.selectors.groupNum.selected = obj;
            $scope.queryParams.selectors.summary.selected = obj;

            $scope.queryParams.inputs = {
                accountCode: null,
                accountName: null,
                period: {
                    from: new Date(projectYear, startMonth - 1, 1),
                    to: new Date(projectYear, endMonth - 1, 1)
                },
                group: null,
                groupNum: null,
                summary: null,
                date: {
                    from: new Date(defaultPeriodDate.from),
                    to: new Date(defaultPeriodDate.to)
                },
                debit: {
                    from: null,
                    to: null
                },
                credit: {
                    from: null,
                    to: null
                }
            };

            //以下代码被屏蔽:界面暂时不再使用 rangePicker ,切换到 dx 的 dateBox 控件
            //var dialog = $("div.filter-dialog[id^='filterMode-']");
            //var rq = dialog.find("#period-picker").data("_ranegPicker");
            //if (!_.isNull(rq) && !_.isUndefined(rq)) {
            //    rq.result[0][0] = citSessionService.month;
            //    rq.result[0][1] = citSessionService.project.year;
            //    rq.result[1][0] = citSessionService.month;
            //    rq.result[1][1] = citSessionService.project.year;
            //    rq.update(rq.result);
            //}

        }
        //导出
        var exportToExcel = function () {
            var dataGrid = $('#gridContainer').dxDataGrid('instance');
            setExportFileName();
            var exportValues = dataGrid.option("export");
            exportValues.fileName = $scope.exportToExcelFileName;
            dataGrid.option("export", exportValues);
            //dataGrid.fileName="testExport",
            dataGrid.exportToExcel(false);
        };

        // ****************************************************************************************
        //************ EXCEL EXPORT FUNCTION ***************/
        $scope.$on('ngEntryRepeatFinished', function (ngRepeatFinishedEvent) {
            if ($scope.isToPrint) {
                setExportFileName();
                export_table_to_excel('exportEntryTable', $scope.exportToExcelFileName, 'xlsx', '');
            }
            $scope.isToPrint = false;
        });
        
        $scope.$on('ngVoucherRepeatFinished', function (ngRepeatFinishedEvent) {
            if ($scope.isToPrint) {
                setExportFileName();
                export_table_to_excel('exportVoucherTable', $scope.exportToExcelFileName, 'xlsx', '');
            }
            $scope.isToPrint = false;
        });
        //导出全部
        $scope.exportAllToExcel = function () {
            $scope.isToPrint = true;
            $scope.getExportData();
        };
        $scope.getExportData = function () {
            if ($scope.queryParams.listQueryCondition && $scope.queryParams.listQueryCondition.length > 0) {
                if ($scope.queryParams.isEntryShow) {
                    vatPreviewService.voucherSelectAdvancedByEntry($scope.queryParams.mainRelation, $scope.queryParams.allJe, null, $scope.queryParams.listQueryCondition).success(function (listData) {
                        listData.data.voucherList.forEach(function (v) {
                            v.debit = PWC.round(v.debit, 2);
                            v.credit = PWC.round(v.credit, 2);
                        });
                        $scope.exportEntryDataList = listData.data.voucherList;
                    });
                }
                else {
                    vatPreviewService.voucherSelectAdvancedByVoucher($scope.queryParams.mainRelation, $scope.queryParams.allJe, null, $scope.queryParams.listQueryCondition).success(function (listData) {
                        listData.data.voucherMainList.forEach(function (v) {
                            v.debitSum = PWC.round(v.debitSum, 2);
                            v.creditSum = PWC.round(v.creditSum, 2);
                        });
                        $scope.exportVoucherDataList = listData.data.voucherMainList;
                    });
                }
            }
        };

        $scope.toggleAllMasterRows = function ($event) {
            var expand = "dx-datagrid-group-closed";
            var collapse = "dx-datagrid-group-opened";
            if ($($event.target).hasClass(expand)) {
                $scope.gridInstance.expandAll(-1);
                $($event.target).removeClass(expand);
                $($event.target).addClass(collapse);
            } else {
                $scope.gridInstance.collapseAll(-1);
                $($event.target).removeClass(collapse);
                $($event.target).addClass(expand);
            }
        }

        var initDataGrid = function () {
            //分录显示
            $log.debug("start to initDataGrid");
            if ($scope.queryParams.isEntryShow) {
                $("#gridContainer").dxDataGrid({
                    dataSource: $scope.voucherDataList,
                    scrolling: {
                        mode: "virtual"
                    },
                    sorting: {
                        mode: "none"
                    },
                    export: {
                        fileName: $scope.exportToExcelFileName
                    },
                    allowColumnResizing: true,
                    //columnAutoWidth: true,
                    showRowLines: true,
                    showColumnLines: true,
                    rowAlternationEnabled: true, //单双行颜色
                    showBorders: true,
                    noDataText: $translate.instant('AccountVoucher_DataGrid_NoDataText'),
                    columns: [
                        {
                            alignment: "left",
                            dataField: "period",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColPeriod'),
                            sortIndex: 0,
                            sortOrder: 'asc',
                            width: 65
                        },
                        {
                            alignment: "center",
                            dataField: "date",
                            dataType: "date",
                            format: "yyyy-MM-dd",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColDate'),
                            sortIndex: 1,
                            sortOrder: 'asc',
                            width: 95
                        },
                        {
                            dataField: "group",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColGroup'),
                            sortIndex: 2,
                            sortOrder: 'asc',
                            width: 180
                        },
                        {
                            dataField: "vid",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColVID'),
                            sortIndex: 3,
                            sortOrder: 'asc',
                            width: "20%"
                        },
                        {
                            dataField: "summary",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColSummary'),
                            width: "30%"
                        },
                        //{
                        //    dataField: "customerCodeAndNameShow",
                        //    caption: $translate.instant('AccountVoucher_DataGrid_ColCustomerCodeAndNameShow'),
                        //    //width: 170
                        //},
                        {
                            dataField: "acctCodeAndNameShow",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColAcctCodeAndNameShow'),
                            width: "20%"
                        },
                        {
                            dataField: "stdCodeAndNameShow",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColStdCodeAndNameShow'),
                            width: "30%"
                        },
                        {
                            dataField: "debit",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColDebit'),
                            alignment: "right",
                            width: 120
                        },
                        {
                            dataField: "credit",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColCredit'),
                            alignment: "right",
                            width: 120
                        }
                    ],
                    masterDetail: {
                        enabled: false
                    },
                    onContentReady: function () {
                        $log.debug("onContentReady entry");
                        $scope.setVoucherSelected();
                    },
                    onInitialized: function (e) {
                        $scope.gridInstance = e.component;
                    }
                });
            } else {

                $("#gridContainer").dxDataGrid({
                    dataSource: $scope.voucherDataList,
                    scrolling: {
                        mode: "virtual"
                    },
                    sorting: {
                        mode: "none"
                    },
                    export: {
                        fileName: $scope.exportToExcelFileName,
                    },
                    allowColumnResizing: true,
                    showRowLines: true,
                    showColumnLines: true,
                    noDataText: $translate.instant('AccountVoucher_DataGrid_NoDataText'),
                    columns: [
                        {
                            dataField: "period",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColPeriod'),
                            sortIndex: 0,
                            sortOrder: 'asc',
                            width: 130
                        },
                        {
                            alignment: "center",
                            dataField: "date",
                            dataType: "date",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColDate'),
                            format: "yyyy-MM-dd",
                            sortIndex: 1,
                            sortOrder: 'asc',
                            width: 100
                        },
                        {
                            dataField: "group",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColGroup'),
                            sortIndex: 2,
                            sortOrder: 'asc',
                            width: "50%"
                        },
                        {
                            dataField: "vid",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColVID'),
                            sortIndex: 3,
                            sortOrder: 'asc',
                            width: "50%"
                        },
                        {
                            dataField: "debitSum",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColDebitSum'),
                            alignment: "right",
                            width: 170
                        },
                        {
                            dataField: "creditSum",
                            caption: $translate.instant('AccountVoucher_DataGrid_ColCreditSum'),
                            alignment: "right",
                            width: 170
                        }
                    ],
                    masterDetail: {
                        enabled: true,
                        template: function (container, options) {
                            var currentVoucherData = options.data;
                            $scope.queryParams.period = currentVoucherData.period;
                            $scope.queryParams.vID = currentVoucherData.vid;
                            $scope.queryParams.group = currentVoucherData.group;
                            container.addClass("internal-grid-container");
                            $("<div>")
                                .addClass("internal-grid")
                                .dxDataGrid({
                                    columnAutoWidth: true,
                                    loadPanel: {
                                        enabled: false
                                    },
                                    showBorders: true,
                                    sorting: {
                                        mode: "none"
                                    },
                                    columns: [
                                        {
                                            dataField: "summary",
                                            caption: $translate.instant('AccountVoucher_DataGrid_ColSummary'),
                                            width: "50%"
                                        },
                                        //{
                                        //    dataField: "customerCodeAndNameShow",
                                        //    caption: $translate.instant('AccountVoucher_DataGrid_ColCustomerCodeAndNameShow') ,
                                        //    //width: 170
                                        //},
                                        {
                                            dataField: "acctCodeAndNameShow",
                                            caption: $translate.instant('AccountVoucher_DataGrid_ColAcctCodeAndNameShow'),
                                            sortIndex: 1,
                                            sortOrder: 'asc',
                                            width: "25%"
                                        },
                                        {
                                            dataField: "stdCodeAndNameShow",
                                            caption: $translate.instant('AccountVoucher_DataGrid_ColStdCodeAndNameShow'),
                                            sortIndex: 0,
                                            sortOrder: 'asc',
                                            width: "25%"
                                        },
                                        {
                                            dataField: "debit",
                                            caption: $translate.instant('AccountVoucher_DataGrid_ColDebit'),
                                            alignment: "right",
                                            width: 170
                                        },
                                        {
                                            dataField: "credit",
                                            caption: $translate.instant('AccountVoucher_DataGrid_ColCredit'),
                                            alignment: "right",
                                            width: 170
                                        }
                                    ],
                                    dataSource: {
                                        store: new DevExpress.data.CustomStore({
                                            load: function (loadOptions) {
                                                return $scope.getVoucherDataFromDatabase($scope.queryParams.mainRelation, $scope.queryParams.allJe, currentVoucherData.period, currentVoucherData.vid, currentVoucherData.group, $scope.queryParams.listQueryCondition).then(function (data) {
                                                    data.data.forEach(function (v) {
                                                        v.debit = PWC.round(v.debit, 2);
                                                        v.credit = PWC.round(v.credit, 2);
                                                    });
                                                    return { data: data.data, totalCount: data.data.length };
                                                }, function () {
                                                    return $q.reject($translate.instant("DataLoadingError"));
                                                });
                                            }
                                        })
                                    }
                                }).appendTo(container);
                        }
                    },
                    onCellPrepared: function(e) {
                        if (e.rowType === "header" && $(e.cellElement).hasClass("dx-command-expand")) {
                            var btn = $("<div class='dx-datagrid-group-closed'></div>");
                            btn.attr("ng-click", "toggleAllMasterRows($event)");
                            e.cellElement.empty();
                            e.cellElement.append($compile(btn) ($scope));
                        }
                    },
                    onContentReady: function() {
                        $log.debug("onContentReady voucher");
                        $scope.setVoucherSelected();
                    },
                    onInitialized: function(e) {
                        $scope.gridInstance = e.component;
                    }
                });
            }
        };

        var setExportFileName = function () {
            var myDate = new Date();
            var now = myDate.formatDateTime('yyyy-MM-dd') + " " + myDate.formatDateTime('HH') + myDate.formatDateTime('mm') + myDate.formatDateTime('ss');
            $scope.exportToExcelFileName = $translate.instant('Voucher_Export_result')+" " + now ;
        };
        $scope.queryParams.selectors =
        {
            accountCode: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "1", name: $translate.instant('AccountVoucher_Selector_1') },
                    { id: "2", name: $translate.instant('AccountVoucher_Selector_2') }
                ],
                selected: { id: "" }
            },
            accountName: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "1", name: $translate.instant('AccountVoucher_Selector_1') },
                    { id: "3", name: $translate.instant('AccountVoucher_Selector_3') },
                    { id: "4", name: $translate.instant('AccountVoucher_Selector_4') },
                    { id: "2", name: $translate.instant('AccountVoucher_Selector_2') }
                ],
                selected: { id: "" }
            },
            period: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "1", name: $translate.instant('AccountVoucher_Selector_1') },
                    { id: "10", name: $translate.instant('AccountVoucher_Selector_10') },
                    { id: "11", name: $translate.instant('AccountVoucher_Selector_11') },
                    { id: "12", name: $translate.instant('AccountVoucher_Selector_12') },
                    { id: "13", name: $translate.instant('AccountVoucher_Selector_13') }
                ],
                selected: { id: "" }
            },
            group: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "1", name: $translate.instant('AccountVoucher_Selector_1') },
                    { id: "3", name: $translate.instant('AccountVoucher_Selector_3') },
                    { id: "4", name: $translate.instant('AccountVoucher_Selector_4') },
                    { id: "2", name: $translate.instant('AccountVoucher_Selector_2') }
                ],
                selected: { id: "" }
            },
            groupNum: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "1", name: $translate.instant('AccountVoucher_Selector_1') },
                    { id: "2", name: $translate.instant('AccountVoucher_Selector_2') }
                ],
                selected: { id: "" }
            },
            summary: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "1", name: $translate.instant('AccountVoucher_Selector_1') },
                    { id: "3", name: $translate.instant('AccountVoucher_Selector_3') },
                    { id: "4", name: $translate.instant('AccountVoucher_Selector_4') },
                    { id: "2", name: $translate.instant('AccountVoucher_Selector_2') }
                ],
                selected: { id: "" }
            },
            date: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "9", name: $translate.instant('AccountVoucher_Selector_9') },
                    { id: "10", name: $translate.instant('AccountVoucher_Selector_10') },
                    { id: "11", name: $translate.instant('AccountVoucher_Selector_11') },
                    { id: "12", name: $translate.instant('AccountVoucher_Selector_12') },
                    { id: "13", name: $translate.instant('AccountVoucher_Selector_13') }
                ],
                selected: { id: "" }
            },
            debit: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "9", name: $translate.instant('AccountVoucher_Selector_9') },
                    { id: "10", name: $translate.instant('AccountVoucher_Selector_10') },
                    { id: "11", name: $translate.instant('AccountVoucher_Selector_11') },
                    { id: "12", name: $translate.instant('AccountVoucher_Selector_12') },
                    { id: "13", name: $translate.instant('AccountVoucher_Selector_13') }
                ],
                selected: { id: "" }
            },
            credit: {
                itemArray: [
                    { id: "", name: $translate.instant('AccountVoucher_SelectorEmpty') },
                    { id: "9", name: $translate.instant('AccountVoucher_Selector_9') },
                    { id: "10", name: $translate.instant('AccountVoucher_Selector_10') },
                    { id: "11", name: $translate.instant('AccountVoucher_Selector_11') },
                    { id: "12", name: $translate.instant('AccountVoucher_Selector_12') },
                    { id: "13", name: $translate.instant('AccountVoucher_Selector_13') }
                ],
                selected: { id: "" }
            }
        };

        $scope.queryParams.inputs = {
            accountCode: null,
            accountName: null,
            period: {
                from: null,
                to: null
            },
            group: null,
            groupNum: null,
            summary: null,
            date: {
                from: null,
                to: null
            },
            debit: {
                from: null,
                to: null
            },
            credit: {
                from: null,
                to: null
            }
        };

        $scope.accountCodes = [];

        $scope.dxControlsOptions = {
            queryPeriodFrom: {
                ControlOption: {
                    acceptCustomValue: false,
                    displayFormat: "yyyy年MM月",
                    max: new Date(projectYear, 11, 31),
                    min: new Date(projectYear, 0, 1),
                    maxZoomLevel: "year",
                    minZoomLevel: "year",
                    placeholder: $translate.instant('AccountVoucher_Placeholder_Period'),
                    showClearButton: true,
                    bindingOptions: {
                        value: "queryParams.inputs.period.from"
                    }
                },
                validatorOption: {
                    validationRules: [],
                    onInitialized: function (e) {
                        $scope.dxControlsOptions.queryPeriodFrom.validatorInstance = e.component;
                    }
                },
                validatorInstance: null
            },
            queryPeriodTo: {
                ControlOption: {
                    acceptCustomValue: false,
                    displayFormat: "yyyy年MM月",
                    max: new Date(projectYear, 11, 31),
                    min: new Date(projectYear, 0, 1),
                    maxZoomLevel: "year",
                    minZoomLevel: "year",
                    placeholder: $translate.instant('AccountVoucher_Placeholder_Period'),
                    showClearButton: true,
                    bindingOptions: {
                        value: "queryParams.inputs.period.to"
                    }
                },
                validatorOption: {
                    validationRules: [],
                    onInitialized: function (e) {
                        $scope.dxControlsOptions.queryPeriodTo.validatorInstance = e.component;
                    }
                },
                validatorInstance: null
            },
            queryDateFrom: {
                ControlOption: {
                    acceptCustomValue: false,
                    displayFormat: "yyyy-MM-dd",
                    maxZoomLevel: "month",
                    minZoomLevel: "year",
                    placeholder: $translate.instant('AccountVoucher_Placeholder_Date'),
                    showClearButton: true,
                    bindingOptions: {
                        value: "queryParams.inputs.date.from"
                    }
                },
                validatorOption: {
                    validationRules: [],
                    onInitialized: function (e) {
                        $scope.dxControlsOptions.queryDateFrom.validatorInstance = e.component;
                    }
                },
                validatorInstance: null
            },
            queryDateTo: {
                ControlOption: {
                    acceptCustomValue: false,
                    displayFormat: "yyyy-MM-dd",
                    maxZoomLevel: "month",
                    minZoomLevel: "year",
                    placeholder: $translate.instant('AccountVoucher_Placeholder_Date'),
                    showClearButton: true,
                    bindingOptions: {
                        value: "queryParams.inputs.date.to"
                    }
                },
                validatorOption: {
                    validationRules: [],
                    onInitialized: function (e) {
                        $scope.dxControlsOptions.queryDateTo.validatorInstance = e.component;
                    }
                },
                validatorInstance: null
            },
            queryAccountCode: {
                dataSource: $scope.autocompleteDataSource,
                minSearchLength: 1,
                maxItemCount: 7,
                searchTimeout: 50,
                maxlength: 12,
                placeholder: $scope.autocompleteAccountCodePlaceholder,
                valueExpr: 'acctCode',
                searchExpr: 'acctCode',
                focusStateEnabled: true,
                itemTemplate: 'autocompleteAcctCodeItemTemplate',
                bindingOptions: {
                    disabled: "!queryParams.selectors.accountCode.selected.id",
                    searchMode: 'autocompleteAccountCodeSearchMode',
                    value: 'queryParams.inputs.accountCode'
                },
                onInitialized: function (e) {

                    var initialBtn = function () {
                        if (e.element.find(".dx-texteditor-buttons-container").length < 1)
                            return false;

                        if (e.element.find(".display-flex.dx-dropdowneditor-icon").length > 0)
                            return true;

                        var btnStr = '<div class="dx-dropdowneditor-button dx-button-normal dx-widget" ng-click="popTheParentCode($event)" role="button">' +
                            '<div class="dx-button-content">' +
                            '<div class="dx-dropdowneditor-icon display-flex justify-content-center align-items-center">' +
                            '<i class="fa fa-columns"></i>' +
                            '</div></div></div>';

                        var button = $(btnStr);
                        var container = e.element.find(".dx-texteditor-buttons-container");
                        container.empty();
                        container.append($compile(button)($scope));
                        e.element.find(".dx-texteditor-input").css("padding-right", "34px");
                        return true;
                    }

                    var tryInitialBtn = function () {
                        if (initialBtn())
                            return;

                        var rst = $timeout(initialBtn, 100);
                        rst.then(function (data) {
                            if (!data)
                                tryInitialBtn();

                        });
                    }
                    tryInitialBtn();
                }
            },
            queryAccountName: {
                dataSource: $scope.autocompleteDataSource,
                minSearchLength: 1,
                maxItemCount: 7,
                searchTimeout: 50,
                maxlength: 12,
                placeholder: $scope.autocompleteAccountNamePlaceholder,
                valueExpr: 'name',
                searchExpr: 'name',
                focusStateEnabled: true,
                itemTemplate: 'autocompleteAccountNameItemTemplate',
                bindingOptions: {
                    disabled: "!queryParams.selectors.accountName.selected.id",
                    searchMode: 'autocompleteAccountNameSearchMode',
                    value: 'queryParams.inputs.accountName'
                }
            }
        };

        //凭证重对应编辑时, 勾选已重对应的凭证
        var setVoucherSelected = function () {
            $log.debug("setVoucherSelected");
            if ($scope.isFromReMapping && !_.isUndefined($scope.selectedVouchers) && !_.isNull($scope.selectedVouchers)
                && !_.isUndefined($scope.voucherDataList) && !_.isNull($scope.voucherDataList)
                && $scope.selectedVouchers.length > 0 && $scope.voucherDataList.length > 0) {
                $log.debug("star to setVoucherSelected");
                var voucherIndexArray = [];
                $scope.selectedVouchers.forEach(function (item, index) {
                    $scope.voucherDataList.forEach(function (vdItem, vdIndex) {
                        if (_.isEqual(item.voucherID, vdItem.voucherID)) {
                            $log.debug(vdIndex);
                            voucherIndexArray.push(vdIndex);

                        }
                    });
                });
                $log.debug(voucherIndexArray);
                $('#gridContainer').dxDataGrid('instance').selectRowsByIndexes(voucherIndexArray);
            }
        }

        //从科目对应调用时,初始化整个页面
        function InitPageFromReMapping(fromReMapping) {
            $log.debug("start InitPageFromReMapping");        
            if (fromReMapping) { 
                //初始化页面样式
                $("#mainPreviewDiv").addClass('vat-preview-account-voucher-accountmapping');
                $("#filterMode-normal").css({ "left": 10 + "px" });
                                                      
                //初始化grid
                $("#gridContainer").dxDataGrid({                  
                    selection: {
                        mode: 'multiple',
                        allowSelectAll: false,
                        selectAllMode: 'allPages',
                        showCheckBoxesMode: 'always'
                    },
                    onSelectionChanged: function (selectedItems) {
                        $scope.selectedVouchers = selectedItems.selectedRowsData;
                        VoucherReMapping($scope.selectedVouchers);
                    }
                });
            }
        }


        function VoucherReMapping(selectedVouchers) {
            $log.debug("start VoucherReMapping");
            $log.debug(selectedVouchers);
        }


        //科目重对应时设置默认的查询条件
        function setRemapSearchConditions() {
            if ($scope.isFromReMapping && $scope.isEdit) {
                $log.debug("start to setRemapSearchConditions");
                $scope.resetSelectCondition();
                $scope.queryParams.listQueryCondition = [];
                var acctMto = {};
                //科目代码
                acctMto.conditionName = $translate.instant('AccountVoucher_AccountCode');
                acctMto.searchKeyWord = "1";
                acctMto.searchValue = $scope.enterpriseCode;
                $scope.queryParams.listQueryCondition.push(acctMto);

                //会计期间
                var periodMto = {};
                periodMto.conditionName = $translate.instant('AccountVoucher_Period');
                periodMto.searchKeyWord = 14;
                periodMto.searchValue = startMonth + " " + endMonth; //eg: "5 5" 
                $scope.queryParams.listQueryCondition.push(periodMto);

                //其它查询条件
                $scope.queryParams.pagingInfo = { pageIndex: 1, pageSize: 100, totalCount: 87 };
                $scope.queryParams.andOr = "AND",
                $scope.queryParams.mainRelation = '8';
                $scope.queryParams.allJe = false;
                $scope.queryParams.isEntryShow = true;
                $scope.queryParams.period = "";
                $scope.queryParams.vID = "";
                $scope.queryParams.group = null;

                $log.debug($scope.queryParams);
            }
        }

        //开始
        (function initialize() {
            $scope.curVoucherItemPage = 1;
            $scope.selectVoucher = selectVoucher;
            $scope.resetSelectCondition = resetSelectCondition;
            $scope.voucherShow = voucherShow;
            $scope.entryShow = entryShow;
            $scope.selectedVouchers;
            $scope.enterpriseCode;
            $scope.setVoucherSelected = setVoucherSelected;
            $scope.isEdit;
            $scope.exportToExcel = exportToExcel;
            showVoucherCount("0", "0", "0", "0", null);
            computeVoucherItemPage(true);
            $timeout(function () {
                initDataGrid();
                InitPageFromReMapping($scope.isFromReMapping);
            }, 100);

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

//树形控件弹出模态框
commonModule.controller('vatPreviewAccountVoucherAccountCodeCtrl', ["$scope", "$translate", "$uibModalInstance", "ivhTreeviewBfs", function ($scope, $translate, $uibModalInstance, ivhTreeviewBfs) {
    var $ctrl = this;

    var initControls = function () {

        var itemSource = angular.copy($scope.$parent.accountCodes);
        var dic = {};

        var debit = $translate.instant('AccountVoucher_Direction_Debit'), credit = $translate.instant('AccountVoucher_Direction_Credit');
        for (var ix = 0; ix < itemSource.length; ix++) {
            var item = itemSource[ix];
            dic[item.acctCode] = {
                id: item.acctCode,
                code: item.acctCode,
                name: item.name,
                selected: false,
                parentNode: null,
                parentCode: item.parentCode,
                direction: item.direction == 1 ? debit : credit,
                children: [],
                data: item
            };
        }

        //查找每个节点是否存在父节点,并维护父节点与本节点的关系
        for (var key in dic) {
            if (dic.hasOwnProperty(key)) {
                var item = dic[key];
                var pCode = item.parentCode || "undefined";
                var p = dic[pCode];
                if (!p)
                    continue;

                if (pCode == "undefined")
                    throw "parentCode is undefined,please check the data in database";

                item.parentNode = p;
                p.children.push(item);
            }
        }

        //node 是已经转化的数据结构
        var trans = function (node) {
            for (var ix = 0; ix < node.children.length; ix++) {
                var cn = node.children[ix];
                cn.parentNode = node;
                trans(cn);
            }
        }

        //对于树节点的根节点(没有父节点信息的节点)的所有子节点数据格式进行转换,并缓存到所有根节点 srcData 中
        var srcData = [];
        for (var key in dic) {
            if (dic.hasOwnProperty(key)) {
                var item = dic[key];
                if (!item || item.parentNode)
                    continue;

                trans(item);
                srcData.push(item);
            }
        }

        //会计科目分类
        var groupData = [
            {
                id: "1",
                code: "资产",
                name: "",
                selected: false,
                direction: "",
                data: null,
                children: []
            }, {
                id: "2",
                code: "负债",
                name: "",
                selected: false,
                direction: "",
                data: null,
                children: []
            }, {
                id: "3",
                code: "共同",
                name: "",
                selected: false,
                direction: "",
                data: null,
                children: []
            }, {
                id: "4",
                code: "权益",
                name: "",
                selected: false,
                direction: "",
                data: null,
                children: []
            }, {
                id: "5",
                code: "成本",
                name: "",
                selected: false,
                direction: "",
                data: null,
                children: []
            }, {
                id: "6",
                code: "损益",
                name: "",
                selected: false,
                direction: "",
                data: null,
                children: []
            }
        ];

        //其他未知类型
        var other = {
            id: "0",
            code: "其他",
            name: "",
            selected: false,
            direction: "",
            data: null,
            children: []
        };

        //将会计科目进行分类
        for (var ix = 0; ix < srcData.length; ix++) {
            item = srcData[ix];
            var p = _.find(groupData, function (n) {
                return Number(n.id) === Number(item.data.acctProp);
            });

            if (p) {
                item.parentNode = p;
                item.parentCode = p.id;
                p.children.push(item);
            } else {
                other.children.push(item);
            }
        }

        if (other.children.length > 0) {
            groupData.push(other);
        }


        $ctrl.treeSrcData = groupData;

        $ctrl.treeViewOps = {
            idAttribute: 'id',
            labelAttribute: 'code',
            childrenAttribute: 'children',
            selectedAttribute: 'selected',
            useCheckboxes: true,
            expandToDepth: 0,
            validate: true,
            defaultSelectedState: false,
            twistieExpandedTpl: '<span class="fa fa-caret-right"></span>',
            twistieCollapsedTpl: '<span class="fa fa-caret-right"></span>',
            twistieLeafTpl: ' ',
            nodeTpl: [
                '<div class="ivh-treeview-node-content" title="{{trvw.label(node)}}">',
                '<div>',
                '<div>',
                '<span ivh-treeview-toggle>',
                '<span class="ivh-treeview-twistie-wrapper" ivh-treeview-twistie></span>',
                '</span>',
                '<span class="ivh-treeview-checkbox-wrapper" ng-if="trvw.useCheckboxes()" ivh-treeview-checkbox></span>',
                '<span class="ivh-treeview-node-label" ivh-treeview-label-select>{{trvw.label(node)}}</span>',
                '</div>',
                '<span class="accountName">{{node.name}}</span>',
                '<span class="debitOrCredit">{{node.direction}}</span>',
                '</div>',
                '<div ivh-treeview-children></div>',
                '</div>'
            ].join('\n')
        };

    }

    $ctrl.ok = function () {

        var selects = [];
        ivhTreeviewBfs($ctrl.treeSrcData, $ctrl.treeViewOps, function (node) {
            if (node.selected && node.id && node.id.toString().length > 1)
                selects.push(node.id);

            return true;
        });

        selects = selects.join(' ');
        $scope.$parent.queryParams.inputs.accountCode = selects;
        $uibModalInstance.close();
    };

    $ctrl.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

    initControls();
}]);