invoiceModule.controller('invoiceDetailVehicleController', ['$log', '$scope', '$translate', '$document', '$uibModal', '$timeout',
    'vatOutputInvoiceManageService', 'SweetAlert', 'enums',
    function ($log, $scope, $translate, $document, $uibModal, $timeout, vatOutputInvoiceManageService, SweetAlert, enums) {
        var revertStatusList = _.invert(enums.GDBDStatusEnum);
        $scope.redLettered = enums.GDBDStatusEnum.redLettered;
        $scope.hasUpdate = false;
        $scope.detailDialog = {
            modalInstance: null,
            open: function () {
                var parentElem = $scope.parentElement ?
                            angular.element($document[0].querySelector('.' + $scope.parentElement)) : undefined;
                $scope.detailDialog.modalInstance = $uibModal.open({
                    animation: false,
                    backdrop: false,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'myModalContent.html',
                    windowClass: 'GD-Vechicle-detail',
                    scope: $scope,
                    appendTo: parentElem
                });


            },
            cancel: function () {
                $scope.detailDialog.modalInstance.dismiss('cancel');
                if ($scope.hasUpdate&&_.isFunction($scope.parentRefresh)) {
                    $scope.parentRefresh();
                }
                $scope.hasUpdate = false;
            }
        };
        $scope.vehicleDetailOptions = {
            bindingOptions: {
                dataSource: 'invoiceDetail.details'
            },
            width: '99%',
            noDataText: $translate.instant('NoData'),
            columnAutoWidth: true,
            showBorders: true,
            showRowLines: true,
            columns: [
                { dataField: 'vin', caption: $translate.instant('VIN') },
                { dataField: 'vehicleModel', caption: $translate.instant('VehicleModel') },
                { dataField: 'quantity', caption: $translate.instant('Quantity'), alignment: 'left' },
                {
                    dataField: 'price', caption: $translate.instant('UnitPrice'),
                    alignment: 'right', format: { type: 'fixedPoint', precision: 2 }
                },
                {
                    dataField: 'amount', caption: $translate.instant('Amount'),
                    alignment: 'right', format: { type: 'fixedPoint', precision: 2 }
                },
                {
                    dataField: 'taxRate', caption: $translate.instant('TaxRate'),
                    alignment: 'right',
                    calculateDisplayValue: function (rowData) {
                        // return rowData.taxRate.formatRate(0);
                        var num = (rowData.taxRate * 100).formatAmount(0);
                        return num + "%";
                    }
                },
                {
                    dataField: 'taxAmount', caption: $translate.instant('TaxAmount'),
                    alignment: 'right', format: { type: 'fixedPoint', precision: 2 }
                },
                {
                    dataField: 'gdBdStatus', caption: $translate.instant('Status'),
                    calculateDisplayValue: function (rowData) {
                        //fix 12875
                        //if ($scope.invoiceStatus === enums.GDInvoiceStatusEnum.cancelled) {
                        //    return $translate.instant(revertStatusList[enums.GDBDStatusEnum.cancelled]);
                        //}
                        return $translate.instant(revertStatusList[rowData.status]);
                    }
                },
                {
                    caption: $translate.instant('Action'), width: '120px',
                    cellTemplate: 'redLetterTemplate'
                }

            ],
            onRowPrepared: function (e) {
                if (e.rowType === 'totalFooter') {
                    var instance = e.component;
                    var grandTotal = instance.getTotalSummaryValue('totalAmount') + instance.getTotalSummaryValue('totalTaxAmount');
                    if (_.isNumber(grandTotal)) {
                        grandTotal = grandTotal.formatAmount(2);
                    }
                    var grandStr = $translate.instant('GrandTotal');
                    var trStr = "<tr class='dx-row' role='row'>"
                        + '<td role="gridcell" aria-label="Column VIN, Value undefined" style="text-align: left;">' 
                        + '<div class="dx-datagrid-summary-item dx-datagrid-text-content" >'
                        + grandStr +'&nbsp;'+ grandTotal+'</div></td>'
                        + '<td role="gridcell" aria-label="Column Vehicle Model, Value undefined" style="text-align: left;"></td>'
                        + '<td role="gridcell" aria-label="Column 数量, Value undefined" style="text-align: left;"></td>'
                        + '<td role="gridcell" aria-label="Column Price, Value undefined" style="text-align: right;"></td>'
                        + '<td role="gridcell" aria-label="Column Amount, Value undefined" style="text-align: right;"></td>'
                        + '<td role="gridcell" aria-label="Column 税率, Value undefined" style="text-align: left;"></td>'
                        + '<td role="gridcell" aria-label="Column 税额, Value undefined" style="text-align: left;"></td>'
                        + '<td role="gridcell" aria-label="Column Status, Value undefined" style="text-align: left;"></td>'
                        + '<td role="gridcell" aria-label="Column , Value undefined" style="text-align: left;"></td>'
                       + "</tr>"
                    e.rowElement.after(trStr);
                }
            },
            summary: {
                totalItems: [
                     {
                         column: 'price',
                         customizeText: function (item) {
                             return $translate.instant('TotalPrice');
                         }
                     },
                    {
                        name: 'totalAmount',
                        column: 'amount',
                        summaryType: 'sum',
                        customizeText: function (data) {
                            return data.value.formatAmount(2);
                        }
                    },
                    {
                        name: 'totalTaxAmount',
                        column: 'taxAmount',
                        summaryType: 'sum',
                        customizeText: function (data) {
                            return data.value.formatAmount(2);
                        }
                    }
                ]
            }

        };


        $scope.eventService = {            
            LoadData: function () {
                if ($scope.detailKey) {
                    vatOutputInvoiceManageService.getGBInvoiceDetail($scope.detailKey).success(function (response) {
                        if (response.result) {
                            $scope.invoiceDetail = response.data;
                           
                            $scope.needHide = $scope.hideAction;
                          
                            //invoiceStatus
                            //GD发票是红冲或者取消状态,就不能操作
                            //或者车辆本身已经红冲过的就不能操作
                            if ($scope.invoiceStatus) {
                                //has value
                                $scope.needHide = $scope.needHide||$scope.invoiceDetail.isRedInvoice || $scope.invoiceStatus === enums.GDInvoiceStatusEnum.cancelled ||
                                    $scope.invoiceStatus === enums.GDInvoiceStatusEnum.redLettered;
                                
                            }
                            //红冲-除去当月往前退180,如果开票日期在这里面的就可以红冲
                            var currentDate = new Date();
                            var currentMonth = currentDate.getMonth();
                            var endDate = new Date(currentDate.getFullYear(), currentMonth, 1);
                            var one_day = 1000 * 60 * 60 * 24;
                            var startDate = new Date(endDate.getTime() - one_day * 180);
                            var iDate = new Date($scope.invoiceDetail.gdIssuedDate);
                            $scope.needHide = $scope.needHide ||iDate < startDate|| iDate > endDate
                          
                            $scope.detailDialog.open();
                        } else {
                            SweetAlert.error('', $translate.instant(response.resultMsg));
                        }

                    }).error(function () {
                        SweetAlert.error('', $translate.instant('CommonFail'));
                    });
                }

            },
            confirmRedLetter: function (rowData) {
                SweetAlert.swal({
                    title: $translate.instant('RedLetterConfirmTitle'),
                    text: $translate.instant('RedLetterConfirmText'),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('ENCancel'),
                    closeOnConfirm: true,
                    closeOnCancel: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        $scope.eventService.toRedLetter(rowData);
                    }
                });
            },
            toRedLetter: function (rowData) {
                var id = rowData.detailID;               
                //to connect baiwang interface and update the printed ID GB-BD status
                vatOutputInvoiceManageService.gdRedLetter(id).success(function (response) {
                    if (response&&response.result) {
                        //返回的是GD-BD发票的状态
                        $scope.invoiceStatus = response.resultMsg;
                        rowData.status = $scope.redLettered;
                        $scope.needHide = $scope.invoiceStatus === enums.GDInvoiceStatusEnum.cancelled ||
                                  $scope.invoiceStatus === enums.GDInvoiceStatusEnum.redLettered;
                        
                        $('#vehicleDetail').dxDataGrid('instance').refresh();
                        $scope.hasUpdate = true;

                    } else {
                        var msg = response ? response.resultMsg : "NotFindItem";
                        SweetAlert.error('', $translate.instant(msg));
                    }

                }).error(function () {
                    SweetAlert.error('', $translate.instant('CommonFail'));
                });
            },
            loadDataAfterReady: function () {
                $timeout(function () {
                    $scope.eventService.LoadData();
                }, 600);
            }

        };

    }
])