vatModule.controller('vatAccountMappingController', ['$scope', '$log', '$timeout',
    '$q', '$translate', '$interval', 'loginContext', 'apiInterceptor', 'SweetAlert',
    'vatReductionService', 'vatSessionService', 'uiGridConstants', 'enums',
    'i18nService', 'BSPLService', 'vatCommonService', '$uibModal', 'commonWebService', 'vatOperationLogService',
    'vatImportService',
function ($scope, $log, $timeout, $q, $translate, $interval, loginContext, apiInterceptor,
    SweetAlert, vatReductionService, vatSessionService, uiGridConstants, enums,
    i18nService, BSPLService, vatCommonService, $uibModal, commonWebService, vatOperationLogService, vatImportService) {
    'use strict';
    $log.debug('vatAccountMappingController.ctor()...');
    var period = vatSessionService.month; //period < 0 覆盖导入时会删除所有数据
    var projectRuleId = 2; //todo: 应该在vatSessionService.project中获取
    var projectId = vatSessionService.project.id;
    var selectedRemapType = -1;
    //写日志
    var comment = vatSessionService.project.name + " " + vatSessionService.project.year + "年" + vatSessionService.month + "月";
    $scope.moduleid = enums.vatModuleEnum.Import_AccountMapping;
    $scope.periodId = vatSessionService.month;
    var logDto = {
        ID: '',
        OperationName: '',
        ModuleID: $scope.moduleid,
        OperationObject: '',
        OperationType: '',
        OperationContent: '',
        OriginalState: '',
        UpdateState: '',
        CreatorID: vatSessionService.logUser.ID,
        Comment: comment,
        IP: '',
        Period: $scope.periodId,
    };

    var stdDto = {
        id: '',
        acctProp: '',
        code: '',
        direction: '',
        fullName: '',
        hasChildren: false,
        name: '',
        parent: ''
    };

    //添加企业科目过滤下拉列表
    var InitFilterAccount = function () {
        var data = constant.espAccountFilter.data;
        data.forEach(function (row) {
            row.value = $translate.instant(row.value);
        });

        $scope.accountFilterList = data;
    };

    $scope.isSelected = function (id) {
        return $scope.filter.selected.indexOf(id) >= 0;
    };


    var showOperateLogPop = function () {
        $scope.isShowLog = true;
    }

    //检查用户机构权限
    var checkUserOrganizationPermissionList = function () {
        var list = [];
        var userManageTemp = constant.vatPermission.dataManage.accountMapping;
        list.push(userManageTemp.importCode);
        $scope.hasImportPermission = false;
        $scope.$root.checkUserOrganizationPermissionList(list).success(function (data) {
            $scope.hasImportPermission = data[userManageTemp.importCode];
        });
    };

    //初始化企业科目数据列表
    var InitEnterpriseSubject = function () {
        vatReductionService.mapStdCodeRecursiveByAccountList(period).success(function (or) {
            if (or.result) {
                var data = or.data;
                if (data === null) return;
                data.forEach(function (row) {
                    //row.directionStr = _.find($scope.directionList, function (num) {
                    //    return num.id === row.direction;
                    //}).name;
                    if (row.acctProp) {

                    }
                    if (row.acctLevel != null) {
                        row.$$treeLevel = parseInt(row.acctLevel - 1);
                    }

                    row.stdResult = getStdResult(row.stdCode, row.stdFullName);
                });

                $log.debug("InitEnterpriseSubject success");
                $log.debug(data);
                $scope.gridOptionsSubjectList.data = data;
                $scope.EnterpriceAccountList = data;
            }
        });
    };


    //切换筛选条件的时候,ng-check event will be triggered
    var stateChanged = function ($event, data) {
        $scope.filter.selected = [];
        $scope.filterConditionDesc = '';
        var checkbox = $event.target;
        if (checkbox.checked && $scope.filter.selected.indexOf(data.key) < 0) {
            $scope.filter.selected.push(data.key);
            $scope.filterConditionDesc = data.value;
        }

        accountFilterChanged();
    };

    //根据不同的状态过滤,未对应,已对应,借贷方向不一致等
    var accountFilterChanged = function () {
        var selectArr = $scope.filter.selected;
        var data = $scope.EnterpriceAccountList;
        var tempData = [];
        var key = $scope.filter.selected[0] || constant.espAccountFilter.key_0;

        switch (key) {
            //所有对应状态,取默认值
            case constant.espAccountFilter.key_0:
                tempData = data;
                break;
                //未对应
            case constant.espAccountFilter.key_1:
                tempData = _.filter(data, function (item) {
                    return item.stdCode == null;
                });
                break;
                //已对应
            case constant.espAccountFilter.key_2:
                tempData = _.filter(data, function (item) {
                    return item.stdCode != null;
                });
                break;
                //借贷方向不一致
            case constant.espAccountFilter.key_3:
                tempData = _.filter(data, function (item) {
                    return item.stdCode != null && item.stdCode != "-" && item.direction != 0
                        && item.stdDirection != null && item.directionDescription != item.stdDirection;
                });
                break;
                //科目类型不一致
            case constant.espAccountFilter.key_4:
                tempData = _.filter(data, function (item) {
                    return item.stdCode != null && item.stdCode != "-" && item.enterAcctProp != 0 && item.enterAcctProp != item.stdAcctProp;
                });
                break;
        }

        $scope.gridOptionsSubjectList.data = tempData;
    };


    ///根据标准科目code和name获取最终界面上应该显示的内容
    var getStdResult = function (stdCode, stdName) {
        var stdResult = stdCode === null ? $translate.instant('Unmapped') : (stdCode === "0000" ? "-" : stdCode + "-" + stdName);
        return stdResult;
    }

    //初始数据
    var InitNgData = function () {
        $scope.stdCollapsed = true;
        $scope.accountFilterList = [];
        //初始化选择器为空
        $scope.filter = {};
        $scope.filter.selected = [];
        //初始化企业科目筛选列表
        InitFilterAccount();
        //设置默认过滤条件为:所有对应状态
        var allMappStatus = constant.espAccountFilter.data[0];
        $scope.filter.selected.push(allMappStatus.key);
        $scope.filterConditionDesc = $translate.instant('AllMappingStatus');

        $timeout(function () {
            $scope.isLoadComplete = true;
        }, 500);
    }

    var getUITreeScope = function (uiTreeID) {
        return angular.element(document.getElementById(uiTreeID)).scope();
    };

    //如果没有全部展开,return false.
    var isExpandAll = function (uiTreeID) {
        var childNodes = getUITreeScope(uiTreeID).childNodes();

        var isCollapsed = function (c) {
            if (c.collapsed)
                return true;

            var childs = c.childNodes();

            for (var i = 0; i < childs.length; i++) {
                if (isCollapsed(childs[i])) {
                    return true;
                }
            }
            return false;
        }

        return !_.some(childNodes, isCollapsed);
    };


    //标准科目,单独展开或折叠
    var toggle1 = function (scope) {
        scope.toggle();
        if (scope.collapsed) {
            $scope.stdCollapsed = true;
        }
        else {
            //如果全部展开,最顶层也要展开
            if (isExpandAll('tree-root')) {
                $scope.stdCollapsed = false;
            }
        }
    };

    //标准科目,全部展开或折叠
    var toggleStdSubject = function () {
        $scope.stdCollapsed = !$scope.stdCollapsed;
        commonWebService.expandCollapseAll('vatStadardAccountTreeTable', $scope.stdCollapsed);
    }

    var updateParentEnterpriseAccount = function (parentMapingDict) {
        for (var key in parentMapingDict) {
            $scope.gridApiSubject.grid.rows.forEach(function (row) {
                if (row.entity.code === key) {
                    row.entity['stdCode'] = parentMapingDict[key][0];
                    row.entity['stdName'] = parentMapingDict[key][1];
                    row.entity['stdResult'] = getStdResult(parentMapingDict[key][0], parentMapingDict[key][2]);
                }
            });
        }
    };

    //当在取消或者手动对应之后更新界面
    //selectedRows: uigrid中当前选中的行集合
    //codeToUpdate: 需要将旧的代码设置为该code
    //nameToUpdate: 需要将旧的科目名称设置为该name
    var updateChildrenEnterpriseAccount = function (selectedRows, codeToUpdate, nameToUpdate) {
        //codeToUpdate = null && nameToUpdate = '': 取消对应
        if (!_.isNull(codeToUpdate) && nameToUpdate != '') {
            getStdCodeListRescurive();
        }

        var stdDto = _.where($scope.stdAccountList, { code: codeToUpdate })[0];
        selectedRows.forEach(function (v) {
            v['stdCode'] = codeToUpdate;
            v['stdName'] = nameToUpdate;
            v['stdResult'] = getStdResult(codeToUpdate, nameToUpdate);
            if (!_.isUndefined(stdDto)) {
                v['stdAcctProp'] = parseInt(stdDto.acctProp);
                v['stdCodeName'] = codeToUpdate + '/' + stdDto.fullName;
                v['stdDirection'] = stdDto.direction === "1" ? $translate.instant('StandardAccountDebit') : $translate.instant('StandardAccountCredit');
                v['stdFullName'] = stdDto.fullName;
            }

            //取消对应
            if (_.isNull(codeToUpdate) && nameToUpdate === '') {
                v['stdAcctProp'] = null;
                v['stdCodeName'] = null;
                v['stdDirection'] = null;
                v['stdFullName'] = null;
            }


            //找出该选中节点的所有子节点,然后复制,避免再次从数据库获取数据
            $scope.gridApiSubject.grid.rows.forEach(function (row) {
                if (row.entity.parent === v.code) {
                    row.entity['stdCode'] = codeToUpdate;
                    row.entity['stdName'] = nameToUpdate;
                    row.entity['stdResult'] = getStdResult(codeToUpdate, nameToUpdate);

                    //再次更新该row下面的子节点如果存在的话
                    updateChildrenMappedCodeNameRecursive($scope.gridApiSubject.grid.rows, row.entity['code'], codeToUpdate, nameToUpdate);
                }
            });
        });
    };

    var updateChildrenMappedCodeNameRecursive = function (rows, filterCode, codeToUpdate, nameToUpdate) {
        $scope.gridApiSubject.grid.rows.forEach(function (row) {
            if (row.entity.parent === filterCode) {
                row.entity['stdCode'] = codeToUpdate;
                row.entity['stdName'] = nameToUpdate;
                row.entity['stdResult'] = getStdResult(codeToUpdate, nameToUpdate);

                //再次更新该row下面的子节点如果存在的话
                updateChildrenMappedCodeNameRecursive($scope.gridApiSubject.grid.rows, row.entity['code'], codeToUpdate, nameToUpdate);
            }
        });
    }

    function getStatusByCurrentStatus(isSubmit) {
        if (!isSubmit &&
            (_.isEqual(vatSessionService.project.projectStatusList[period], constant.ProjectStatusEnum.Imported)
            || _.isEqual(vatSessionService.project.projectStatusList[period], constant.ProjectStatusEnum.AccountMapSubmitted))) {
            return constant.ProjectStatusEnum.Imported;
        }

        if (isSubmit &&
           (_.isEqual(vatSessionService.project.projectStatusList[period], constant.ProjectStatusEnum.Imported)
           || _.isEqual(vatSessionService.project.projectStatusList[period], constant.ProjectStatusEnum.AccountMapSubmitted))) {
            return constant.ProjectStatusEnum.AccountMapSubmitted;
        }

        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.Generated) {
            return vatSessionService.project.projectStatusList[period];
        }
    }

    function doAutoMap() {
        logDto.ID = PWC.newGuid();
        logDto.CreateTime = new Date();
        logDto.UpdateTime = new Date();
        logDto.OperationContent = "";
        logDto.OriginalState = "";
        logDto.OperationName = $translate.instant('AutoMapping');
        logDto.OperationType = enums.vatLogOperationTypeEnum.AM_AutoMapping;

        vatReductionService.autoMap(projectRuleId, period).success(function (or) {
            if (or != null && or != undefined) {
                if (or.result) {
                    getEnterpriseAccountNotMapped();
                    var status = getStatusByCurrentStatus(false);
                    vatCommonService.setProjectStatus(projectDbName, period, status, constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.NotFinished);
                    logDto.UpdateState = $translate.instant('AccountMapSuccess');
                    vatOperationLogService.addOperationLog(logDto);
                    // mapping success
                    SweetAlert.success($translate.instant('AccountMapSuccess'));
                    InitEnterpriseSubject();
                }
                else {
                    SweetAlert.warning($translate.instant(or.resultMsg));
                }
            }
            else {
                logDto.UpdateState = $translate.instant('AccountMapFailed');
                vatOperationLogService.addOperationLog(logDto);
                SweetAlert.warning($translate.instant('AccountMapFailed'));
            }
        });
    }

    //自动对应
    var autoMap = function () {
        if (vatSessionService.project.projectStatusList[period] < constant.ProjectStatusEnum.Imported) {
            SweetAlert.warning($translate.instant('AutoMapWarning'));
        }

        if (vatSessionService.project.projectStatusList[period] === constant.ProjectStatusEnum.Imported) {
            doAutoMap();
        }

        if (vatSessionService.project.projectStatusList[period] > constant.ProjectStatusEnum.Imported) {
            swal({
                title: $translate.instant('WarningTitle'),
                text: $translate.instant('IsConfirmToReMap').formatObj({ status: vatCommonService.getProjectStautsEnumDesc(vatSessionService.project.projectStatusList[period]) }),
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Yes'),
                cancelButtonText: $translate.instant('No'),
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    doAutoMap();
                }
                else {
                    swal.close();
                }
            });
        }
    };


    function doClearMap() {
        var clearEnterpriseAccountCodes = [];
        var selectedRows = $scope.gridApiSubject.selection.getSelectedRows();
        var orignalStdCodeName = [];
        if (selectedRows.length === 0) {
            SweetAlert.warning($translate.instant('SelectOneAccountToClearMap'));
            return;
        }

        selectedRows.forEach(function (v) {
            clearEnterpriseAccountCodes.push(v['code']);
            orignalStdCodeName.push(v.stdResult);
        });


        logDto.ID = PWC.newGuid();
        logDto.CreateTime = new Date();
        logDto.UpdateTime = new Date();
        logDto.OriginalState = orignalStdCodeName.join(",");
        logDto.UpdateState = "";
        logDto.OperationContent = "";
        logDto.OperationName = $translate.instant('CancelMapping');
        logDto.OperationObject = clearEnterpriseAccountCodes.join(",");
        logDto.OperationType = enums.vatLogOperationTypeEnum.AM_CancelMapping;



        vatReductionService.clearMap(period, clearEnterpriseAccountCodes).success(function (or) {
            if (or != null && or != undefined) {
                if (or.result) {
                    getEnterpriseAccountNotMapped();
                    var status = getStatusByCurrentStatus(false);
                    vatCommonService.setProjectStatus(project.id, period, status, constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.NotFinished);
                    // clear mapping success
                    SweetAlert.success($translate.instant('ClearMapSuccess'));
                    //如果重新从数据库加载,数据会重新绑定然后感觉界面被刷新
                    updateChildrenEnterpriseAccount(selectedRows, null, '');
                    updateParentEnterpriseAccount(or.data);
                    //清除所有checkbox
                    $scope.gridApiSubject.selection.clearSelectedRows();
                    vatOperationLogService.addOperationLog(logDto);
                }
                else {
                    logDto.UpdateState = $translate.instant('ClearMapFailed');
                    vatOperationLogService.addOperationLog(logDto);
                    SweetAlert.warning($translate.instant(or.resultMsg));
                }
            }
            else {
                logDto.UpdateState = $translate.instant('ClearMapFailed');
                vatOperationLogService.addOperationLog(logDto);
                SweetAlert.warning($translate.instant('ClearMapFailed'));
            }
        });
    }

    //取消对应
    var ClearMap = function () {
        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.AccountMapSubmitted) {
            swal({
                title: $translate.instant('WarningTitle'),
                text: $translate.instant('IsConfirmCancelMap').formatObj({ status: vatCommonService.getProjectStautsEnumDesc(vatSessionService.project.projectStatusList[period]) }),
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Yes'),
                cancelButtonText: $translate.instant('No'),
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    doClearMap();
                }
                else {
                    swal.close();
                }
            });
        }
        else {
            SweetAlert.warning($translate.instant('CancelMapWarning'));
            //doClearMap();
        }
    };

    function doMapStdAccount(code, name, acctProp, direction) {
        if (!$scope.hasImportPermission || $scope.isSubmitted) {
            if ($scope.isSubmitted) {
                $timeout(function () {
                    SweetAlert.warning($translate.instant('UndoAccountMapToMap'));
                }, 300)

            }
            return false;
        }
        var accountMap = {};
        var rowIndexArray = [];
        var isMapped = false;
        var isAcctPropMatched = false;
        var isDirectionMatched = false;

        accountMap.enterpriseAccountCodes = [];
        accountMap.standardAccountCode = code;

        var selectedRows = $scope.gridApiSubject.selection.getSelectedRows();
        if (selectedRows.length === 0) {
            SweetAlert.warning($translate.instant('SelectOneAccountToMap'));
            return;
        }

        var stdAcctProp = acctProp;
        var stdDirection = direction;
        var orignalStdCodeName = [];
        selectedRows.forEach(function (v) {
            accountMap.enterpriseAccountCodes.push(v['code']);
            var rowIndex = findIndexByKeyValue($scope.gridOptionsSubjectList.data, "code", v['code']);
            rowIndexArray.push(rowIndex);
            orignalStdCodeName.push(v.stdResult);
            var stdCode = v['stdCode'];
            var acctProp = v['enterAcctProp'].toString();
            var direction = v['direction'].toString();

            //判断企业科目是否已有对应的标准科目,如果有isMapped=true
            isMapped = !_.isNull(stdCode) ? true : false;

            //判断企业科目和标准科目的类型否一致,如果不一致,isAcctPropMatched=false
            if (acctProp !== -1 && !_.isNull(acctProp) && stdAcctProp !== acctProp) {
                isAcctPropMatched = false;
            }
            else {
                isAcctPropMatched = true;
            }

            //判断企业科目和标准科目的借贷方是否一致,如果不一致,isDirectionMatched=false
            if (stdDirection !== direction) {
                isDirectionMatched = false;
            }
            else {
                isDirectionMatched = true;
            }
        });

        logDto.ID = PWC.newGuid();
        logDto.CreateTime = new Date();
        logDto.UpdateTime = new Date();
        logDto.OriginalState = orignalStdCodeName.join(",");
        logDto.UpdateState = code + "-" + name;
        logDto.OperationContent = code;
        logDto.OperationName = $translate.instant('HandleMapping');
        logDto.OperationObject = accountMap.enterpriseAccountCodes.join(",");
        logDto.OperationType = enums.vatLogOperationTypeEnum.AM_ManualMapping;


        //如果已经map过
        if (isMapped) {
            msgboxOptions.text = $translate.instant('ComfirmToReMap');
            msgboxOptions.closeOnConfirm = isAcctPropMatched && isDirectionMatched ? true : false;
            SweetAlert.swal(msgboxOptions, function (isConfirm) {
                if (isConfirm) {
                    //如果科目类型不一致
                    if (!isAcctPropMatched) {
                        msgboxOptions.text = $translate.instant('ConfirmToMapForDiffAcctProp');
                        msgboxOptions.closeOnConfirm = isDirectionMatched ? true : false;
                        SweetAlert.swal(msgboxOptions, function (isConfirm) {
                            if (isConfirm) {
                                //如果科目类型一致,则判断借贷方向是否一致
                                if (!isDirectionMatched) {
                                    msgboxOptions.text = $translate.instant('ConfirmToMapForDiffDirection');
                                    msgboxOptions.closeOnConfirm = true;
                                    SweetAlert.swal(msgboxOptions, function (isConfirm) {
                                        if (isConfirm) {
                                            mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                                        } else {
                                            swal.close();
                                        }
                                    });
                                } else {
                                    mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                                }
                            } else {
                                swal.close();
                            }
                        });
                    }
                    else {
                        //如果借贷方向不一致
                        if (!isDirectionMatched) {
                            msgboxOptions.text = $translate.instant('ConfirmToMapForDiffDirection');
                            msgboxOptions.closeOnConfirm = true;
                            SweetAlert.swal(msgboxOptions, function (isConfirm) {
                                if (isConfirm) {
                                    mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                                } else {
                                    swal.close();
                                }
                            });
                        }
                        else {
                            mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                        }
                    }
                } else {
                    swal.close();
                }
            });
        }
        else {
            //如果没有map过,则判断科目类型是否一致
            if (!isAcctPropMatched) {
                msgboxOptions.text = $translate.instant('ConfirmToMapForDiffAcctProp');
                msgboxOptions.closeOnConfirm = isDirectionMatched ? true : false;
                SweetAlert.swal(msgboxOptions, function (isConfirm) {
                    if (isConfirm) {
                        //如果科目类型一致,则判断借贷方向是否一致
                        if (!isDirectionMatched) {
                            msgboxOptions.text = $translate.instant('ConfirmToMapForDiffDirection');
                            msgboxOptions.closeOnConfirm = true;
                            SweetAlert.swal(msgboxOptions, function (isConfirm) {
                                if (isConfirm) {
                                    mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                                } else {
                                    swal.close();
                                }
                            });
                        } else {
                            mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                        }
                    } else {
                        swal.close();
                    }
                });
            }
            else {
                //如果借贷方向不一致
                if (!isDirectionMatched) {
                    msgboxOptions.text = $translate.instant('ConfirmToMapForDiffDirection');
                    msgboxOptions.closeOnConfirm = true;
                    SweetAlert.swal(msgboxOptions, function (isConfirm) {
                        if (isConfirm) {
                            mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                        } else {
                            swal.close();
                        }
                    });
                } else {
                    mapAccountParentChild(selectedRows, accountMap, code, name, logDto);
                }
            }
        }
    };


    //手动对应,双击页面右侧的标准科目列表执行该事件
    var mapStdAccount = function (code, name, acctProp, direction) {
        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.Imported) {
            if ($scope.manualMapAlter) {
                swal({
                    title: $translate.instant('WarningTitle'),
                    text: $translate.instant('IsConfirmToReMap').formatObj({ status: vatCommonService.getProjectStautsEnumDesc(vatSessionService.project.projectStatusList[period]) }),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: $translate.instant('Yes'),
                    cancelButtonText: $translate.instant('No'),
                    closeOnConfirm: true,
                    closeOnCancel: true
                },
               function (isConfirm) {
                   if (isConfirm) {
                       $scope.manualMapAlter = false;
                       $timeout(function () {
                           doMapStdAccount(code, name, acctProp, direction);
                       }, 300);

                   }
                   else {
                       swal.close();
                   }
               });
            }
            else {
                $timeout(function () {
                    doMapStdAccount(code, name, acctProp, direction);
                }, 300);

            }

        }
        else {
            //doMapStdAccount(code, name, acctProp, direction);
            SweetAlert.warning($translate.instant('ManualMapWarning'));
        }
    };


    var findIndexByKeyValue = function (arrayToSearch, key, valueToSearch) {
        for (var i = 0; i < arrayToSearch.length; i++) {
            if (arrayToSearch[i][key] == valueToSearch) {
                return i;
            }
        }
        return null;
    };

    //弹出框的默认配置项
    var msgboxOptions = {
        title: $translate.instant('ConfirmToContinue'),
        text: $translate.instant('ComfirmToReMap'),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: $translate.instant('Confirm'),
        cancelButtonText: $translate.instant('Cancel'),
        closeOnConfirm: false,
        closeOnCancel: true
    };

    var mapAccountParentChild = function (selectedRows, accountMap, code, name, logDtoValue) {
        vatReductionService.mapAccount(accountMap.standardAccountCode, period, accountMap.enterpriseAccountCodes).success(function (or) {
            if (or.result === true) {
                getEnterpriseAccountNotMapped();
                $scope.gridApiSubject.selection.clearSelectedRows();

                //如果重新从数据库加载,数据会重新绑定然后感觉界面被刷新
                updateChildrenEnterpriseAccount(selectedRows, code, name);
                //更新父级科目的状态
                updateParentEnterpriseAccount(or.data);
                var status = getStatusByCurrentStatus(false);
                vatCommonService.setProjectStatus(project.id, period, status, constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.NotFinished);
                if (!_.isNull(logDtoValue)) {
                    vatOperationLogService.addOperationLog(logDtoValue);
                }
                //SweetAlert.success($translate.instant('AccountMapSuccess'));
            }
            else {
                logDtoValue.UpdateState = $translate.instant('AccountMapFailed');
                if (!_.isNull(logDtoValue)) {
                    vatOperationLogService.addOperationLog(logDtoValue);
                }
                SweetAlert.warning($translate.instant(or.resultMsg).formatObj({ code: or.data.standardAccountCode }));
            }
        });
    };

    $scope.getGridHeight = function () {
        if ($scope.isLoadComplete) {
            return {
                height: $(".subject-corresponding-container #enterprizeAccount .subject-list-grid-warp").height() + "px"
            };
        }
    };


    //动态设定重分类明细grid的高度
    var getReclassificationItemGridHeight = function () {
        if ($scope.isLoadComplete) {
            var y = $("#reclassification-item-wrapper").height();

            // Enough space
            if (y > constant.UIGrid.gapHeight) {
                y = y - constant.UIGrid.gapHeight;
                return { height: (y - $('#topMenu').height()) + "px" };
            } else {
                return { height: '0px' };
            }
        }

        return {};
    };

    //单击企业科目代码,显示重分类grid明细
    var toggleReclassificationGridTab = function () {
        $scope.ImportErrorTag = !$scope.ImportErrorTag;

        // topIcon and content-resize gapBottom 15px
        if (!$scope.ImportErrorTag) {
            setErrorWrapCssDefault();
        } else {

            if (parseInt($('#content-resizer').css('bottom')) < 100) {
                $('#content-resizer').css('bottom', '130px');
                $('.reclassification-item-wrapper').css('height', '130px');
            }
        }
    };

    //重置重分类明细的位置
    var setErrorWrapCssDefault = function () {
        $('#content-resizer').css('bottom', '0px');
        $('.reclassification-item-wrapper').css('height', '0px');
    };

    //点击手工重分类事件
    var manualReclassificate = function () {
        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.Imported) {
            $log.debug("start manualReclassificate");
            setAutoCompleteDataSource("reMapCustStdAutoComplete");
            selectedRemapType = enums.vatReMapType.ReMapCust;
            var selectedRows = $scope.gridApiSubject.selection.getSelectedRows();
            if (selectedRows.length !== 1) {
                SweetAlert.warning($translate.instant('SelectOneAccountToManualReclassificate'));
                return;
            }

            if (!isEnterpriseCodeLeafAcct()) {
                SweetAlert.warning($translate.instant('NotLeafEnterpriseCode'));
                return;
            }

            $scope.enterpriseCode = selectedRows[0].code;
            $scope.processTypeId = enums.processType.Add;
            initReMapCustModel(constant.Operation.Add, -1, null);
            logDto.OperationName = $translate.instant('AddCustRemap');
            logDto.OperationType = enums.vatLogOperationTypeEnum.AM_AddManualClass;
            logDto.OriginalState = "";
            $scope.remapTitle = $translate.instant('AccountMappingTitle') + "  " + selectedRows[0].codeNameDesc;
            resetCustRemapValidation();
            //$("#reMapCustStdAutoComplete").dxAutocomplete("instance").option("value", "");
            $scope.selectedStdCode = "";
            $('#manualReclassificationModal').modal('show');
        }
        else {
            SweetAlert.warning($translate.instant('RemapClickWarning'));
        }
    };

    //点击凭证重分类按钮事件
    var voucherReclassificate = function () {
        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.Imported) {
            $log.debug("start voucherReclassificate");
            selectedRemapType = enums.vatReMapType.ReMapVoucher;
            setAutoCompleteDataSource("reMapStdAutoComplete");
            var selectedRows = $scope.gridApiSubject.selection.getSelectedRows();
            if (selectedRows.length !== 1) {
                SweetAlert.warning($translate.instant('SelectOneAccountToVoucherReclassificate'));
                return;
            }

            if (!isEnterpriseCodeLeafAcct()) {
                SweetAlert.warning($translate.instant('NotLeafEnterpriseCode'));
                return;
            }


            //清空重分类明细选择项
            $scope.gridApiReclassificationItem.selection.clearSelectedRows();
            $scope.enterpriseCode = selectedRows[0].code;
            $scope.processTypeId = enums.processType.Add;
            initReMapVoucherModel(constant.Operation.Add, null, -1);
            $scope.isSearching = true;
            logDto.OperationName = $translate.instant('AddVoucherReMap');
            logDto.OperationType = enums.vatLogOperationTypeEnum.AM_AddVoucherClass;
            logDto.OriginalState = "";
            $scope.remapTitle = $translate.instant('VoucherReclassificationTitle') + "  " + selectedRows[0].codeNameDesc;
            resetVoucerRemapValidation();
            //$("#reMapStdAutoComplete").dxAutocomplete("instance").option("value", "");        
            $scope.selectedStdCode = "";
            $('#voucherReclassificationModal').modal('show');
        }
        else {
            SweetAlert.warning($translate.instant('RemapClickWarning'));
        }
    };

    //企业科目单击事件
    var showReclassificationItemGrid = function (etsRow) {
        $log.debug("start showReclassificationItemGrid");
        if (parseInt($('#content-resizer').css('bottom')) < 100) {
            $('#content-resizer').css('bottom', '20px');
            $('.reclassification-item-wrapper').css('height', '20px');
        }

        initReMapVoucherModel(constant.Operation.Add, null, -1);
        initReMapCustModel(constant.Operation.Add, -1, null);
        var selectedRows = $scope.gridApiSubject.selection.getSelectedRows();
        $scope.enterpriseCode = selectedRows[0].code;
        getReMapItemByCode(etsRow.code);
    };


    function doSaveManualReclassification() {
        $log.debug("start saveManualReclassification");
        constructReMapCustModel(selectedRemapType);
        $log.debug($scope.editManualRModel);


        var stdDto = _.where($scope.stdAccountList, { code: $scope.editManualRModel.stdCode })[0];
        var updateStateStr = "";
        if (!_.isNull(stdDto)) {
            //var directStr = stdDto.direction === "1" ? $translate.instant('StandardAccountDebit') : $translate.instant('StandardAccountCredit');
            updateStateStr = stdDto.code + "-" + stdDto.fullName + ":"
                            + $translate.instant('AccountVoucher_Debit') + ":" + $scope.editManualRModel.reMapDebit + "  "
                            + $translate.instant('AccountVoucher_Credit') + ":" + $scope.editManualRModel.reMapCredit;
        }
        logDto.ID = PWC.newGuid();
        logDto.CreateTime = new Date();
        logDto.UpdateTime = new Date();
        logDto.OperationObject = $scope.enterpriseCode;
        logDto.OperationContent = $scope.editManualRModel.reMapName;
        logDto.UpdateState = updateStateStr;


        vatReductionService.saveManualReclassification($scope.editManualRModel).success(function (or) {
            if (!_.isNull(or) && !_.isUndefined(or)) {
                if (or.result) {
                    $('#manualReclassificationModal').modal('hide');
                    getReMapItemByCode($scope.editManualRModel.code);
                    var status = getStatusByCurrentStatus(false);
                    vatCommonService.setProjectStatus(project.id, period, status, constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.NotFinished);
                    vatOperationLogService.addOperationLog(logDto);
                    InitEnterpriseSubject();
                    SweetAlert.success($translate.instant('CustReMappingSuccess'));
                }
                else {
                    logDto.UpdateState = $translate.instant('AccountReMappingFail');
                    vatOperationLogService.addOperationLog(logDto);
                    SweetAlert.warning($translate.instant(or.resultMsg));
                }
            }
            else {
                logDto.UpdateState = $translate.instant('AccountReMappingFail');
                vatOperationLogService.addOperationLog(logDto);
                SweetAlert.warning($translate.instant('AccountReMappingFail'));
            }

        });
    }

    //保存手工重分类数据
    var saveManualReclassification = function () {
        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.AccountMapSubmitted) {
            swal({
                title: $translate.instant('WarningTitle'),
                text: $translate.instant('IsConfirmManualReClassify').formatObj({ status: vatCommonService.getProjectStautsEnumDesc(vatSessionService.project.projectStatusList[period]) }),
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Yes'),
                cancelButtonText: $translate.instant('No'),
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    doSaveManualReclassification();
                }
                else {
                    swal.close();
                }
            });
        }
        else {
            doSaveManualReclassification();
        }
    };


    function doSaveVoucherReclassification() {
        $log.debug("start saveVoucherReclassification ");
        $scope.isSearching = false;
        constructReMapVoucherModel($scope.selectedVouchers, selectedRemapType, $scope.processTypeId);
        $log.debug($scope.editVoucherRModel);
        $log.debug($scope.selectedVouchers);

        var stdDto = _.where($scope.stdAccountList, { code: $scope.editVoucherRModel.stdCode })[0];
        var updateStateStr = "";
        if (!_.isNull(stdDto)) {
            //var directStr = stdDto.direction === "1" ? $translate.instant('StandardAccountDebit') : $translate.instant('StandardAccountCredit');
            updateStateStr = stdDto.code + "-" + stdDto.fullName + ":"
                            + $translate.instant('AccountVoucher_Debit') + ":" + $scope.editVoucherRModel.reMapDebit + "  "
                            + $translate.instant('AccountVoucher_Credit') + ":" + $scope.editVoucherRModel.reMapCredit;
        }
        logDto.ID = PWC.newGuid();
        logDto.CreateTime = new Date();
        logDto.UpdateTime = new Date();
        logDto.OperationObject = $scope.enterpriseCode;
        logDto.OperationContent = $scope.editVoucherRModel.reMapName;
        logDto.UpdateState = updateStateStr;

        vatReductionService.saveVoucherReclassification($scope.editVoucherRModel).success(function (or) {
            if (!_.isNull(or) && !_.isUndefined(or)) {
                if (or.result) {
                    $('#voucherReclassificationModal').modal('hide');
                    getReMapItemByCode($scope.editVoucherRModel.code);
                    var status = getStatusByCurrentStatus(false);
                    vatCommonService.setProjectStatus(project.id, period, status, constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.NotFinished);
                    vatOperationLogService.addOperationLog(logDto);
                    InitEnterpriseSubject();
                    SweetAlert.success($translate.instant('VoucherReMappingSuccess'));
                }
                else {
                    logDto.UpdateState = $translate.instant('AccountReMappingFail');
                    vatOperationLogService.addOperationLog(logDto);
                    SweetAlert.warning($translate.instant(or.resultMsg));
                }
            }
            else {
                logDto.UpdateState = $translate.instant('AccountReMappingFail');
                vatOperationLogService.addOperationLog(logDto);
                SweetAlert.warning($translate.instant('AccountReMappingFail'));
            }
        });
    }

    //保存凭证重分类数据
    var saveVoucherReclassification = function () {
        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.AccountMapSubmitted) {
            swal({
                title: $translate.instant('WarningTitle'),
                text: $translate.instant('IsConfirmVoucherReClassify').formatObj({ status: vatCommonService.getProjectStautsEnumDesc(vatSessionService.project.projectStatusList[period]) }),
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Yes'),
                cancelButtonText: $translate.instant('No'),
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    doSaveVoucherReclassification();
                }
                else {
                    swal.close();
                }
            });
        }
        else {
            doSaveVoucherReclassification();
        }
    };


    //编辑重对应记录
    var editReMapItem = function () {
        $log.debug("editReMapItem");
        $log.debug($scope.selectedVouchers);
        $scope.isSearching = false;
        $scope.processTypeId = enums.processType.Edit;

        var selectedRows = $scope.gridApiReclassificationItem.selection.getSelectedRows();
        if (!_.isNull(selectedRows) && !_.isUndefined(selectedRows)) {
            if (selectedRows.length === 0) {
                SweetAlert.warning($translate.instant('AccountReMappingSelectOne'));
                return false;
            }
            $log.debug(selectedRows);
            var selectedRemapItem = selectedRows[0];
            var reMapTypeId = selectedRemapItem.reMappTypeId;
            if (reMapTypeId === enums.vatReMapType.ReMapVoucher) {
                $log.debug("edit voucher remap");
                $scope.isSearching = true;
                setAutoCompleteDataSource("reMapStdAutoComplete");
                if (_.isNull($scope.selectedVouchers) || $scope.selectedVouchers.length === 0) {
                    $scope.selectedVouchers = selectedRemapItem.vouchers;
                }

                var vStdDto = _.where($scope.stdAccountList, { code: selectedRemapItem.stdCode })[0];
                var vOriginalState = "";
                if (!_.isNull(vStdDto)) {
                    vOriginalState = vStdDto.code + "-" + vStdDto.fullName + ":"
                            + $translate.instant('AccountVoucher_Debit') + ":" + selectedRemapItem.remapDebit + "  "
                            + $translate.instant('AccountVoucher_Credit') + ":" + selectedRemapItem.remapCredit;
                }

                logDto.OperationName = $translate.instant('EditVoucherReMap');
                logDto.OperationType = enums.vatLogOperationTypeEnum.AM_EditVoucherClass;
                logDto.OriginalState = vOriginalState;

                $log.debug($scope.selectedVouchers);
                $('#voucherReclassificationModal').modal('show');
            }

            if (reMapTypeId === enums.vatReMapType.ReMapCust) {
                $log.debug("edit cust remap");
                setAutoCompleteDataSource("reMapCustStdAutoComplete");
                initReMapCustModel(constant.Operation.Edit, enums.vatReMapType.ReMapCust, selectedRemapItem);

                var vCustStdDto = _.where($scope.stdAccountList, { code: selectedRemapItem.stdCode })[0];
                var vCustOriginalState = "";
                if (!_.isNull(vStdDto)) {
                    vCustOriginalState = vCustStdDto.code + "-" + vCustStdDto.fullName + ":"
                            + $translate.instant('AccountVoucher_Debit') + ":" + selectedRemapItem.remapDebit + "  "
                            + $translate.instant('AccountVoucher_Credit') + ":" + selectedRemapItem.remapCredit;
                }

                logDto.OperationName = $translate.instant('EditCustRemap');
                logDto.OperationType = enums.vatLogOperationTypeEnum.AM_EditManualClass;
                logDto.OriginalState = vCustOriginalState;

                $('#manualReclassificationModal').modal('show');
            }
        }
    }

    //删除重对应记录
    var deleteReMapItem = function () {
        $log.debug("deleteReMapItem");
        var selectedRows = $scope.gridApiReclassificationItem.selection.getSelectedRows();
        $scope.processTypeId = enums.processType.Delete;
        if (selectedRows.length === 0) {
            SweetAlert.warning($translate.instant('AccountReMappingSelectOne'));
            return false;
        }

        if (!_.isNull(selectedRows) && !_.isUndefined(selectedRows)) {
            var selectedRemapItem = selectedRows[0];
            $log.debug(selectedRemapItem);
            deleteReMappingRecords(selectedRemapItem);
        }

    }


    //提交科目对应
    var submitAccountMap = function () {
        if (vatSessionService.project.projectStatusList[period] < constant.ProjectStatusEnum.Imported) {
            SweetAlert.warning($translate.instant('NotAllowSubmitAccountMap'));
            return false;
        }
        vatReductionService.submitAccountMapping(enums.vatReMapType.ReMapVoucher, enums.vatReMapType.ReMapCust).success(function (ret) {
            if (ret.result) {
                BSPLService.GenerateBSPL(vatSessionService.project.id, vatSessionService.month).success(function () {
                    $scope.isSubmitted = true;
                    var status = getStatusByCurrentStatus(true);
                    vatCommonService.setProjectStatus(project.id, period, constant.ProjectStatusEnum.AccountMapSubmitted
                                                      , constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.Finished);
                    SweetAlert.success($translate.instant('AccountMappingSubmitComplete'));
                }).error(function () {
                    SweetAlert.error('生成报表失败');
                });
            }
            else {
                SweetAlert.error($translate.instant('CallbackError').formatObj({ errorMsg: ret.resultMsg }));
            }
        });
    };


    //撤销科目对应
    var undoAccountMap = function () {

        //已提交状态时不用提醒直接撤销
        if (vatSessionService.project.projectStatusList[period] === constant.ProjectStatusEnum.AccountMapSubmitted) {
            $scope.isSubmitted = false;
            var status = getStatusByCurrentStatus(false);
            vatCommonService.setProjectStatus(project.id, period, status, constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.NotFinished);
            SweetAlert.success($translate.instant('UndoAccountMappingComplete'));
        }


        //到底已生成之后需要提醒确认之后再撤销
        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.Generated) {
            swal({
                title: $translate.instant('WarningTitle'),
                text: $translate.instant('IsConfirmUndoMap').formatObj({ status: vatCommonService.getProjectStautsEnumDesc(vatSessionService.project.projectStatusList[period]) }),
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Yes'),
                cancelButtonText: $translate.instant('No'),
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    $scope.isSubmitted = false;
                    var status = getStatusByCurrentStatus(false);
                    vatCommonService.setProjectStatus(project.id, period, status, constant.DictionaryDictKey.WFAccountMap, enums.FinishStatusEnum.NotFinished);
                    SweetAlert.success($translate.instant('UndoAccountMappingComplete'));
                }
                else {
                    swal.close();
                }
            });
        }
        else {
            $scope.isSubmitted = false;
        }
    }

    var onReMapGridRowSelectionChanged = function (entity) {
        $log.debug("onReMapGridRowSelectionChanged");
        $scope.reMappId = entity.remapId;
        $scope.reMapItem = entity;
        if (entity.reMappTypeId === enums.vatReMapType.ReMapVoucher) {
            selectedRemapType = enums.vatReMapType.ReMapVoucher;
            var selectedReMapRow = $scope.gridApiReclassificationItem.selection.getSelectedRows()[0];
            $log.debug(selectedReMapRow);
            if (!_.isNull(selectedReMapRow) && !_.isUndefined(selectedReMapRow)) {
                $scope.selectedVouchers = selectedReMapRow.vouchers;//当前选择的重对应记录关联的vouchers
                $log.debug($scope.selectedVouchers);
            }
            initReMapVoucherModel(constant.Operation.Edit, selectedReMapRow, enums.vatReMapType.ReMapVoucher);

        }

        if (entity.reMappTypeId === enums.vatReMapType.ReMapCust) {
            selectedRemapType = enums.vatReMapType.ReMapCust;
            initReMapCustModel(constant.Operation.Add, -1, null);
        }
    }


    var closeModal = function (e) {
        var buttonId = e.target.id;
        if (!_.isUndefined(buttonId) && !_.isNull(buttonId)) {
            if (_.isEqual(buttonId, "btnCloseStdReMapResult")) {
                $('#stdReMapResultModal').modal('hide');
            }

            if (_.isEqual(buttonId, "btnCloseVoucherRemap")) {
                $scope.isSearching = false;
            }

            if (_.isEqual(buttonId, "btnCloseVouchersDetail")) {
                $('#voucherDetailModal').modal('hide');
            }
        }
    }


    //获取标准科目重对应结果
    var getStdRemapResult = function () {
        //todo: period = -1 is only for test
        vatReductionService.getStdRemapResult(period).success(function (or) {
            if (!_.isUndefined(or) && !_.isNull(or)) {
                if (or.result) {
                    $log.debug("getStdRemapResult success");
                    if (!_.isUndefined(or.data) && !_.isNull(or.data)) {
                        $log.debug(or.data);
                        $scope.gridOptionsStdReMapResult.data = or.data;
                        $('#stdReMapResultModal').modal('show');
                    }
                }
                else {
                    SweetAlert.warning($translate.instant(or.resultMsg));
                }

            }
            else {
                SweetAlert.warning($translate.instant('AccountReMappingFail'));
            }
        });
    }


    function setStdAccountIsLeaf(e) {
        var selectedCode = !_.isUndefined(e.selectedItem.code) ? e.selectedItem.code : e.selectedItem;
        var stdAccount = _.where($scope.stdAccountList, { code: selectedCode })[0];
        if (!_.isUndefined(stdAccount)) {
            $scope.stdAccountIsLeaf = !stdAccount.hasChildren;
        }
    }

    function isStdCodeLeafNode(codeValue) {
        var stdAccount = _.where($scope.stdAccountList, { code: codeValue })[0];
        if (!_.isUndefined(stdAccount)) {
            $scope.stdAccountIsLeaf = !stdAccount.hasChildren;
        }
    }

    function onSelectionChangedHandlerVoucherRemap(e) {
        setStdAccountIsLeaf(e);
        $scope.selectedStdCode = !_.isUndefined(e.selectedItem.code) ? e.selectedItem.code : e.selectedItem;
    }

    function onSelectionChangedHandlerCustRemap(e) {
        setStdAccountIsLeaf(e);
        $scope.selectedStdCode = !_.isUndefined(e.selectedItem.code) ? e.selectedItem.code : e.selectedItem;
    }


    function calcVoucherDebitCredit(vocuhers) {
        var sumDebit = 0.00;
        var sumCredit = 0.00;
        $.each(vocuhers, function (index, element) {
            sumDebit += PWC.parseFloatRound(element.debit, 2);
            sumCredit += PWC.parseFloatRound(element.credit, 2);
        });

        $scope.editVoucherRModel.reMapDebit = PWC.parseFloatRound(sumDebit.toString(), 2);
        $scope.editVoucherRModel.reMapCredit = PWC.parseFloatRound(sumCredit.toString(), 2);
    }


    //提交之前构建editVoucherRModel
    function constructReMapVoucherModel(selectedVouchers, reMapType, processTypeId) {
        var selectedRemapItem = $scope.gridApiReclassificationItem.selection.getSelectedRows()[0];
        var stdCode = "";
        if (!_.isNull(selectedRemapItem) && !_.isUndefined(selectedRemapItem)) {
            switch (processTypeId) {
                case enums.processType.Add:
                    stdCode = "";
                    break;
                case enums.processType.Edit:
                    stdCode = selectedRemapItem.stdCode;
                    break;
            }
        }

        $scope.editVoucherRModel = {
            //reMapId: !_.isUndefined(selectedRemapItem) ? selectedRemapItem.remapId : PWC.newGuid(),
            remapBatchId: !_.isUndefined(selectedRemapItem) ? selectedRemapItem.remapBatchId : PWC.newGuid(),
            code: $scope.enterpriseCode,
            stdCode: $scope.selectedStdCode,//$("#reMapStdAutoComplete").dxAutocomplete("instance").option("value"),
            reMapStdCode: stdCode,
            reMapName: $("#voucherName").val(),
            reMapDebit: PWC.round($("#voucherDebit").val(), 2),
            reMapCredit: PWC.round($("#voucherCredit").val(), 2),
            reMapReason: $("#voucherReason").val(),
            reMapTypeId: reMapType,
            reMapDateTime: new Date(),
            period: period,
            reMapProcessTypeId: processTypeId,
            vouchers: selectedVouchers
        };
    }

    //初始化凭证重分类的model:editVoucherRModel
    function initReMapVoucherModel(operation, reMapModel, reMapType) {
        $log.debug("initReMapVoucherModel");
        if (_.isEqual(operation, constant.Operation.Add)) {
            $scope.editVoucherRModel = {
                //reMapId: PWC.newGuid(),
                remapBatchId: PWC.newGuid(),
                code: $scope.enterpriseCode,
                stdCode: "",
                reMapStdCode: "",
                reMapName: "",
                reMapDebit: 0.00,
                reMapCredit: 0.00,
                reMapReason: "",
                reMapTypeId: reMapType,
                reMapDateTime: new Date(),
                period: period,
                reMapProcessTypeId: $scope.processTypeId,
                vouchers: _.isNull(reMapModel) || _.isUndefined(reMapModel) ? null : reMapModel.vouchers
            };
            $scope.selectedVouchers = null;
        }

        if (_.isEqual(operation, constant.Operation.Edit)) {
            $scope.editVoucherRModel = {
                //reMapId: reMapModel.remapId,
                remapBatchId: reMapModel.remapBatchId,
                code: $scope.enterpriseCode,
                stdCode: reMapModel.stdCode,
                reMapStdCode: reMapModel.stdCode,
                reMapName: reMapModel.reMappName,
                reMapDebit: reMapModel.remapDebit,
                reMapCredit: reMapModel.remapCredit,
                reMapReason: reMapModel.reMappReason,
                reMapTypeId: reMapType,
                reMapDateTime: new Date(),
                period: period,
                reMapProcessTypeId: $scope.processTypeId,
                vouchers: _.isNull(reMapModel) || _.isUndefined(reMapModel) ? null : reMapModel.vouchers
            };
            //$("#reMapStdAutoComplete").dxAutocomplete("instance").option("value", reMapModel.stdCode);
            $scope.selectedStdCode = reMapModel.stdCode;
        }
    }


    function constructReMapCustModel(reMapType) {
        $scope.editManualRModel = {
            code: $scope.enterpriseCode,
            stdCode: $scope.selectedStdCode,//$("#reMapCustStdAutoComplete").dxAutocomplete("instance").option("value"),
            reMapName: $("#manualName").val(),
            reMapDebit: PWC.round($("#manualDebitBal").val(), 2),
            reMapCredit: PWC.round($("#manualCreditBal").val(), 2),
            reMapReason: $("#manualReason").val(),
            reMapTypeId: reMapType,
            period: period
        };
    }


    //初始化手动重分类的model:editManualRModel
    //operation: 操作类型。 constant.Operation.Add: 添加操作; constant.Operation.Edit:编辑操作
    //reMapType: 重对应类型。永远为2
    //reMapItem: 选中的重对应数据。Add操作时为NULL
    function initReMapCustModel(operation, reMapType, reMapItem) {
        if (_.isEqual(operation, constant.Operation.Add)) {
            $scope.editManualRModel = {
                code: "",
                stdCode: "",
                reMapName: "",
                reMapDebit: 0.00,
                reMapCredit: 0.00,
                reMapReason: "",
                reMapTypeId: reMapType,
                period: period
            }
            $scope.selectedVouchers = null;
        }

        if (_.isEqual(operation, constant.Operation.Edit) && !_.isNull(reMapItem)) {
            $scope.editManualRModel = {
                code: reMapItem.acctCode,
                stdCode: reMapItem.stdCode,
                reMapName: reMapItem.reMappName,
                reMapDebit: reMapItem.remapDebit,
                reMapCredit: reMapItem.remapCredit,
                reMapReason: reMapItem.reMappReason,
                reMapTypeId: reMapType,
                period: period
            }
            //$("#reMapCustStdAutoComplete").dxAutocomplete("instance").option("value", reMapItem.stdCode);
            $scope.selectedStdCode = reMapItem.stdCode;
        }

    }


    //获取重对应结果(包含凭证信息)
    function getReMapItemByCode(estCode) {
        vatReductionService.getClassificationList(estCode).success(function (or) {
            if (!_.isNull(or) && !_.isUndefined(or)) {
                if (or.result) {
                    $log.debug(or.data);
                    $scope.gridOptionsReclassificationItem.data = or.data;
                    $log.debug("getReMapItemByCode assigned value finished");
                    $log.debug($scope.gridOptionsReclassificationItem.data);
                }
                else {
                    SweetAlert.warning($translate.instant(or.resultMsg));
                }
            }
            else {
                SweetAlert.warning($translate.instant('AccountReMappingFail'))
            }

        });
    }


    function deleteReMappingRecords(model) {
        logDto.ID = PWC.newGuid();
        logDto.CreateTime = new Date();
        logDto.UpdateTime = new Date();
        logDto.OperationObject = $scope.enterpriseCode;
        logDto.OperationContent = model.reMappName;
        logDto.OriginalState = "";

        var vStdDto = _.where($scope.stdAccountList, { code: model.stdCode })[0];
        var vUpdateState = "";
        if (!_.isNull(vStdDto) && !_.isUndefined(vStdDto)) {
            vUpdateState = vStdDto.code + "-" + vStdDto.fullName + ":"
                    + $translate.instant('AccountVoucher_Debit') + ":" + model.remapDebit + "  "
                    + $translate.instant('AccountVoucher_Credit') + ":" + model.remapCredit;
        }
        logDto.UpdateState = vUpdateState;

        if (model.reMappTypeId === enums.vatReMapType.ReMapVoucher) {
            logDto.OperationType = enums.vatLogOperationTypeEnum.AM_DeleteVoucherClass;
            logDto.OperationName = $translate.instant('DeleteVoucherRemap');
        }


        if (model.reMappTypeId === enums.vatReMapType.ReMapCust) {
            logDto.OperationType = enums.vatLogOperationTypeEnum.AM_DeleteManualClass;
            logDto.OperationName = $translate.instant('DeleteCustRemap');
        }

        vatReductionService.deleteReMappingRecords(model).success(function (or) {
            if (!_.isNull(or) && !_.isUndefined(or)) {
                if (or.result) {
                    getReMapItemByCode(model.acctCode);
                    vatOperationLogService.addOperationLog(logDto);
                    InitEnterpriseSubject();
                    SweetAlert.success($translate.instant('AccountReMappingSuccess'));

                }
                else {
                    logDto.UpdateState = $translate.instant('AccountReMappingFail');
                    vatOperationLogService.addOperationLog(logDto);
                    SweetAlert.warning($translate.instant(or.resultMsg));
                }
            }
            else {
                logDto.UpdateState = $translate.instant('AccountReMappingFail');
                vatOperationLogService.addOperationLog(logDto);
                SweetAlert.warning($translate.instant('AccountReMappingFail'));
            }
        });
    }


    function showReMapVouchers(entity) {
        $log.debug("showReMapVouchers");
        $log.debug(entity);
        if (!_.isUndefined(entity) && !_.isNull(entity)) {
            //重分类明细选中凭证
            if (!_.isNull(entity.vouchers) && !_.isUndefined(entity.vouchers)) {
                var remapVouchers = _.filter(entity.vouchers, function (v) {
                    var chk = _.find(entity.remapIdes, function (id) { return id === v.remapId; });
                    return chk;
                });
                $scope.gridOptionsVouchersDetail.data = remapVouchers;//entity.vouchers;
                $('#voucherDetailModal').modal('show');
            }
            else { //企业科目列表选中凭证                     
                vatReductionService.getVouchersByCode(entity.code, period).success(function (or) {
                    if (!_.isNull(or) && !_.isUndefined(or)) {
                        if (or.result) {
                            $scope.gridOptionsVouchersDetail.data = or.data;
                            $('#voucherDetailModal').modal('show');
                        }
                        else {
                            SweetAlert.warning($translate.instant(or.resultMsg));
                        }
                    }
                    else {
                        SweetAlert.warning($translate.instant('GetVoucherDetailsFail'));
                    }
                });

            }

        }
    }

    function getAllStdCodes(id) {
        var tree = $("#vatStadardAccountTreeTable").fancytree("getTree");
        var treeSourceData = tree.toDict(true);
        $scope.stdAccountList = [];
        $.each(treeSourceData.children, function (index, item) {
            $.each(item.children, function (index1, item1) {
                getChildStdCodes(item1, $scope.stdAccountList);
            })
        });
        $("#" + id).dxAutocomplete("instance").option("dataSource", $scope.stdAccountList);
    }

    function getChildStdCodes(stdParent, stdLists) {
        stdParent.data.directionDesc = stdParent.data.direction === "1" ? $translate.instant('AccountVoucher_Direction_Debit')
                                       : $translate.instant('AccountVoucher_Direction_Credit');
        stdLists.push(stdParent.data);
        if (!_.isNull(stdParent.children) && !_.isUndefined(stdParent.children)) {
            $.each(stdParent.children, function (index, item) {
                item.data.directionDesc = item.direction === "1" ? $translate.instant('AccountVoucher_Direction_Debit')
                   : $translate.instant('AccountVoucher_Direction_Credit');
                getChildStdCodes(item, stdLists);
            })
        }
    };

    function getStdCodeListRescurive() {
        var tree = $("#vatStadardAccountTreeTable").fancytree("getTree");
        var treeSourceData = tree.toDict(true);
        if ($scope.stdAccountList.length === 0) {
            $scope.stdAccountList = [];
            $.each(treeSourceData.children, function (index, item) {
                $.each(item.children, function (index1, item1) {
                    getChildStdCodes(item1, $scope.stdAccountList);
                })
            });
        }
    }

    function setAutoCompleteDataSource(id) {
        getStdCodeListRescurive();
        $("#" + id).dxAutocomplete("instance").option("dataSource", $scope.stdAccountList);
    }

    //获取未对应企业科目数量
    function getEnterpriseAccountNotMapped() {
        vatReductionService.getEnterpriseAccountNotMapped(vatSessionService.month).success(function (data) {
            $scope.notMappedCount = vatSessionService.enterpriseAccountNotMappedCount = data;
            $scope.$emit('notMappedCount', $scope.notMappedCount);
        });
    };


    //获取TB、ERP导入类型
    function getPeriodInfor() {
        vatImportService.getImportType(vatSessionService.project.id, period).success(function (data) {
            $scope.importTypeId = data;
            vatImportService.IsImportAuditAdjustOnly(vatSessionService.project.id, period).success(function (or) {
                if (or.result) {
                    $scope.isImportAuditAdjust = or.data;

                }
            });
        });
    }

    function isEnterpriseCodeLeafAcct() {
        var selectedRow = $scope.gridApiSubject.selection.getSelectedRows()[0];
        if (!_.isNull(selectedRow) && !_.isUndefined(selectedRow)) {
            if (selectedRow.isLeaf === 1) {
                return true;
            }
            else {
                return false;
            }
        }
    }

    //重置凭证重对应的valudation results
    function resetVoucerRemapValidation() {
        $scope.stdAccountIsLeaf = true;
        $scope.addVoucherReclassificationItem.$setPristine();
    }

    //重置手工重对应的valudation results
    function resetCustRemapValidation() {
        $scope.stdAccountIsLeaf = true;
        $scope.addReclassificationItem.$setPristine();
    }


    //通过科目的$$treeLevel来决定使用哪个class
    //cellTemplate :'<div class="text-align-left-padding ui-grid-cell-contents {{grid.appScope.rowLevel(row.entity)}}"><span>{{row.entity.codeNameDesc}}<span></div>'
    function rowLevel(row) {
        var cls = '';
        cls = 'rowLevel-' + row.$$treeLevel;
        return cls;
    }

    function getExportData() {
        var temp = [];
        var data = $scope.gridOptionsSubjectList.data;
        data.forEach(function (d) {
            var item = {};
            item.code = d.code;
            item.stdCode = d.stdCode;
            item.fullName = d.fullName;
            item.stdFullName = d.stdFullName;
            item.directionDescription = d.directionDescription;
            item.stdDirection = d.stdDirection;
            temp.push(item);
        });

        $scope.exportDataList = temp;
        $log.debug($scope.exportDataList);
    }


    function exportData() {
        getExportData();
        $scope.isToPrint = true;
    }


    (function initialize() {
        //初始化右侧标准科目的树,使用jquery fancytree的方式来显示树,所以需要用到ajax的方式
        var stdAccountUrl = '/AccountMapping/stdAccounts/getStdAccountHierarchy';
        commonWebService.initVATFancyTreeAjax('vatStadardAccountTreeTable', stdAccountUrl, mapStdAccount);
        getEnterpriseAccountNotMapped();

        $scope.stdAccountsCategories = [];
        $scope.stdAccountList = [];
        // i18nService.setCurrentLang("zh-cn");
        //默认显示科目重分类grid
        $scope.ImportErrorTag = true;
        //借贷方向
        $scope.directionList = [
                { id: 1, name: $translate.instant('StandardAccountDebit') },
                { id: -1, name: $translate.instant('StandardAccountCredit') }
        ];

        //标准科目类别
        $scope.acctPropList = [
            { id: 0, name: 'UnKnow' },
            { id: 1, name: $translate.instant('StandardAccountAcctPropAsset') },
            { id: 2, name: $translate.instant('StandardAccountAcctPropDebt') },
            { id: 3, name: $translate.instant('StandardAccountAcctPropCommon') },
            { id: 4, name: $translate.instant('StandardAccountAcctPropInterest') },
            { id: 5, name: $translate.instant('StandardAccountAcctPropCost') },
            { id: 6, name: $translate.instant('StandardAccountAcctPropProfitAndLoss') }
        ];

        //操作菜单选择框
        $scope.processMenuList = [
            //{ key: 'UnSelected', name: $translate.instant('AccountMappingMenuUnSelect') },
            { key: constant.AccountMappingProcessKey.Submit, name: $translate.instant('AccountMappingSubmit') },
            { key: constant.AccountMappingProcessKey.Undo, name: $translate.instant('AccountMappingUndo') }
        ];

        $scope.currentProcess = {};
        $scope.currentProcess.selected = {
            key: constant.AccountMappingProcessKey.UnSelected, name: $translate.instant('AccountMappingMenuUnSelect')
        };

        //********start 重对应autocomplete scope变量定义********

        $scope.maxStdCodeLength = constant.ReMapMaxLength.MaxStdCodeLength;
        $scope.autocompletePlaceholder = $translate.instant('MaxLengthTips').formatObj({ maxLength: $scope.maxStdCodeLength }) + "  "
                                         + $translate.instant("TypeStandardCode");
        $scope.autocompleteSearchModeStartsWith = "startswith";
        $scope.autocompleteSearchModeContains = "contains";
        $scope.maxTextLength = constant.ReMapMaxLength.MaxTextLength;
        $scope.maxRemarkLength = constant.ReMapMaxLength.MaxRemarkLength;
        $scope.regexNum = "/^(\-)?\d+(\.\d{1,2})?$/"; //带1-2位小数的正数或负数 需要在开头和结尾加'/',不然会报Lexer error  
        $scope.stdAccountIsLeaf = true; //默认不展示错误提示
        $scope.onSelectionChangedHandlerCustRemap = onSelectionChangedHandlerCustRemap;
        $scope.onSelectionChangedHandlerVoucherRemap = onSelectionChangedHandlerVoucherRemap;


        //********end 重对应autocomplete scope变量定义********




        //企业科目列表grid
        $scope.gridOptionsSubjectList = {
            virtualizationThreshold: 50,
            enableColumnResizing: true,
            enableRowSelection: false,
            enableSelectAll: true,
            rowHeight: constant.UIGrid.rowHeight,
            enableRowHeaderSelection: true,
            modifierKeysToMultiSelect: true, //按住Ctrl才能多选 
            enableHorizontalScrollbar: uiGridConstants.scrollbars.enableHorizontalScrollbar,
            enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,
            selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
            enableSorting: false,
            enableColumnMenus: true,
            enableFiltering: false,
            showTreeExpandNoChildren: false,
            enableFullRowSelection: false, //是否点击行任意位置后选中,默认为false
            multiSelect: true,// 是否可以选择多个,默认为true;
            columnDefs: [
                {
                    name: $translate.instant('CITProject'), headerCellClass: '', width: '25%', pinnedLeft: true,
                    cellTemplate: '<div class="text-align-left-padding ui-grid-cell-contents"><span>{{row.entity.codeNameDesc}}<span></div>'
                },
                {
                    name: $translate.instant('SubjectDirectionCol'), headerCellClass: '', width: '10%', pinnedLeft: true,
                    cellTemplate: '<div class="text-align-left-padding">'
                                  + '<span>{{row.entity.directionDescription}}</span></div>'
                },
                {
                    name: $translate.instant('SubjectTypeCol'), headerCellClass: '', width: '10%',
                    cellTemplate: '<div class="text-align-left-padding">'
                                 + ' <span>{{row.entity.acctPropStr}}</span></div>'
                },
                {
                    name: $translate.instant('DebitRelevantAmtCol'), headerCellClass: '', width: '20%',
                    cellTemplate: '<div class="text-align-right-padding">'
                                 + ' <span>{{row.entity.debitBal}}</span></div>'
                },
                {
                    name: $translate.instant('CreditRelevantAmtCol'), headerCellClass: '', width: '20%',
                    cellTemplate: '<div class="text-align-right-padding">'
                                 + ' <span>{{row.entity.creditBal}}</span></div>'
                },
                {
                    name: $translate.instant('DebitReclassificationCol'), headerCellClass: '', width: '15%',
                    cellTemplate: '<div class="text-align-right-padding">'
                                 + ' <span>{{row.entity.remapDebit}}</span></div>'
                },
                {
                    name: $translate.instant('CreditReclassificationCol'), headerCellClass: '', width: '15%',
                    cellTemplate: '<div class="text-align-right-padding">'
                                 + ' <span>{{row.entity.remapCredit}}</span></div>'
                },
                {
                    name: $translate.instant('StandardSubjectCol'), headerCellClass: '', width: '20%',
                    cellTemplate: '<div class="text-align-left-padding"><span title="{{row.entity.stdResult}}"><i class="material-icons map-status-flag" ng-if="row.entity.stdCode == null">flag</i>{{row.entity.stdResult}}</span></div>'
                },
                {
                    name: $translate.instant('RelatedVoucherCol'), headerCellClass: '', width: '10%',
                    cellTemplate: '<div class="text-align-left-padding" ng-click="grid.appScope.showReMapVouchers(row.entity)">'
                                  + ' <i class="fa fa-clipboard" style="color:#E84100;" aria-hidden="true" ng-if="row.entity.isShowVoucher"></i></div>'
                },
                {
                    name: $translate.instant('IsLeafCol'), headerCellClass: '', width: '15%', visible: false,
                    cellTemplate: '<div class="text-align-right-padding"><span>{{row.entity.isLeaf}}</span></div>'
                },
                {
                    name: $translate.instant('StdAcctPropCol'), headerCellClass: '', width: '15%', visible: false,
                    cellTemplate: '<div class="text-align-right-padding"><span>{{row.entity.stdAcctProp}}</span></div>'
                },
                {
                    name: $translate.instant('EnterAcctPropCol'), headerCellClass: '', width: '15%', visible: false,
                    cellTemplate: '<div class="text-align-right-padding"><span>{{row.entity.enterAcctProp}}</span></div>'
                },
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApiSubject = gridApi;
                $scope.gridSelectCount = $scope.gridApiSubject.selection.getSelectedRows().length;
                var onRowsRenderedOff = gridApi.core.on.rowsRendered(null, function () {
                    onRowsRenderedOff(); // run once
                    PWC.triggerRowSelectOnClick('#etsGrid'); // requires '.ui-grid-canvas'
                });
                // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                //$interval(function () {
                //    $scope.gridApiSubject.core.handleWindowResize();
                //}, 500, 60 * 60 * 8);

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

                $scope.gridApiSubject.selection.on.rowSelectionChanged($scope, function (row) {
                    var msg = 'row selected ' + row.isSelected;
                    $log.debug(msg);
                    $log.debug(row);
                    if (row.isSelected) {
                        $scope.showReclassificationItemGrid(row.entity);
                    }
                });
            }
        };

        //重分类明细grid
        $scope.gridOptionsReclassificationItem = {
            virtualizationThreshold: 50,
            enableColumnResizing: true,
            rowHeight: constant.UIGrid.rowHeight,
            selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
            enableSorting: false,
            enableColumnMenus: false,
            enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
            enableRowSelection: true,
            enableSelectAll: false,
            enableRowHeaderSelection: false,
            enableFiltering: false,
            showTreeExpandNoChildren: false,
            multiSelect: false,
            columnDefs: [
                {
                    name: $translate.instant('ReclassificationIdCol'), headerCellClass: '', visible: false,
                    cellTemplate: '<div class="text-align-left-padding" ng-show = "false"><span>{{row.entity.remapId}}<span></div>'
                },
                {
                    name: $translate.instant('ReclassificationBatchIdCol'), headerCellClass: '', visible: false,
                    cellTemplate: '<div class="text-align-left-padding" ng-show = "false"><span>{{row.entity.remapBatchId}}<span></div>'
                },
                {
                    name: $translate.instant('ImportErrorPopUpNoCol'), width: '5%', headerCellClass: '',
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.num}}<span></div>'
                },
                {
                    name: $translate.instant('ReclassificationNameCol'), width: '15%', headerCellClass: '',
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.reMappName}}</span></div>'
                },
                {
                    name: $translate.instant('AdjustmentReasonCol'), width: '15%', headerCellClass: '',
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.reMappReason}}</span></div>'
                },
                {
                    name: $translate.instant('AccountReMappingCustomerCode'), headerCellClass: '', visible: false,
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.customerCode}}</span></div>'
                },
                {
                    name: $translate.instant('AccountReMappingDebit'), width: '15%', headerCellClass: '',
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.remapDebit}}</span></div>'
                },
                {
                    name: $translate.instant('AccountReMappingCredit'), width: '15%', headerCellClass: '',
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.remapCredit}}</span></div>'
                },
                {
                    name: $translate.instant('STANDARDProject'), width: '15%', headerCellClass: 'text-align-center',
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.stdCode}}</span></div>'
                    //cellTemplate: '<div class="text-align-left-padding"><span><i class="material-icons map-status-flag" ng-if="row.entity.etsCode === null">flag</i>{{row.entity.etsCode === null ? "未对应" : (row.entity.etsCode + "-" + row.entity.etsName)}}</span></div>'
                },
                {
                    name: $translate.instant('AccountReMappingType'), width: '10%', headerCellClass: 'text-align-center',
                    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.reMappTypeDesc}}</span></div>'
                    //cellTemplate: '<div class="text-align-left-padding"><span><i class="material-icons map-status-flag" ng-if="row.entity.etsCode === null">flag</i>{{row.entity.etsCode === null ? "未对应" : (row.entity.etsCode + "-" + row.entity.etsName)}}</span></div>'
                },
                {
                    name: $translate.instant('RelatedVoucherCol'), width: '10%', headerCellClass: '',
                    cellTemplate: '<div class="text-align-left-padding" ng-click="grid.appScope.showReMapVouchers(row.entity)"><span></span>'
                        + ' <i class="fa fa-clipboard" style="color:#E84100;" aria-hidden="true" ng-if = "row.entity.vouchers != null" ></i></div>'
                },
                //{
                //    name: $translate.instant('RelatedAttachmentCol'), width: '5%', headerCellClass: '',
                //    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.attachments}}</span></div>'
                //}
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApiReclassificationItem = gridApi;
                // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                //$interval(function () {
                //    $scope.gridApiReclassificationItem.core.handleWindowResize();
                //}, 500, 60 * 60 * 8);


                $scope.gridApiReclassificationItem.selection.on.rowSelectionChanged($scope, function (row) {
                    var msg = 'row selected ' + row.isSelected;
                    $log.debug(msg);
                    $log.debug(row);
                    if (row.isSelected) {
                        $scope.onReMapGridRowSelectionChanged(row.entity);
                    }
                });

            }
        };


        //标准科目对应结果
        $scope.gridOptionsStdReMapResult = {
            virtualizationThreshold: 50,
            enableColumnResizing: true,
            rowHeight: constant.UIGrid.rowHeight,
            selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
            enableSorting: false,
            enableColumnMenus: false,
            enableHorizontalScrollbar: uiGridConstants.scrollbars.enableHorizontalScrollbar,
            enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,
            enableRowSelection: true,
            enableSelectAll: false,
            enableRowHeaderSelection: false,
            enableFiltering: false,
            showTreeExpandNoChildren: false,
            multiSelect: false,
            columnDefs: [
               {
                   name: $translate.instant('STANDARDProject'), headerCellClass: '', width: '15%',
                   cellTemplate: '<div class="text-align-left-padding" ><span>{{row.entity.stdCodeAndStdName}}</span></div>'
               },
               {
                   name: $translate.instant('FinalDebit'), headerCellClass: '', width: '15%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.stdDebitStr}}</span></div>'
               },
               {
                   name: $translate.instant('FinalCredit'), headerCellClass: '', width: '15%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.stdCreditStr}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_DataGrid_ColAcctCodeAndNameShow'), headerCellClass: '', width: '10%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.acctCodeAndAcctName}}</span></div>'
               },
               {
                   name: $translate.instant('DebitRelevantAmtCol'), headerCellClass: '', width: '10%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.debitStr}}</span></div>'
               },
               {
                   name: $translate.instant('CreditRelevantAmtCol'), headerCellClass: '', width: '10%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.creditStr}}</span></div>'
               },
               {
                   name: $translate.instant('DebitReclassificationCol'), headerCellClass: '', width: '10%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.remapDebitStr}}</span></div>'
               },
               {
                   name: $translate.instant('CreditReclassificationCol'), headerCellClass: '', width: '10%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.remapCreditStr}}</span></div>'
               },
               {
                   name: $translate.instant('ConfirmDebit'), headerCellClass: '', width: '10%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.acctRealDebitStr}}</span></div>'
               },
               {
                   name: $translate.instant('ConfirmCredit'), headerCellClass: '', width: '10%',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.acctRealCreditStr}}</span></div>'
               }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApiStdMapResult = gridApi;
                // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                $interval(function () {
                    $scope.gridApiStdMapResult.core.handleWindowResize();
                }, 500, 60 * 60 * 8);
            }
        }


        //凭证信息
        $scope.gridOptionsVouchersDetail = {
            virtualizationThreshold: 50,
            enableColumnResizing: true,
            rowHeight: constant.UIGrid.rowHeight,
            selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
            enableSorting: false,
            enableColumnMenus: false,
            enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
            enableRowSelection: false,
            enableSelectAll: false,
            enableRowHeaderSelection: false,
            enableFiltering: false,
            showTreeExpandNoChildren: false,
            multiSelect: false,
            columnDefs: [
               {
                   name: $translate.instant('JournalQJ'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding" ><span>{{row.entity.period}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_DataGrid_ColDate'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.date | date:"yyyy-MM-dd"}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_DataGrid_ColGroup'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.group}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_DataGrid_ColVID'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.vid}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_DataGrid_ColSummary'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.summary}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_DataGrid_ColAcctCodeAndNameShow'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding" ><span>{{row.entity.acctCodeAndNameShow}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_DataGrid_ColStdCodeAndNameShow'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.stdCodeAndNameShow}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_Debit'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.debit}}</span></div>'
               },
               {
                   name: $translate.instant('AccountVoucher_Credit'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.credit}}</span></div>'
               },
               {
                   name: $translate.instant('AccountReMappingCustomerCode'), headerCellClass: '',
                   cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.customerCode}}</span></div>'
               }
               //{
               //    name: $translate.instant('itemID'), headerCellClass: '',
               //    cellTemplate: '<div class="text-align-left-padding"><span>{{row.entity.itemID}}</span></div>'
               //}                                         
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApiVouchersDetail = gridApi;
                //$scope.gridApiVouchersDetail.core.handleWindowResize();
                // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                $interval(function () {
                    $scope.gridApiVouchersDetail.core.handleWindowResize();
                }, 500, 60 * 60 * 8);
            }
        }



        //var editorValue = ko.observable("").extend({
        //    dxValidator: {
        //        validationRules: [{
        //            type: 'required',
        //            message: 'Specify this value'
        //        }]
        //    }
        //});

        //重对应 autocomplete配置
        $scope.dxAutocompleteOptions = {
            CustRemapAutocomplete: {
                dataSource: $scope.stdAccountList,
                minSearchLength: 1,
                maxItemCount: 7,
                searchTimeout: 50,
                placeholder: $scope.autocompletePlaceholder,
                valueExpr: 'code',
                searchExpr: 'code',
                focusStateEnabled: true,
                itemTemplate: 'acStdItemTemplate',
                //validationError: editorValue.dxValidator.validationError,
                onSelectionChanged: $scope.onSelectionChangedHandlerCustRemap,
                bindingOptions: {
                    maxLength: 'maxStdCodeLength',
                    searchMode: 'autocompleteSearchModeContains',
                    value: 'selectedStdCode'
                    //disabled: "!queryParams.selectors.accountCode.selected.id",                   

                }

            },

            VoucherRemapAutoComplete: {
                dataSource: $scope.stdAccountList,
                minSearchLength: 1,
                maxItemCount: 7,
                searchTimeout: 50,
                placeholder: $scope.autocompletePlaceholder,
                valueExpr: 'code',
                searchExpr: 'code',
                focusStateEnabled: true,
                itemTemplate: 'acStdItemTemplate',
                //validationError: editorValue.dxValidator.validationError,
                onSelectionChanged: $scope.onSelectionChangedHandlerVoucherRemap,
                bindingOptions: {
                    maxLength: 'maxStdCodeLength',
                    searchMode: 'autocompleteSearchModeContains',
                    value: 'selectedStdCode'
                    //disabled: "!queryParams.selectors.accountCode.selected.id",                   

                }
            }
        }


        $scope.popTheParentCode = function () {
            $scope.isShowStdFilter = true;
            $scope.selectedStdCode = "";
        }

        InitEnterpriseSubject();
        InitNgData();
        //默认隐藏重分类明细grid
        setErrorWrapCssDefault();
        getPeriodInfor();
        $scope.manualMapAlter = true; //手工对应时,“是否重新对应”的提示只出现一次

        $scope.stateChanged = stateChanged;

        $scope.autoMap = autoMap;

        $scope.ClearMap = ClearMap;

        $scope.toggle1 = toggle1;

        $scope.toggleStdSubject = toggleStdSubject;

        $scope.mapStdAccount = mapStdAccount;

        $scope.getReclassificationItemGridHeight = getReclassificationItemGridHeight;

        $scope.toggleReclassificationGridTab = toggleReclassificationGridTab;

        $scope.manualReclassificate = manualReclassificate;

        $scope.voucherReclassificate = voucherReclassificate;

        $scope.showReclassificationItemGrid = showReclassificationItemGrid;

        $scope.saveManualReclassification = saveManualReclassification;

        $scope.saveVoucherReclassification = saveVoucherReclassification;

        $scope.getStdRemapResult = getStdRemapResult;

        $scope.closeModal = closeModal;

        $scope.submitAccountMap = submitAccountMap;

        $scope.undoAccountMap = undoAccountMap;

        $scope.showOperateLogPop = showOperateLogPop;


        checkUserOrganizationPermissionList();
        initReMapVoucherModel(constant.Operation.Add, null, -1);
        initReMapCustModel(constant.Operation.Add, -1, null);

        $scope.showReMapVouchers = showReMapVouchers;
        $scope.rowLevel = rowLevel;
        $scope.editReMapItem = editReMapItem;
        $scope.deleteReMapItem = deleteReMapItem;
        $scope.onReMapGridRowSelectionChanged = onReMapGridRowSelectionChanged;
        $scope.enterpriseCode;//选中的企业科目代码    
        $scope.selectedVouchers;//凭证对应时选中的分录
        $scope.reMappId;//重对应明细记录的id
        $scope.isSubmitted = vatSessionService.project.projectStatusList[vatSessionService.month] <= constant.ProjectStatusEnum.Imported
                             ? false : true;
        $scope.isSearching = false;
        $scope.remapTitle = "";
        $scope.processTypeId = enums.processType.UnDefined;
        $scope.userId = vatSessionService.logUser.id;
        $scope.exportData = exportData;
        $scope.isToPrint = false;
        $scope.exportDataList = [];


        //watch $scope.selectedVouchers的长度变化
        $scope.$watch('selectedVouchers.length', function (newValue, oldValue) {
            $log.debug("start to watch selectedVouchers");
            $log.debug($scope.selectedVouchers);
            calcVoucherDebitCredit($scope.selectedVouchers);
        });

        $scope.$watch('selectedStdCode', function (newValue, oldValue) {
            isStdCodeLeafNode(newValue);
        });

        //执行exportData(),table: exportTable ng-repeat绘制完成后执行
        $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
            if ($scope.isToPrint) {
                export_table_to_excel('exportTable', 'AccountMapping', 'xlsx', '');
            }
            $scope.isToPrint = false;
        });


    })();
}
]);