invoiceModule.controller('bdViewByVINController', ['$log', '$timeout', '$scope', '$translate', 'vatOutputInvoiceManageService',
    'SweetAlert', 'enums', 'modalAdapterService', '$document', '$uibModal', "$q",
    function ($log, $timeout, $scope, $translate, vatOutputInvoiceManageService, SweetAlert, enums,
        modalAdapterService, $document, $uibModal, $q) {

        //Define the globle Variable of the page. -->start
        var dateFormat = 'yyyy-MM-dd';
        var isShowClearButton = true;
        var revertStatusList = _.invert(enums.GDBDStatusEnum);
        var revertGDStatusList = _.invert(enums.GDInvoiceStatusEnum);
        $scope.pleaseSelect = $translate.instant("ChoosePlaceholder");
        $scope.pleaseInput = $translate.instant('InputPlaceholder');
        $scope.noDataText = $translate.instant('NoDataText');
        $scope.masterDetailHeader = {
            invoiceNo: $translate.instant('InvoiceNo'),
            invoiceCode: $translate.instant('InvoiceCode'),
            invoiceCaseNum: $translate.instant('InvoiceCase'),
            issuedDate: $translate.instant('IssuedDate'),
            buyer: $translate.instant('Buyer'),
            amount: $translate.instant('Amount'),
            taxAmount: $translate.instant('TaxAmount'),
            totalAmount: $translate.instant('TotalAmount'),
            gdStatus: $translate.instant('GDStatus'),
            status: $translate.instant('Status')
        };

        $scope.pagingOptions = {
            pageIndex: 1,  //当前页码
            totalItems: 0,  //总数据
            pageSize: constant.page.pageSizeArrary[1],  //每页多少条数据 
        };

        $scope.bdVinSearchEntity = {};
        $scope.selectedIssuedInvoiceCount = 0;
        $scope.selectedIssuedInvoiceAmount = 0;
        //Define the globle Variable of the page. -->end

        
        $scope.searchOptions = {
            //The define of search field. -->start
            InvoiceNo:{
                width: "100%",
                placeholder: $translate.instant('InputPlaceholder'),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'bdVinSearchEntity.invoiceNo',
                }
            },
            VIN:{
                width: "100%",
                placeholder: $translate.instant('InputPlaceholder'),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'bdVinSearchEntity.VIN',
                }
            },
            InvoiceCode: {
                width: "100%",
                placeholder: $translate.instant('InputPlaceholder'),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'bdVinSearchEntity.invoiceCode',
                }
            },
            VehicleModel:{
                width: "100%",
                placeholder: $translate.instant("ChoosePlaceholder"),
                showClearButton: isShowClearButton,
                displayExpr: 'name',
                valueExpr: 'id',
                //items: ['Salesforce', 'Smart Tax', 'Local'],
                bindingOptions: {
                    value: 'bdVinSearchEntity.vehicleModel',
                    dataSource: 'VehicleModelNameList'
                }
            },
            CaseNumber: {
                width: "100%",
                placeholder: $translate.instant('InputPlaceholder'),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'bdVinSearchEntity.caseNumber',
                }
            },//The define of search field. -->end
            

            //The define of Grid options. -->start
            bdVinGridOptions: {
                bindingOptions: {
                    dataSource: 'vinList',
                    'height': 'height'
                },
                keyExpr: 'vin',
                noDataText: $scope.noDataText,
                columnAutoWidth: true,
                showRowLines: true,
                showBorders: true,
                columnChooser: {
                    enabled: true
                },
                paging: {
                    enabled: false
                },
                columns: [
                    { dataField: 'vin', caption: $translate.instant('VIN'), allowHeaderFiltering: false },
                    { dataField: 'vehicleModel', caption: $translate.instant('VehicleModel'), allowHeaderFiltering: false },
                    { dataField: 'count', caption: $translate.instant('InvoiceCount'), allowHeaderFiltering: false },
                    {
                        dataField: 'totalTaxAmount', caption: $translate.instant('DrilldownTotalTaxAmount'),
                        format: { type: 'fixedPoint', precision: 2 }, allowHeaderFiltering: false
                    },
                    {
                        dataField: 'totalEffectiveAmount', caption: $translate.instant('TotalEffectiveAmount'),
                        format: { type: 'fixedPoint', precision: 2 }, allowHeaderFiltering: false
                    },
                ],
                masterDetail: {
                    enabled: true,
                    template: "gdInvoiceTemplate"
                },
                bdView: function (bdInvoices) {
                    bdInvoices.forEach(function (item) {
                        item.invoiceNo = item.invoiceNumber;
                        item.invoiceCase = '';
                        item.issuedDate = item.bdIssuedDate ? (new Date(item.bdIssuedDate)).dateTimeToString('yyyyMMdd') : '';
                        item.caseCollectionDate = item.caseCollectionDate ? (new Date(item.caseCollectionDate)).dateTimeToString('yyyyMMdd') : '';
                        item.issuranceType = $translate.instant(PWC.getEnumKeyByValue(enums.IssuanceType, item.issuranceType));
                        if (!item.cabinConfiguration) {
                            item.cabinConfiguration = $translate.instant('FiveSeatInterior');
                        }
                    });
                    return {
                        keyExpr: 'id',
                        dataSource: bdInvoices,
                        noDataText: $scope.noDataText,
                        columnAutoWidth: true,
                        selection: {
                            mode: 'multiple',
                            showCheckBoxesMode: 'always'
                        },
                        onSelectionChanged: function (e) {
                            if (e && e.selectedRowsData) {
                                $scope.selectedIssuedInvoiceCount = e.selectedRowsData.length;
                                $scope.selectedIssuedInvoiceData = e.selectedRowsData;
                                var amount = 0;
                                _.each(e.selectedRowsData, function (item) {
                                    if (item.subtotalforFinalPayment) {
                                        amount += item.subtotalforFinalPayment;
                                    }
                                });
                                $scope.selectedIssuedInvoiceAmount = amount.formatAmount(2);
                            }
                        },
                        showBorders: true,
                        columns: [
                          { dataField: 'invoiceNo', caption: $scope.masterDetailHeader.invoiceNo, allowHeaderFiltering: false },
                          { dataField: 'invoiceCode', caption: $scope.masterDetailHeader.invoiceCode, allowHeaderFiltering: false },
                          { dataField: 'caseNumber', caption: $scope.masterDetailHeader.invoiceCaseNum, allowHeaderFiltering: false },
                          {
                              dataField: 'issuedDate', caption: $scope.masterDetailHeader.issuedDate,
                              dataType: 'date', format: dateFormat, allowHeaderFiltering: false
                          },
                          { dataField: 'registrationLocalName', caption: $scope.masterDetailHeader.buyer, allowHeaderFiltering: false },
                          {
                              dataField: 'excludeTaxPrice', caption: $scope.masterDetailHeader.amount,
                               format: { type: 'fixedPoint', precision: 2 }, allowHeaderFiltering: false
                          },
                          {
                              dataField: 'vatTax', caption: $scope.masterDetailHeader.taxAmount,
                              format: { type: 'fixedPoint', precision: 2 }, allowHeaderFiltering: false
                          },
                          {
                              dataField: 'subtotalforFinalPayment', caption: $scope.masterDetailHeader.totalAmount,
                               format: { type: 'fixedPoint', precision: 2 }, allowHeaderFiltering: false
                               //calculateDisplayValue: function (rowData) {
                               //    var r = 0;
                               //    if (_.isNumber(rowData.subtotalforFinalPayment)) {
                               //        r += rowData.subtotalforFinalPayment;
                               //    }
                               //    if (_.isNumber(rowData.taxableSubtotal)) {
                               //        r += rowData.taxableSubtotal;
                               //    }
                               //    return r;
                               //}
                           },
                           {
                                dataField: 'bdStatus', caption: $scope.masterDetailHeader.status,
                                calculateDisplayValue: function (rowData) {
                                    return $translate.instant(PWC.getEnumKeyByValue(enums.BDStatusEnum, rowData.bdStatus));
                                }
                           },
                           {
                                caption: $translate.instant('Action'), alignment: 'left', cellTemplate: function (ele, info) {
                                    $('<a/>').css({ 'color': '#6699cc', 'cursor': 'pointer' }).text($translate.instant('View')).on('dxclick', function () {
                                        $scope.invoiceOperateType = constant.Operation.Query;
                                        $scope.invoiceModel = info.data;
                                    }).appendTo(ele);

                                    var checkDateStart = new Date().dateAdd('d', -1 * (new Date().getDate() + 180)).dateTimeToString('yyyyMMdd');
                                    var checkDateEnd = new Date().dateAdd('d', -1 * new Date().getDate()).dateTimeToString('yyyyMMdd');
                                    if (info.data.bdStatus != enums.BDStatusEnum.RedLettered && info.data.bdStatus != enums.BDStatusEnum.Cancelled &&
                                        info.data.issuedDate >= checkDateStart && info.data.issuedDate <= checkDateEnd) {
                                        var element = $('<a/>');
                                        element.css({ 'color': '#6699cc', 'cursor': 'pointer', 'margin-left': '10px' }).text($translate.instant('Red Letter')).on('dxclick', function () {
                                            $scope.redLetterBdUserInvoice(info.data, element);
                                        }).appendTo(ele);
                                    }
                                }
                            }]

                    };

                }
            }//The define of Grid options. -->end
        };

        //Red letter BD-User fapiao. -->start
        $scope.redLetterBdUserInvoice = function (data, element) {

            var redLetterBdUserPopController = function ($scope) {
                $scope.redLetterData = {};
                $scope.redLetterData.needReasonRdio = 1;

                $scope.redLetterData.inputReasonOption = {
                    width: '100%',
                    height: 60,
                    bindingOptions: {
                        value: 'redLetterData.inputReason'
                    }
                };
                $scope.validateOption = {};
                $scope.validateOption.inputReasonOption = {
                    validationRules: [{
                        type: "required",
                        message: $translate.instant('BdUserRedLetterWarningInfoInputRequired')
                    }, {
                        type: 'stringLength',
                        max: 500,
                        message: $translate.instant('BdUserRedLetterWarningInfoInputLengthCheck')
                    }]
                };

                var addBdUserRedLetterReason = function (files) {
                    var reasonData = {};
                    reasonData.invoicingReasonIndex = $scope.redLetterData.needReasonRdio;
                    if ($scope.redLetterData.needReasonRdio == 2) {
                        reasonData.inputReason = $scope.redLetterData.inputReason;
                    }
                    reasonData.isRecievingAll = $scope.redLetterData.isRevievingAll ? 1 : 0;
                    reasonData.invoiceID = data.id;
                    reasonData.caseNumber = data.caseNumber;

                    //用户首字母大写
                    var tmpChar = loginContext.userName.substring(0, 1).toUpperCase();
                    var postString = loginContext.userName.substring(1, loginContext.userName.length);
                    var tmpStr = tmpChar + postString;
                    reasonData.createBy = tmpStr;

                    //设置附件
                    if (files && files.length > 0) {
                        var fileIds = [];
                        _.each(files, function (item) {
                            fileIds.push(item.data.fileID);
                        });
                        reasonData.evidenceDocuments = fileIds.join(',');
                    }

                    var deffered = $q.defer();
                    vatOutputInvoiceManageService.addBdUserRedLetterReason(reasonData).success(function (data) {
                        deffered.resolve(data);
                    });
                    return deffered.promise;
                };

                //BD红冲检查。
                var checkDataAvailable = function (files) {
                    if ($scope.redLetterData.needReasonRdio == 2) {

                        var dxResult = DevExpress.validationEngine.validateGroup($('#reasonModalForm').dxValidationGroup("instance")).isValid;
                        if (!dxResult) {
                            return;
                        }

                        if (!$scope.redLetterData.inputReason) {
                            SweetAlert.warning($translate.instant('BdUserRedLetterWarningInfoInputRequired'));
                            return false;
                        } else if ($scope.redLetterData.inputReason.length > 500) {
                            SweetAlert.warning($translate.instant('BdUserRedLetterWarningInfoInputLengthCheck'));
                            return false;
                        }
                    }
                    if (!files || files.length < 1 || !$scope.redLetterData.isRevievingAll) {
                        //检查证明文件
                        if (!files || files.length < 1) {
                            $('#UploadFileCheckTipId').show();
                        } else {
                            $('#UploadFileCheckTipId').hide();
                        }
                        if (!$scope.redLetterData.isRevievingAll) {
                            $('#CancelDialogTextTipId').show();
                        } else {
                            $('#CancelDialogTextTipId').hide();
                        }
                        return false;
                    } else {
                        $('#UploadFileCheckTipId').hide();
                        $('#CancelDialogTextTipId').hide();
                    }
                    return true;
                };

                $scope.$watch('$parent.uploadFileOption.files', function (newValue, oldValue) {
                    if (newValue && newValue != oldValue) {
                        var files = $scope.$parent.uploadFileOption.files;
                    }
                });

                //上传文件
                $scope.uploadFile = function () {
                    $scope.$parent.uploadFileType = 'multiple';
                    $scope.$parent.uploadFileOption = {
                        title: 'Upload Evidence Document',
                        uploadButtonText: 'Select Upload Files',
                        files: $scope.$parent.uploadFileOption.files || []
                    };
                }

                //关闭弹窗口
                $scope.hidePopPanel = function () {
                    $scope.$parent.uploadFileOption = {};
                    $scope.$dismiss({ $value: 'cancel' });
                };

                //删除证据文件
                $scope.deleteEvidenceFile = function (fileId) {
                    var fileList = [fileId];
                    vatOutputInvoiceManageService.deleteEvidenceFile(fileList).then(function () {
                        $scope.$parent.uploadFileOption.files = _.filter($scope.$parent.uploadFileOption.files, function (item) {
                            return item.data.fileID != fileId;
                        });
                    });
                }

                //下载证据文件
                $scope.downloadEvidenceFile = function (data) {
                    var queryDto = {};
                    queryDto.fileName = data.fileName;
                    queryDto.filePath = data.filePath;
                    vatOutputInvoiceManageService.downloadEvidenceFile(queryDto);
                };

                //执行红冲发票
                $scope.confirmRedLetterInvoice = function (files) {
                    if (checkDataAvailable(files)) {
                        //调用红冲接口
                        vatOutputInvoiceManageService.redLetterInvoice(data.id).then(function () {
                            //保存红冲原因及附件。
                            var promise = addBdUserRedLetterReason(files);
                            promise.then(function (data) {
                                //红冲结束隐藏红冲按钮。
                                element.hide();
                                $scope.$parent.uploadFileOption = {};
                                $scope.$dismiss({ $value: 'cancel' });
                                $scope.eventService.refreshInvoiceDataGrid();
                            });
                        });
                    }
                };

            };

            var parentElem = angular.element($document[0].querySelector('#red-letter-bd-user-pop'));
            var modalInstance = $uibModal.open({
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                backdrop: 'static',
                templateUrl: 'red-letter-bd-user-page.html',
                controller: redLetterBdUserPopController,
                windowClass: 'data-table',
                appendTo: parentElem,
                scope: $scope
            });
        };//Red letter BD-User fapiao. -->end

        $scope.cancelCore = function () {
            //调用取消发票接口执行取消发票功能。
            var promiss = [];
            var data = $scope.selectedIssuedInvoiceData;
            _.each(data, function (item) {
                var cancelPromiss = vatOutputInvoiceManageService.cancelInvoice(item.id, $scope.isReprint);
                promiss.push(cancelPromiss);
            });
            $q.all(promiss).then(function () {
                modalAdapterService.close(constant.OutputInvoiceCancalDialog, "bd-vin-view");
                $scope.eventService.refreshInvoiceDataGrid();
            });
        };

        //取消发票
        $scope.CancelInvoice = function (data, reprint) {
            if (!data || data.length < 1) {
                SweetAlert.warning($translate.instant('SelectBdInvoiceCheck'));
                return;
            }

            //已红冲和已取消的发票不能再做取消操作。
            var canCancelDatas = [];
            var negativeDatas = [];
            _.each(data, function (item) {
                if (item.bdStatus == enums.BDStatusEnum.Cancelled || item.bdStatus == enums.BDStatusEnum.RedLettered) {
                    canCancelDatas.push(item);
                }
            });

            _.each(data, function (item) {
                if (item.subtotalforFinalPayment < 0) {
                    negativeDatas.push(item);
                }
            });
            if (canCancelDatas.length > 0) {
                SweetAlert.warning($translate.instant('BDFapiaoCancelCheck')
                    .replace('{0}', _.pluck(canCancelDatas, 'invoiceNumber').join(',')));
                return;
            }

            if (negativeDatas.length > 0) {
                SweetAlert.warning($translate.instant('NegativeFapiaoCheck')
                    .replace('{0}', _.pluck(negativeDatas, 'invoiceNumber').join(',')));
                return;
            }

            $scope.title = reprint ? $translate.instant("CancelReprintInvoiceBDTitle") : $translate.instant("CancelInvoiceBDTitle")
            $scope.isReprint = reprint ? reprint : false;
            modalAdapterService.open(constant.OutputInvoiceCancalDialog, "bd-vin-view");
        };

        //The define of page event. -->start
        $scope.eventService = {
            refreshInvoiceDataGrid: function () {
                var dataDto = {
                    queryParam: $scope.bdVinSearchEntity,
                    pagingParam: $scope.pagingOptions
                }
                vatOutputInvoiceManageService.getBDDetailGroupByVIN(dataDto).success(function (response) {
                    $scope.vinList = response.list;
                    $scope.pagingOptions.totalItems = response.pageInfo.totalCount;
                }).error(function () {
                    SweetAlert.error('', $translate.instant('CommonFail'));
                });
            },

            toggleSearchContent: function () {
                if ($("#toggle-search-tr").css("display") == "none") {
                    $(".hide-search-btn").addClass("fa-angle-up").html('&nbsp;&nbsp;Collapse');
                    $(".hide-search-btn").removeClass("fa-angle-down");
                } else {
                    $(".hide-search-btn").addClass("fa-angle-down").html('&nbsp;&nbsp;Expand');
                    $(".hide-search-btn").removeClass("fa-angle-up");
                }
                $("#toggle-search-tr").toggle(200);
                $timeout(function () {
                    $scope.setInvoiceGridHeight();
                }, 300);
            }
        };//The define of page event. -->end

        (function () {
            $scope.eventService.refreshInvoiceDataGrid();
            $scope.hasShowMoreSearchBox = false;
            $scope.uploadFileOption = {};

            //fixed bug 13761, 测试说这个要跟vat drilldown相同。以前是取自printed表,现在改为取自imported表。
            //vatOutputInvoiceManageService.getVehicleModelNameList().success(function (result) {
            //    $scope.VehicleModelNameList = result;
            //});
            vatOutputInvoiceManageService.getModelSeries().success(function (response) {
                if (response && response.length > 0) {
                    $scope.VehicleModelNameList = _.map(response, function (item) {
                        return { id: item, name: item };
                    });
                }
            }).error(function (err) {
                SweetAlert.error('', $translate.instant('CommonFail'));
            });
            //设置表格高度
            $timeout(function () {
                $scope.setInvoiceGridHeight();
            }, 500);
        })();


    }]);