vatModule.controller('vatInvoiceMappingController', ['$scope', '$log', '$timeout', '$q', '$interval', '$translate', 'loginContext', 'apiInterceptor', 'Upload', 'dataImportService', 'SweetAlert', 'vatImportService', 'vatSessionService', 'uiGridConstants', 'enums', 'vatCommonService', 'vatOperationLogService',
function ($scope, $log, $timeout, $q, $interval, $translate, loginContext, apiInterceptor, Upload, dataImportService, SweetAlert, vatImportService, vatSessionService, uiGridConstants, enums, vatCommonService, vatOperationLogService) {
    'use strict';
    $log.debug('vatInvoiceMappingController.ctor()...');

    var uploadUrl = apiInterceptor.vatWebApiHostUrl + '/FileUpload/NewFile';
    var successCount = 0;
    var resumable = true;
    var period = vatSessionService.month;
    var year = 2017;
    var projectId = vatSessionService.project.id;
    $scope.chunkSize = 100000;
    $scope.columnNum = 1;
    $scope.showErrorTable = false;
    $scope.showInitTable = false;
    $scope.showImportTable = false
    $scope.period = period;
    $scope.moduleid = enums.vatModuleEnum.Import_InvoiceMapping;
    var logDto = {};
    logDto.ModuleID = $scope.moduleid;
    logDto.CreatorID = vatSessionService.logUser.ID;
    logDto.OperationObject = $translate.instant('invoiceMappingDesc');
    logDto.Comment = vatSessionService.project.name + " " + vatSessionService.project.year + "年" + vatSessionService.month + "月";
    logDto.Period = period;

    var validationErrorType = {
        ColumnsMapErrorType: $translate.instant('ColumnsMapErrorType'),
        InvoiceCodeEmptyErrorType: $translate.instant('InvoiceCodeEmptyErrorType'),
        InvoiceNumberEmptyErrorType: $translate.instant('InvoiceNumberEmptyErrorType'),
        TrancodeParseEmptyErrorType: $translate.instant('TrancodeParseEmptyErrorType'),
        NumOutRangeErrorType: $translate.instant('NumOutRangeErrorType'),
        OutputStringLengthType: $translate.instant('OutputStringLengthType'),
        StartRowError: $translate.instant('StartRowError')
    };
    
    var initColumns = function () {

        $scope.allColumns = [
            $translate.instant('PleaseSelectColumn'),
            $translate.instant('tranCode'),
            $translate.instant('invoiceCode'),
            $translate.instant('invoiceNumber')
        ];

        $scope.necessoryColumns = [
            $translate.instant('tranCode'),
            $translate.instant('invoiceCode'),
            $translate.instant('invoiceNumber')
        ];
    };

    var initGrid = function () {

        $scope.gridOptions = {
            rowHeight: constant.UIGrid.rowHeight,
            selectionRowHeaderWidth: constant.UIGrid.rowHeight,
            enableFullRowSelection: false,
            enableRowSelection: false,
            enableSorting: false,
            enableFiltering: false,
            enableColumnMenus: false,
            enableRowHeaderSelection: false,
            enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
            columnDefs: [
            {
                field: 'index', name: $translate.instant('ImportErrorPopUpNoCol'), width: '10%', headerCellClass: '', enableFiltering: false,

                cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.index}}<span></div>'
            },
              {
                  field: 'tranCode', name: $translate.instant('tranCode'), width: '30%', headerCellClass: '',

                  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.tranCode}}">{{row.entity.tranCode}}<span></div>'
              },

              {
                  field: 'invoiceCode', name: $translate.instant('invoiceCode'), width: '30%', headerCellClass: '',

                  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.invoiceCode}}">{{row.entity.invoiceCode}}</span></div>'
              },
              {
                  field: 'invoiceNumber', name: $translate.instant('invoiceNumber'), width: '30%', headerCellClass: '',

                  cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.invoiceNumber}}">{{row.entity.invoiceNumber}}</span></div>'
              }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApiTotal = gridApi;
            }
        };

        $scope.gridOptions.noData = false;
    };

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


    var mapppingList = function () {
        return [{ TranCode: 'A0000001', InvoiceCode: 'ABDJSHS', InvoiceNumber: '201702251000' },
            { TranCode: 'A0000006', InvoiceCode: 'SDFADSS', InvoiceNumber: '201702261020' },
            { TranCode: 'A0000010', InvoiceCode: 'SDFDFES', InvoiceNumber: '201702051006' }];
    }

    //parentIndex:column index
    //index:selecteditem index
    var mappingColumn = function (parentIndex, index, colName) {
        if (colName) {

            var oldColumn = $scope.selectedColumnMap[parentIndex];
            var newColumn = $scope.allColumns[index];

            if (oldColumn === newColumn) {
                return;
            }
            else {
                $scope.selectedColumnMap[parentIndex] = colName;

                if (colName !== $translate.instant('PleaseSelectColumn')) {
                    $scope.allColumns.splice(index, 1);

                    if (oldColumn && oldColumn !== $translate.instant('PleaseSelectColumn')) {
                        $scope.allColumns.push(oldColumn);
                    }
                }
                else {
                    if (oldColumn) {
                        $scope.allColumns.push(oldColumn);
                    }
                }
            }
        }
        $log.debug($scope.selectedColumnMap);
    };

    var UploadFile = function (file) {
        if (file) {
            if (!file.name.endsWith('.xls') != 0 && !file.name.endsWith('.xlsx')) {
                SweetAlert.warning($translate.instant('ImportFileInvalidType'));
                return;
            };
            $scope.initIncomeInvoiceList = [];
            successCount = 0;
            if (!file.$error) {
                var tempFileName = PWC.newGuid() + '.dat';
                Upload.upload({
                    url: uploadUrl,
                    data: {
                        filename: file.name,
                        tempFileName: tempFileName,
                        file: file
                    },
                    resumeChunkSize: resumable ? $scope.chunkSize : null,
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                        Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken()
                    },
                    __RequestVerificationToken: $scope.token,
                    withCredentials: true
                }).then(function (resp) {
                    successCount++;
                    $scope.fileName = file.name;
                    if (successCount === 1) {
                        $scope.tempFileName = resp.data;
                        changeSheet(0);
                    }
                });
            }
        }
    }

    var resetMappingRow = function () {
        initColumns();
        $scope.selectedColumnMap = [];
    };

    var changeSheet = function (index) {
        $scope.showErrorTable = false;
        $scope.selectedSheet.sheetIndex = index;
        resetMappingRow();
        if (_.isString($scope.tempFileName)) {
            $scope.excelSource = { sheetNameList: [], dataList: [] };
            vatImportService.getFileContent($scope.tempFileName, $scope.selectedSheet.sheetIndex, $scope.selectedSheet.topRowNumber).success(function (data) {
                if (data && data.result === false) {
                    $scope.showInitTable = true;
                    $scope.showImportTable = false;
                    SweetAlert.warning(data.resultMsg);
                    return;
                }
                var index = 1;
                data.dataList.forEach(function (i) {
                    i.index = index++;
                });
                $scope.showInitTable = false;
                $scope.showImportTable = true
                $scope.excelSource = data;
                $scope.firstDataRow = data.dataList[0];
                $scope.columnNum = data.dataList[0].length;
                $scope.startRowList = _.range(data.lastRowIndex);
                $scope.selectedSheet.sheetName = $scope.excelSource.sheetNameList[$scope.selectedSheet.sheetIndex];
                $scope.isImportView = true;
                vatSessionService.dataChanged = true;
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        }
    };

    var validatefirst = function () {
        var result = true;
        var notMappedColumns = '';
        $scope.errorMsgMap = [];
        if ($scope.selectedColumnMap.length >= 0) {
            var count1 = 0;
            $scope.necessoryColumns.forEach(function (m) {
                if (m !== $translate.instant('PleaseSelectColumn')) {
                    if ($.inArray(m, $scope.selectedColumnMap) < 0) {
                        notMappedColumns += m + ',';
                        count1++;
                    }
                }
            });
            if (count1) {
                result = false;
                //加入到错误列表中
                $scope.errorMsgMap.push(
                    {
                        'errorType': validationErrorType.ColumnsMapErrorType,
                        'errorCount': count1,
                        'errorContent': $translate.instant('ColumnsMapErrorMsg').formatObj({ columns: notMappedColumns.substring(0, notMappedColumns.length - 1) })
                    });
            }
        }
        //2:判断起始行输入框输入内容是否合理
        var startNumberCheckMsg = '';
        $scope.StartRowNum = $('#StartRowNum').val();
        if ($scope.StartRowNum === '') {
            result = false;
            $scope.errorMsgMap.push(
                    {
                        'errorType': validationErrorType.StartRowError,
                        'errorCount': 1,
                        'errorContent': $translate.instant('StartRowNull')
                    });
        }
        else if (parseInt($scope.StartRowNum) > $scope.excelSource.dataList.length) {
            result = false;
            $scope.errorMsgMap.push(
                    {
                        'errorType': validationErrorType.StartRowError,
                        'errorCount': 1,
                        'errorContent': $translate.instant('StartRowNumberCheckMsg')
                    });
        }
        return result;
    };

    var validateClientSide = function (dataList) {
        var InvoiceCodeEmptyCheckMsg = '';
        var InvoiceCodeEmptyCheckCount = 0;

        var InvoiceNumberEmptyCheckMsg = '';
        var InvoiceNumberEmptyCheckCount = 0;

        var TranCodeEmptyCheckMsg = '';
        var TranCodeEmptyCheckCount = 0;

        var numOutRangeCheckMsg = '';
        var numOutRangeCheckCount = 0;

        var stringOverLengthCheckMsg = '';
        var stringOverLengthCheckCount = 0;

        dataList.forEach(function (m) {
            var curRowInfo = '(' + $translate.instant('RowIndex').formatObj({ rowIndex: m.Index }) + ')' +
                            $translate.instant('tranCode') + ':' + m.TranCode + ',' +
                            $translate.instant('invoiceCode') + ':' + m.InvoiceCode + ',' +
                            $translate.instant('invoiceNumber') + ':' + m.InvoiceNumber + ';<br />';

            if (PWC.isNullOrEmpty(m.InvoiceCode)) {
                //InvoiceCodeEmptyCheckCount++;
                //InvoiceCodeEmptyCheckMsg += curRowInfo;
            }
            else {

                if (m.InvoiceCode.length > constant.validateLength.StringLength_50) {
                    stringOverLengthCheckMsg += '(' + $translate.instant('RowIndex').formatObj({ rowIndex: m.Index }) + ')' + $translate.instant('invoiceCode') + $translate.instant('OutputStringLengthMsg') + ';<br />';
                    stringOverLengthCheckCount++;
                }
            }


            if (PWC.isNullOrEmpty(m.InvoiceNumber)) {
                InvoiceNumberEmptyCheckCount++;
                InvoiceNumberEmptyCheckMsg += curRowInfo;
            }
            else {

                if (m.InvoiceNumber.length > constant.validateLength.StringLength_50) {
                    stringOverLengthCheckMsg += '(' + $translate.instant('RowIndex').formatObj({ rowIndex: m.Index }) + ')' + $translate.instant('invoiceNumber') + $translate.instant('OutputStringLengthMsg') + ';<br />';
                    stringOverLengthCheckCount++;
                }
            }

            if (PWC.isNullOrEmpty(m.TranCode)) {
                TranCodeEmptyCheckCount++;
                TranCodeEmptyCheckMsg += curRowInfo;
            }
            else {

                if (m.TranCode.length > constant.validateLength.StringLength_50) {
                    stringOverLengthCheckMsg += '(' + $translate.instant('RowIndex').formatObj({ rowIndex: m.Index }) + ')' + $translate.instant('tranCode') + $translate.instant('OutputStringLengthMsg') + ';<br />';
                    stringOverLengthCheckCount++;
                }
            }
        });

        if (InvoiceCodeEmptyCheckCount > 0) {
            $scope.errorMsgMap.push(
                {
                    'errorType': validationErrorType.InvoiceCodeEmptyErrorType,
                    'errorCount': InvoiceCodeEmptyCheckCount,
                    'errorContent': InvoiceCodeEmptyCheckMsg
                });
        }
        if (InvoiceNumberEmptyCheckCount > 0) {
            $scope.errorMsgMap.push(
                {
                    'errorType': validationErrorType.InvoiceNumberEmptyErrorType,
                    'errorCount': InvoiceNumberEmptyCheckCount,
                    'errorContent': InvoiceNumberEmptyCheckMsg
                });
        }
        if (TranCodeEmptyCheckCount > 0) {
            $scope.errorMsgMap.push(
                {
                    'errorType': validationErrorType.TrancodeParseEmptyErrorType,
                    'errorCount': TranCodeEmptyCheckCount,
                    'errorContent': TranCodeEmptyCheckMsg
                });
        }
        if (stringOverLengthCheckCount > 0) {
            $scope.errorMsgMap.push({
                'errorType': validationErrorType.OutputStringLengthType,
                'errorCount': stringOverLengthCheckCount,
                'errorContent': stringOverLengthCheckMsg
            });
        }

        if (numOutRangeCheckCount > 0) {
            $scope.errorMsgMap.push({
                'errorType': validationErrorType.NumOutRangeErrorType,
                'errorCount': numOutRangeCheckCount,
                'errorContent': numOutRangeCheckMsg
            });
        }
    }

    function doSave2Server(saveType) {
        // saveType 1:override,2:append

//        if (!validatefirst()) {//todo: to be open future (neo)
//            $('#errorListModal').modal('show');
//            return;
//        }

        var dataList = [];
        for (var i = $scope.StartRowNum - 1; i < $scope.excelSource.dataList.length; i++) {
            var item = {
                'Index': $scope.excelSource.dataList[i].index,
                'Period': period,
                'InvoiceCode': $scope.excelSource.dataList[i][$.inArray($translate.instant('invoiceCode'), $scope.selectedColumnMap)],
                'InvoiceNumber': $scope.excelSource.dataList[i][$.inArray($translate.instant('invoiceNumber'), $scope.selectedColumnMap)],
                'TranCode': $scope.excelSource.dataList[i][$.inArray($translate.instant('tranCode'), $scope.selectedColumnMap)]
            };
            dataList.push(item);
        }

//        validateClientSide(dataList); todo: to be open future (neo)
//        if ($scope.errorMsgMap.length > 0) {
//            $('#errorListModal').modal('show');
//            return;
//        }

        if (dataList.length == 0) {
            SweetAlert.warning($translate.instant('noCurMonthRecordErrorMsg'));
            return;
        }
        else {
            vatImportService.SaveInvoiceMappings(dataList, period, saveType).success(function (data) {
                if (data) {
                    if (data.result) {

                        logDto.ID = PWC.newGuid();
                        logDto.CreateTime = new Date();
                        logDto.UpdateTime = new Date();
                        logDto.OperationContent = $scope.fileName;
                        if (saveType === 2) {
                            logDto.OperationName = $translate.instant('AddImportBtn');
                            logDto.OperationType = enums.vatLogOperationTypeEnum.AddImport;
                        }
                        else if (saveType === 1) {
                            logDto.OperationName = $translate.instant('ConverImportBtn');
                            logDto.OperationType = enums.vatLogOperationTypeEnum.CoverImport;
                        }
                        logDto.UpdateState = $translate.instant('ImportSuccess');
                        vatOperationLogService.addOperationLog(logDto);

                        $scope.showInitTable = true;
                        $scope.showImportTable = false;
                        $scope.showErrorTable = false;
                        $scope.ImportErrorTab = false;
                        $scope.ImportErrorTag = false;
                        vatCommonService.importSetProjectStatus(projectDbName, period, constant.DictionaryDictKey.WFImportInvoiceMap
                                                                , enums.FinishStatusEnum.Finished);
                        vatCommonService.setImportSubStatus(enums.VatImportSubStatus.isInvoiceMapImport, true);
                        $log.debug("import invoiceMapping save2Server: " + vatSessionService.project.importSubStatus.isInvoiceMapImport);
                        SweetAlert.success($translate.instant('ImportSuccess'));
                        resetMappingRow();
                        getMappings();
                        $scope.fileName = '';
                    }
                    //else {
                    //    processValidateMsg(data.data);
                    //    if ($scope.errorMsgMap.length > 0) {
                    //        $('#errorListModal').modal('show');
                    //    }
                    //}
                }
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        }
    }

    var save2Server = function (saveType) {
        if ($scope.excelSource.sheetNameList.length == 0) {
            SweetAlert.warning($translate.instant('PleaseSelectFileFirst'));
            return;
        }

        if (vatSessionService.project.projectStatusList[period] >= constant.ProjectStatusEnum.Generated) {
            swal({
                title: "warning!",
                text: $translate.instant('IsConfirmToReImport').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) {
                    $timeout(function () { doSave2Server(saveType) }, 300);
                }
                else {
                    swal.close();
                }
            });
        }
        else {
            doSave2Server(saveType);
        }
    };

    var buildDataStr = function (p) {
        var empty = '<' + $translate.instant('empty') + '>';
        return $translate.instant('tranCode') + ':' + (PWC.isNullOrEmpty(p.tranCode) ? empty : p.tranCode) + ',' +
               $translate.instant('invoiceCode') + ':' + (PWC.isNullOrEmpty(p.invoiceCode) ? empty : p.invoiceCode) + ',' +
               $translate.instant('invoiceNumber') + ':' + (PWC.isNullOrEmpty(p.invoiceNumber) ? empty : p.invoiceNumber) + ';<br />';
    };
    
    var clear = function () {
        swal({
            title: "warning!",
            text: $translate.instant('ClearTips'),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: $translate.instant('Yes'),
            cancelButtonText: $translate.instant('No'),
            closeOnConfirm: true,
            closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                var dataList = [];
                var saveType = 1;//overide
                vatImportService.SaveInvoiceMappings(dataList, period, saveType).success(function (data) {
                    if (data && data.result) {

                        logDto.ID = PWC.newGuid();
                        logDto.CreateTime = new Date();
                        logDto.UpdateTime = new Date();
                        logDto.OperationContent = '';
                        logDto.OperationName = $translate.instant('ClearAll');
                        logDto.OperationType = enums.vatLogOperationTypeEnum.ClearData;
                        logDto.UpdateState = $translate.instant('ClearSuccess');
                        vatOperationLogService.addOperationLog(logDto);

                        $scope.showInitTable = true;
                        $scope.showImportTable = false;
                        $scope.showErrorTable = false;
                        $scope.ImportErrorTab = false;
                        $scope.ImportErrorTag = false;
                        vatCommonService.clearProjectStatus(projectDbName, period, constant.DictionaryDictKey.WFImportInvoiceMap
                                                                   , enums.FinishStatusEnum.NotFinished);
                        vatCommonService.setImportSubStatus(enums.VatImportSubStatus.isInvoiceMapImport, false);
                        $log.debug("clear invoiceMapping clear: " + vatSessionService.project.importSubStatus.isInvoiceMapImport);
                        SweetAlert.success($translate.instant('ClearSuccess'));
                        resetMappingRow();
                        getMappings();
                    }
                });
            }
        }).error(function () {
            SweetAlert.error($translate.instant('PleaseContactAdministrator'));
        });
    };

    var getMappings = function () {
        vatImportService.GetInvoiceMappings(period).success(function (data) {
            if (data.length > 0) {
                GetValidationList();
            }
            else {
                $scope.haveImported = false;
                $scope.showErrorTable = false;
                $scope.ImportErrorTab = false;
                $scope.ImportErrorTag = false;
            }
            $scope.excelSource = { sheetNameList: [], dataList: [] };
            $scope.mapppingList = data; var seqNo = 1;
            $scope.mapppingList.forEach(function (i) {
                i.index = seqNo;
                seqNo++;
            });
            //获取发票对应数据
            $scope.gridOptions.data = $scope.mapppingList;
            $scope.gridOptions.noData = $scope.mapppingList.length === 0;
            $scope.isImportView = false;
            $scope.firstDataRow = null;
            vatSessionService.dataChanged = false;
        }).error(function () {
            SweetAlert.error($translate.instant('PleaseContactAdministrator'));
        });
    };

    $scope.$watch('selectedFileName', function (newValue, oldValue) {
        if (newValue && newValue !== oldValue) {
            UploadFile($scope.selectedFileName);
            $scope.ImportErrorTab = false;
            $scope.ImportErrorTag = false;
            resetMappingRow();
        }
    });

    $scope.gridOptionsErrorMsg = {
        rowHeight: constant.UIGrid.rowHeight,
        selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
        enableSorting: false,
        enableColumnMenus: false,
        enableHorizontalScrollbar: uiGridConstants.scrollbars.enableHorizontalScrollbar,
        enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,
        columnDefs: [
        {
            name: $translate.instant('Icon'), width: '5%', cellTemplate: '<div class="ui-grid-cell-contents"><span><img data-ng-src="{{grid.appScope.errorLevelToString(row.entity.errorLevel)}}"><span></div>'
        },
          {
              name: $translate.instant('SequenceNo'), width: '5%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.index}}<span></div>'
          },
          {
              name: $translate.instant('ErrorResult'), width: '20%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.validationResult}}<span></div>'
          },
           {
               name: $translate.instant('ErrorCount'), width: '10%', cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.number}}<span></div>'
           },
          {
              name: $translate.instant('ErrorDetail'), width: '35%', cellTemplate: '<div ng-if="row.entity.isShowDetail === 1" class="ui-grid-cell-contents"><span><a  ng-click="grid.appScope.openTab(row.entity.erpCheckTypeId,row.entity.validationDetails)">查看明细</a><span></div>' +
                '<div  ng-if="row.entity.isShowDetail !== 1" class="ui-grid-cell-contents" title="{{row.entity.validationDetails}}"><span>{{row.entity.validationDetails}}<span></div>'
          },
           {
               name: $translate.instant('ValidationTips'), width: '25%', cellTemplate: '<div class="ui-grid-cell-contents" title="{{row.entity.validationTips}}"><span>{{row.entity.validationTips}}<span></div>'
           },
        ],
        onRegisterApi: function (gridApi) {
            $scope.errorGridApi = gridApi;

        }
    };

    function GetValidationList() {
        $scope.validationType = 10;
        vatImportService.getValidationList($scope.validationType, period).success(function (data) {
            if (data.length > 0) {
                var index = 1;
                data.forEach(function (v) {
                    v.index = index++;
                });
                $scope.errorList = data;
                $scope.gridOptionsErrorMsg.data = data;

                showErrTab();
                $scope.toggleErrorTab();
                $scope.showErrorTable = true;
            }
            else {
                $scope.errorList = [];
                $scope.gridOptionsErrorMsg.data = [];
                $scope.showErrorTable = false;
                $scope.ImportErrorTab = false;
                $scope.ImportErrorTag = false;
            }
        });
    }

    $scope.errorLevelToString = function (errorLevel) {
        if (errorLevel === 0) {
            return '/app-resources/images/vat/error.png';
        }
        if (errorLevel === 1) {
            return '/app-resources/images/vat/warning.png';
        }
        if (errorLevel === 2) {
            return '/app-resources/images/vat/tips.png';
        }
        else {
            return '/app-resources/images/vat/tips.png';
        }
    }

    $scope.toggleErrorTab = function () {
        $scope.errorGridApi.core.handleWindowResize();
        $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', '190px');

                $('#topIcon').css({ bottom: '-381px' });

                $('.error-info-wrapper').css('height', '190px');
            }
        }
    };

    var dealDetail = function () {
        return '<div ng-if="row.entity.isShowDetail === 1" class="ui-grid-cell-contents"><span><a  ng-click="grid.appScope.openTab(row.entity.erpCheckTypeId,row.entity.validationDetails)">查看明细</a><span></div>' +
                '<div  ng-if="row.entity.isShowDetail !== 1" class="ui-grid-cell-contents" title="{{row.entity.validationDetails}}"><span>{{row.entity.validationDetails}}<span></div>';
    }

    $scope.openTab = function (errorType, rowdata) {
        var data = JSON.parse(rowdata);
        if (errorType === 45) {
            dispalyDuplicatedValidation(data);
        }
    }
 
    $scope.deleteDupData = function () {
        var dataGrid = $('#gridDuplicatedValidation').dxDataGrid("instance");
        var deleteList = [];
        dataGrid.getSelectedRowsData().done(function (rowData) {
            for (var i = 0; i < rowData.length; i++) {
                var msg = $translate.instant('tranCode') + ':' + rowData[i].TranCode + ',' +
                                            $translate.instant('period') + ':' + rowData[i].Period + ',' +
                                            $translate.instant('vid') + ':' + rowData[i].VID + ',' +
                                            $translate.instant('vGroup') + ':' + rowData[i].Group + ',' +
                                            $translate.instant('itemID') + ':' + rowData[i].ItemID;
                deleteList.push(msg);
            }
        });
        dataGrid.getSelectedRowKeys().done(function (keys) {
            if (keys && keys.length === 0) {
                SweetAlert.warning($translate.instant('DeleteEmptyWarning'));
                return;
            }

            logDto.ID = PWC.newGuid();
            logDto.CreateTime = new Date();
            logDto.UpdateTime = new Date();
            logDto.OperationContent = deleteList.join(";");
            logDto.OperationName = $translate.instant('DeleteDuplicateData');
            logDto.OperationType = enums.vatLogOperationTypeEnum.DeleteDuplicate;

            vatImportService.deleteInvoiceMappings(keys).success(function (rsp) {
                if (rsp) {
                    logDto.UpdateState = $translate.instant('DeleteSuccess');
                    vatOperationLogService.addOperationLog(logDto);
                    //刷新数据
                    vatImportService.validDBInvoiceMapping(period).success(function (result) {
                        if (result) {
                            logDto.ID = PWC.newGuid();
                            logDto.CreateTime = new Date();
                            logDto.UpdateTime = new Date();
                            logDto.OperationContent = $translate.instant('invoiceMappingDesc');
                            logDto.OperationName = $translate.instant('RefreshValidationData');
                            logDto.OperationType = enums.vatLogOperationTypeEnum.Refresh;
                            logDto.UpdateState = $translate.instant('RefreshSuccess');
                            vatOperationLogService.addOperationLog(logDto);

                            $('#duplicatedValidationModal').modal('hide');
                            SweetAlert.success($translate.instant('DeleteSuccess'));
                            getMappings();
                        }
                        else {
                            SweetAlert.warning($translate.instant('RefreshTbFail'));
                        }
                    }).error(function (e) {
                        SweetAlert.error($translate.instant('PleaseContactAdministrator'));
                    });
                }

            }).error(function (e) {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        });
    }

    $scope.refreshData = function () {
        logDto.ID = PWC.newGuid();
        logDto.CreateTime = new Date();
        logDto.UpdateTime = new Date();
        logDto.OperationContent = $translate.instant('invoiceMappingDesc');
        logDto.OperationName = $translate.instant('RefreshValidationData');
        logDto.OperationType = enums.vatLogOperationTypeEnum.Refresh;
        //刷新数据
        vatImportService.validDBInvoiceMapping(period).success(function (result) {
            if (result) {
                logDto.UpdateState = $translate.instant('RefreshSuccess');
                vatOperationLogService.addOperationLog(logDto);

                getMappings();
                SweetAlert.success($translate.instant('RefreshSuccess'));
            }
            else {
                SweetAlert.warning($translate.instant('RefreshTbFail'));
            }
        }).error(function (e) {
            SweetAlert.error($translate.instant('PleaseContactAdministrator'));
        });
    }

    var dispalyDuplicatedValidation = function (sourcedata) {
        $scope.detailData = sourcedata;
        var dupColumns = [
        { caption: $translate.instant('tranCode'), dataField: "TranCode", width: 180 },
        { caption: $translate.instant('period'), dataField: "Period", width: 100 },
        { caption: $translate.instant('vGroup'), dataField: "Group", width: 180 },
        { caption: $translate.instant('vid'), dataField: "VID", width: 180 },
        { caption: $translate.instant('itemID'), dataField: "ItemID", dataType: "date", width: 180 }, ];

        $scope.deferStatus = true;
        $scope.filterCondition = ["IsDuplicate", "=", true];
        $scope.gridDuplicatedOptions = {
            columns: dupColumns,
            bindingOptions: {
                "dataSource.store.data": "detailData",
                "selection.deferred": "deferStatus",
                "selectionFilter": "filterCondition"
            },
            dataSource: {
                store: {
                    type: "array",
                    key: 'ID'
                }
            },
            selection: {
                mode: "multiple",
                selectAllMode: "allPages",
                showCheckBoxesMode: "always",
            },
            hoverStateEnabled: true,
            paging: {
                pageSize: 10
            },
        }
        $('#duplicatedValidationModal').modal('show');
    }

    var setErrorWrapCssDefault = function () {
        $('#content-resizer').css('bottom', '65px');

        $('#topIcon').css({ bottom: '-501px' });

        $('.error-info-wrapper').css('height', '65px');
    };

    function showErrTab() {
        $scope.ImportErrorTab = true;
        $scope.ImportErrorTag = true;
        $scope.errorMsg = $translate.instant('ImportErrorMsg').formatObj({ "NumberOfError": $scope.errorList.length });

    };

    $scope.getGridHeight = function () {
        if ($scope.isLoadComplete) {
            return { height: ($('.balance-ouput-grid-wrapper').height()) + "px" };
        }
        else {
            return { height: 0 + "px" };
        }
    };

    $scope.getErrorGridHeight = function () {
        if ($scope.isLoadComplete) {
            var y = $("#error-info-wrapper").height();
            // Enough space
            if (y > constant.UIGrid.gapHeight) {
                y = y - constant.UIGrid.gapHeight;
                return { height: y + "px" };
            } else {

                return { height: '0px' };
            }
        }
        return {};
    };

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

    //控制明细信息中删除权限
    var getUserPermission = function () {
        var list = [];
        var code = constant.vatPermission.dataImport.invoiceMapping.importCode;
        list.push(code);

        $scope.$root.checkUserOrganizationPermissionList(list).success(function (data) {
            $scope.hasImportPermission = data[code];
        });
    };

    (function initialize() {
        $scope.StartRowNum = 2;
        $scope.isImportView = false;
        $scope.mapppingList = [];
        $scope.mappingRow = null;
        $scope.firstDataRow = null;
        $scope.selectedColumnMap = [];
        $scope.selectedFileName = '';
        $scope.excelSource = { sheetNameList: [], dataList: [] };
        $scope.selectedSheet = { sheetName: '', sheetIndex: 0, topRowNumber: 0 };

        initColumns();
        initGrid();
        getUserPermission();
        $scope.mapppingList = getMappings();
        //$scope.refresh = getMappings;
        $scope.clear = clear;

        $scope.changeSheet = changeSheet;
        $scope.mappingColumn = mappingColumn;
        $scope.save2Server = save2Server;

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

    })();
}
]);