issued-invoice-gd-view.ctrl.js 44.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
invoiceModule.controller('issuedInvoiceGdViewController', ['$scope', '$log', '$document', '$uibModal', '$translate',
    '$q', '$interval', '$timeout', '$location', '$state', 'SweetAlert', 'orgService', 'vatOutputInvoiceManageService',
    'enums', 'messagebox',
    function ($scope, $log, $document, $uibModal, $translate, $q, $interval, $timeout, $location, $state, SweetAlert,
        orgService, vatOutputInvoiceManageService, enums, messagebox) {
        'use strict';
        var maxValueLimit = 1000000000.00;
        var bdOptionTemplate = {
            displayExpr: 'displayName',
            valueExpr: 'code',
            width: "100%",
            placeholder: $translate.instant("ChoosePlaceholder"),
            bindingOptions: {
                value: 'searchEntity.bd'
            },
            itemTemplate: 'bdList',
            showClearButton: true
        };

        var bdEntityList = [];

        var vrlOptionTemplate = {
            displayExpr: 'name',
            valueExpr: 'name',
            width: "100%",
            placeholder: $translate.instant("ChoosePlaceholder"),
            bindingOptions: {
                value: 'searchEntity.vrl'
            },
            itemTemplate: 'vrlList'
        };

        var init = function () {
            $scope.selectedItems = [];
            $scope.selectedTotalAmount = 0;
            $scope.invoiceMarkupRatioEntity = {};
            $scope.invoiceQuotaEntity = {};
            $scope.preIssueEntity = {};
            $scope.selectedGDInvoiceID = null;

            thisService.getinvoiceQuota();
        };

        //-----------------搜索对象定义-----------------//start
        var isShowClearButton = true;
        var gdStatusList = _.chain(enums.GDBDStatusEnum)
            .invert().pairs().map(function (x) {
                return [x[0], $translate.instant(x[1])];
            }).value();
        var bdStatusList = _.chain(enums.BDStatusEnum)
            .invert().pairs().map(function (x) {
                return [x[0], $translate.instant(x[1])];
            }).value();
        $scope.searchEntity = {};
        $scope.searchOptions = {
            invoiceNo: {
                width: "100%",
                placeholder: $translate.instant("InputPlaceholder"),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'searchEntity.invoiceNo'
                }
            },
            vin: {
                width: "100%",
                placeholder: $translate.instant("InputPlaceholder"),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'searchEntity.vin'
                }
            },
            gdStatus: {
                dataSource: gdStatusList,
                displayExpr: '1',
                valueExpr: '0',
                multiline: false,
                width: "100%",
                placeholder: $translate.instant("ChoosePlaceholder"),
                showDropButton: true,
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'searchEntity.gdStatus'
                }
            },
            bdStatus: {
                dataSource: bdStatusList,
                displayExpr: '1',
                valueExpr: '0',
                multiline: false,
                width: "100%",
                placeholder: $translate.instant("ChoosePlaceholder"),
                showDropButton: true,
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'searchEntity.bdStatus'
                }
            },
            issuedPeriodStart: {
                type: 'date',
                width: "100%",
                placeholder: $translate.instant("ChoosePlaceholder"),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'searchEntity.startTime'
                },
                displayFormat: 'yyyy-MM-dd',
            },
            issuedPeriodEnd: {
                type: 'date',
                width: "100%",
                placeholder: $translate.instant("ChoosePlaceholder"),
                showClearButton: isShowClearButton,
                bindingOptions: {
                    value: 'searchEntity.endTime',
                },
                displayFormat: 'yyyy-MM-dd',
            },
            markupRatio: 0,
            invoiceQuota: 10000000
        };

        $scope.toggleSearchContent = function () {
            if ($(".toggle-search-tr").css("display") == "none") {
                $(".hide-search-btn").addClass("fa-angle-up").html('  Collapse');
                $(".hide-search-btn").removeClass("fa-angle-down");
            } else {
                $(".hide-search-btn").addClass("fa-angle-down").html('  Expand');
                $(".hide-search-btn").removeClass("fa-angle-up");
            }
            $(".toggle-search-tr").toggle(200);
            $timeout(function () {
                $scope.setInvoiceGridHeight();
            }, 300);
        };

        //-----------------搜索对象定义-----------------//end

        //-----------------表格对象定义-----------------//start
        $scope.dataGridOption = {
            keyExpr: 'id',
            showRowLines: true,
            showColumnLines: true,
            showBorders: true,
            allowColumnReordering: true,
            allowColumnResizing: true,
            columnAutoWidth: true,
            hoverStateEnabled: true,
            columnFixing: {
                enabled: true
            },
            columnChooser: {
                enabled: true
            },
            paging: {
                enabled: false
            },
            selection: {
                mode: 'multiple',
                showCheckBoxesMode: 'always'
            },
            bindingOptions: {
                dataSource: 'invoiceGridDataSource',
                height: 'dataGridHeight'
            },
            onSelectionChanged: function (s) {
                $scope.selectedItems = s.selectedRowsData;
                $scope.selectedTotalAmount = _.reduce(s.selectedRowsData, function (memo, item) {
                    return memo + item.amountAdjusted;
                }, 0);
            }
        };

        $scope.dataGridOption.columns = [
            { dataField: 'entityName', caption: $translate.instant('BDName'), alignment: 'left' },
            { dataField: 'vehicleroutinglocation', caption: $translate.instant('VRL'), alignment: 'left' },
            { dataField: 'vin', caption: $translate.instant('VIN'), alignment: 'left' },
            { dataField: 'invoiceNumber', caption: $translate.instant('InvoiceNo'), alignment: 'left', visible: false },
            { dataField: 'invoiceCode', caption: $translate.instant('InvoiceCode'), alignment: 'left', visible: false },
            { dataField: 'bdIssuedDate', caption: $translate.instant('IssuedDate'), alignment: 'left' },
            {
                dataField: 'amount', format: 'currency', precision: 2,
                caption: $translate.instant('SubtotalForFinalPayment'), alignment: 'right'
            },
            {
                dataField: 'amountAdjusted', format: 'currency', precision: 2,
                caption: $translate.instant('AmountAdjusted'), alignment: 'right'
            },
            { dataField: 'deliveryStatus', caption: $translate.instant('DeliveryStatus'), alignment: 'left' },
            {
                dataField: 'gdBdStatusStr', caption: $translate.instant('GDStatus'), alignment: 'left'
            },
            {
                caption: $translate.instant('ViewGDBDFapiao'), alignment: 'left',
                cellTemplate: function (ele, info) {
                    if (info.data.buyerOrganizationCode && info.data.gdIssuedId) {
                        $('<a/>').css({ 'color': '#923', 'cursor': 'pointer' })
                            .text($translate.instant('IssuedTo') + info.data.buyerOrganizationCode)
                            .on('dxclick', function () {
                                dataService.showGdInvoice(info.data.gdIssuedId, info.data.gdBdStatus);
                            }).appendTo(ele);
                    }
                }
            },
            { dataField: 'bdStatusStr', caption: $translate.instant('BDStatus'), alignment: 'left' },
            {
                caption: $translate.instant('BDFapiao'), alignment: 'left',
                cellTemplate: function (ele, info) {
                    $('<a/>').css({ 'color': '#923', 'cursor': 'pointer' })
                        .text($translate.instant('View'))
                        .on('dxclick', function () {
                            $scope.invoiceOperateType = constant.Operation.Query;
                            $scope.invoiceModel = info.data;
                        }).appendTo(ele);
                }
            },
            { dataField: 'caseNumber', caption: $translate.instant('InvoiceCaseNo'), alignment: 'left', visible: false },
            { dataField: 'vehicleModel', caption: $translate.instant('VehicleModel'), alignment: 'left', visible: false }
           /* { dataField: 'caseCollectionDate', caption: $translate.instant('CaseCollectionDate'), alignment: 'left', visible: false } */
        ];
        //-----------------表格对象定义-----------------//end

        //-----------------数据服务-----------------//start
        var dataService = {
            //筛选invoice list
            search: function () {
                var deferred = $q.defer();

                var invoiceParams = {
                    queryParam: $scope.searchEntity,
                    pagingParam: $scope.pagingOptions,
                };

                vatOutputInvoiceManageService.getIssuedInvoiceGdList(invoiceParams).success(function (data) {
                    if (data && data.list) {
                        $scope.pagingOptions.totalItems = data.pageInfo && data.pageInfo.totalCount;
                        data.list.forEach(function (item) {
                            var entity = _.findWhere(bdEntityList, { code: item.bdFapiaoEntity });

                            item.gdIssuedDate = item.gdIssuedDate ? (new Date(item.gdIssuedDate)).dateTimeToString('yyyyMMdd') : '';
                            item.bdIssuedDate = item.bdIssuedDate ? (new Date(item.bdIssuedDate)).dateTimeToString('yyyyMMdd') : '';
                            item.caseCollectionDate = item.caseCollectionDate ? (new Date(item.caseCollectionDate)).dateTimeToString('yyyyMMdd') : '';
                            item.entityName = entity ? (entity.code + ' ' + entity.name) : '';
                            item.amount = item.subtotalforFinalPayment;

                            if (item.printedType == 2) {
                                item.amountAdjusted = null;
                            } else {
                                item.amountAdjusted = (1 - $scope.searchOptions.markupRatio) * item.taxableSubtotal;
                            }

                            item.bdStatusStr = $translate.instant(PWC.getEnumKeyByValue(enums.BDStatusEnum, item.bdStatus));
                            item.gdBdStatusStr = $translate.instant(PWC.getEnumKeyByValue(enums.GDBDStatusEnum, item.gdBdStatus));
                            //fix bug 12828
                            if (item.gdBdStatus === enums.GDBDStatusEnum.readyToIssue) {
                                if (item.bdStatus !== enums.BDStatusEnum.NormalStatus
                                    && item.bdStatus !== enums.BDStatusEnum.Matched
                                    //fix bug 13668
                                    && item.bdStatus !== enums.BDStatusEnum.Duplicated) {
                                    item.gdBdStatusStr = "";
                                }
                                if (item.isBDRed) {
                                    item.gdBdStatusStr = "";
                                }
                            }


                        });
                        var source = data.list;
                        //fix bug13147
                        //这里使用==而不使用===,是因为$scope.searchEntity.gdStatus这个是字符串,enums.GDBDStatusEnum.readyToIssue这个是数字
                        //故"3"==3 true "3"===3 false 这里需要"3"==3
                        //if ($scope.searchEntity.readyToIssue || $scope.searchEntity.gdStatus == enums.GDBDStatusEnum.readyToIssue) {
                        //    source = _.filter(source, function (item) {
                        //        return item.gdBdStatusStr !== "";
                        //    });
                        //}
                        $scope.invoiceGridDataSource = source;
                        deferred.resolve(data);
                    };
                });
                return deferred.promise;
            },

            getBdList: function () {
                return orgService.getBdList().then(function (data) {
                    if (data && data.data) {
                        //data.data.unshift({
                        //    id: '',
                        //    name: '',
                        //    code: '',
                        //    vehicleroutinglocation: ''
                        //});

                        _.each(data.data, function (x) {
                            x.displayName = x.code + ' ' + x.name;
                        });
                        return $q.when(data.data);
                    }
                    else {
                        return $q.when(null);
                    }
                }).then(function (data) {
                    bdEntityList = data;
                    $scope.searchOptions.bd = _.extend(bdOptionTemplate, {
                        dataSource: data
                    });

                    // Get VRL list
                    var vrlList = _.chain(data).reject(function (x) {
                        return _.isEmpty(x.vehicleroutinglocation);
                    }).map(function (x) {
                        return { name: x.vehicleroutinglocation };
                    }).sortBy(function (x) {
                        return x.name;
                    }).uniq(true, function (x) {
                        return x.name;
                    }).value();
                    vrlList.unshift({ name: '' });

                    $scope.searchOptions.vrl = _.extend(vrlOptionTemplate, {
                        dataSource: vrlList
                    });

                    return $q.when(data);
                });
            },

            showGdInvoice: function (id, gdStatus) {
                $scope.selectedGDInvoiceID = id;
                $scope.selectedGDInvoiceStatus = gdStatus;
                $scope.$broadcast("openGDDetailDialog");
            },

            checkStatusBeforeIssue: function () {
                if (!$scope.selectedItems || $scope.selectedItems.length === 0) {
                    messagebox.warning('SelectBdInvoiceCheck');
                    return false;
                };
                //BD 红票不能开GD票
                var redInvoice = _.where($scope.selectedItems, { isBDRed: true });
                if (redInvoice && redInvoice.length > 0) {
                    messagebox.warning('RedInvoiceWarrning');
                    return false;
                }
                var unmatched = _.where($scope.selectedItems, { bdStatus: enums.BDStatusEnum.Unmatched });
                if (!_.isEmpty(unmatched)) {
                    SweetAlert.warning($translate.instant('BDStatusUnmatched')
                        .replace('{0}', _.pluck(unmatched, 'vin').join(',')));
                    return false;
                }

                var cancelledOrRedLettered = _.filter($scope.selectedItems, function (x) {
                    return x.bdStatus === enums.BDStatusEnum.Cancelled || x.bdStatus === enums.BDStatusEnum.RedLettered;
                });
                if (!_.isEmpty(cancelledOrRedLettered)) {
                    SweetAlert.warning($translate.instant('BDStatusCancelled')
                        .replace('{0}', _.pluck(cancelledOrRedLettered, 'vin').join(',')));
                    return false;
                }

                var gdNotReadyToIssue = _.filter($scope.selectedItems, function (x) {
                    return x.gdBdStatus !== enums.GDBDStatusEnum.readyToIssue
                        && x.gdBdStatus !== enums.GDBDStatusEnum.redLettered
                        && x.gdBdStatus !== enums.GDBDStatusEnum.cancelled;
                });
                if (!_.isEmpty(gdNotReadyToIssue)) {
                    SweetAlert.warning($translate.instant('GDStatusNotReady')
                        .replace('{0}', _.pluck(gdNotReadyToIssue, 'vin').join(',')));
                    return false;
                }

                return true;
            }
        };
        //-----------------数据服务-----------------//end

        //--------------设置发票折扣率--------------//start
        //红冲BD-User Invoice
        $scope.setInvoiceMarkupRatio = function () {

            var setInvoiceMarkupRatioController = ['$scope', function (scope) {
                scope.invoiceMarkupRatioEntity = scope.$parent.invoiceMarkupRatioEntity || {};
                scope.validateOption = {};
                scope.markupRatioOption = {
                    width: 230,
                    bindingOptions: {
                        value: 'invoiceMarkupRatioEntity.rate'
                    }
                };
                scope.validateOption.markupRatioOption = {
                    validationRules: [{
                        type: "required",
                        message: $translate.instant('MarkUpRateRequire')
                    }, {
                        type: 'numeric', message: $translate.instant('MarkupRatioInputFormatCheckInfo')
                    }, {
                        type: 'range',
                        min: 0, max: 99.99, message: $translate.instant('MarkupRatioInputFormatCheckInfo')
                    }]
                };

                scope.effectiveDateOption = {
                    width: 230,
                    type: 'date',
                    min: new Date(),
                    invalidDateMessage: $translate.instant('EffectiveDateSpellCheck'),
                    bindingOptions: {
                        value: 'invoiceMarkupRatioEntity.effectiveDate'
                    },
                    spellcheck: true,
                    onInput: function (e) {
                        scope.inputEffectiveDate = e.component.field().val();
                    },
                    displayFormat: 'yyyy-MM-dd',
                }

                scope.validateOption.effectiveDateOption = {
                    validationRules: [{
                        type: "required",
                        message: $translate.instant('MarkUpEffectiveDateRequire')
                    }]
                };

                //关闭弹窗口
                scope.hidePopPanel = function () {
                    scope.invoiceMarkupRatioEntity.rate = null;
                    scope.invoiceMarkupRatioEntity.effectiveDate = null;
                    scope.$dismiss({ $value: 'cancel' });
                };

                //输入数据检查
                scope.inputEffectiveDate;
                var checkSaveData = function () {
                    var dxResult = DevExpress.validationEngine.validateGroup($('#rateModalForm').dxValidationGroup("instance")).isValid;
                    if (!dxResult) {
                        return;
                    }
                    if (scope.invoiceMarkupRatioEntity.rate && scope.invoiceMarkupRatioEntity.effectiveDate) {
                        var rate = scope.invoiceMarkupRatioEntity.rate;
                        if (scope.invoiceMarkupRatioEntity.rate < 0 || scope.invoiceMarkupRatioEntity.rate >= 100) {
                            messagebox.warning('MarkupRatioInputFormatCheckInfo');
                            return false;
                        }

                        if (scope.inputEffectiveDate && new Date(scope.inputEffectiveDate).dateTimeToString('yyyyMMdd').indexOf('NaN') >= 0) {
                            messagebox.warning('EffectiveDateFormatCheckInfo');
                            return false;
                        }
                        if (scope.inputEffectiveDate && new Date(scope.inputEffectiveDate).dateTimeToString('yyyyMMdd') < new Date().dateTimeToString('yyyyMMdd')) {
                            messagebox.warning('EffectiveDateTimeCheckInfo');
                            return false;
                        }
                        scope.inputEffectiveDate = "";
                    } else {
                        messagebox.warning('MarkupRatioRequired');
                        return false;
                    }
                    return true;
                }

                //执行红冲发票
                scope.confirmSetInvoiceMarkupRatio = function () {
                    if (!checkSaveData()) {
                        return;
                    }

                    scope.invoiceMarkupRatioEntity.rate /= 100;
                    //保存折扣率
                    vatOutputInvoiceManageService.saveMarkupRatio(scope.invoiceMarkupRatioEntity).success(function (result) {
                        if (result && result.data) {
                            scope.invoiceMarkupRatioEntity = result.data;
                            if (result.data.currentRate) {
                                scope.searchOptions.markupRatio = result.data.currentRate;
                            } else {
                                scope.searchOptions.markupRatio = 0;
                            }
                            scope.$parent.invoiceMarkupRatioEntity = scope.invoiceMarkupRatioEntity;
                        }
                        scope.$dismiss({ $value: 'cancel' });
                        scope.invoiceMarkupRatioEntity.rate = null;
                        scope.invoiceMarkupRatioEntity.effectiveDate = null;

                        dataService.search();
                    });
                };

            }];

            var parentElem = angular.element($document[0].querySelector('#setup-mark-up-ratio-pop'));
            var modalInstance = $uibModal.open({
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                backdrop: 'static',
                templateUrl: 'setup-mark-up-ratio-page.html',
                controller: setInvoiceMarkupRatioController,
                windowClass: 'data-table',
                appendTo: parentElem,
                scope: $scope
            });
        };
        //--------------设置发票折扣率--------------//end

        //--------------设置发票限额--------------//start
        //设置发票限额
        $scope.setInvoiceQuota = function () {

            var setInvoiceQuotaController = ['$scope', function (scope) {
                scope.invoiceQuotaEntity = {};

                if (!_.isEmpty(scope.$parent.invoiceQuotaEntity)) {
                    _.extend(scope.invoiceQuotaEntity, scope.$parent.invoiceQuotaEntity);
                }

                scope.maxValueOption = {
                    width: 230,
                    bindingOptions: {
                        value: 'invoiceQuotaEntity.maxValue'
                    },
                    onFocusOut: function (e) {
                        var data = scope.invoiceQuotaEntity.maxValue;
                        var ele = e.component;
                        var result = PWC.AccountToFloat(scope.invoiceQuotaEntity.maxValue);
                       // var formatExp = /^[+-]?\d+(\.\d+)?$/;
                        //先验证是否是数字
                        if (result&&result.isNumber) {
                            var n = parseFloat(result.value);
                            //验证金额
                            if (n > maxValueLimit) {
                                ele.option("isValid", false);
                                ele.option("validationError", { message: $translate.instant('MaximumValueLengthCheckInfo') });
                                return;
                            }
                            //变成Account
                            scope.invoiceQuotaEntity.maxValue = n.formatAmount(2);
                            ele.option("isValid", true);
                            ele.option("validationError", { message: '' });
                        }
                        else
                        {
                            ele.option("isValid", false);
                            ele.option("validationError", { message: $translate.instant('MaximumValueFormatCheckInfo') });
                        }
                       
                    }
                };
                scope.maxValueOptionValid = {
                    validationRules: [
                        {
                            type: 'required',
                            message: $translate.instant('MaximumValueRequired')
                        },
                        //{
                        //    type: 'stringLength',
                        //    min:1,
                        //    max: 9,
                        //    message: $translate.instant('MaximumValueLengthCheckInfo')
                        //}
                    ]
                };

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

                //输入数据检查
                var checkSaveData = function () {
                    if (scope.invoiceQuotaEntity.maxValue) {
                        var formatExp = /^\d+$/;
                        if (!formatExp.test(scope.invoiceQuotaEntity.maxValue)) {
                            messagebox.warning('MaximumValueFormatCheckInfo');
                            return false;
                        }
                        else if (scope.invoiceQuotaEntity.maxValue.length > 9) {
                            messagebox.warning('MaximumValueLengthCheckInfo');
                            return false;
                        }
                    } else {
                        messagebox.warning('MaximumValueRequired');
                        return false;
                    }
                    return true;
                }

                //保存限额设置
                scope.confirmSetInvoiceQuota = function () {
                    //if (!checkSaveData()) {
                    //    return;
                    //}
                    var dxResult = DevExpress.validationEngine.validateGroup($('#setupGroup').dxValidationGroup("instance")).isValid;
                    if (!dxResult) {
                        return;
                    }
                    var ele = $('#max-value').dxTextBox('instance');
                    var result = PWC.AccountToFloat(scope.invoiceQuotaEntity.maxValue);
                    if (result && !result.isNumber) {
                        ele.option("isValid", false);
                        ele.option("validationError", { message: $translate.instant('MaximumValueFormatCheckInfo') });
                        return;
                    }
                    var data = result.value;
                    //验证长度
                    if (data >=maxValueLimit) {
                        ele.option("isValid", false);
                        ele.option("validationError", { message: $translate.instant('MaximumValueLengthCheckInfo') });
                        return;
                    }
                   
                    vatOutputInvoiceManageService.saveInvoiceQuota(data).success(function (result) {
                        if (result && result.data) {
                            scope.invoiceQuotaEntity.maxValue = parseFloat(result.data).formatAmount(2);
                            scope.searchOptions.invoiceQuota = result.data;
                            scope.$parent.invoiceQuotaEntity = scope.invoiceQuotaEntity;
                        }
                        scope.$dismiss({ $value: 'cancel' });
                    });
                };

            }];

            var parentElem = angular.element($document[0].querySelector('#setup-quota-pop'));
            var modalInstance = $uibModal.open({
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                backdrop: 'static',
                templateUrl: 'setup-quota-page.html',
                controller: setInvoiceQuotaController,
                windowClass: 'data-table',
                appendTo: parentElem,
                scope: $scope
            });
        };
        //--------------设置发票限额--------------//end

        //--------------打印前确认--------------//start
        //打印前确认
        $scope.selectedManualInput;
        $scope.popupPreIssue = function () {
            if (!dataService.checkStatusBeforeIssue()) {
                return;
            }

            var preIssueController = ['$scope', function (scope) {
                scope.preIssueEntity = scope.$parent.preIssueEntity || {};
                scope.preIssueEntity.page = 0;

                scope.uploadFileType = null;
                scope.uploadFileOption = null;

                scope.preIssueEntity.manualInputReasons = scope.manualInputReasons;

                scope.dataGridOption = {
                    height: 250,
                    showRowLines: true,
                    showColumnLines: true,
                    showBorders: true,
                    allowColumnReordering: false,
                    allowColumnResizing: true,
                    columnAutoWidth: true,
                    hoverStateEnabled: false,
                    columnFixing: {
                        enabled: true
                    },
                    paging: {
                        enabled: false
                    },
                    selection: {
                        mode: 'none'
                    },
                    bindingOptions: {
                        dataSource: 'shipmentDataSource'
                    }
                };

                scope.dataGridOption.columns = [
                    //{ dataField: 'vehicleroutinglocation', caption: $translate.instant('VRL'), alignment: 'left' },
                    { dataField: 'vin', caption: $translate.instant('VIN'), alignment: 'left' },
                    {
                        dataField: 'vehicleAmount', format: 'currency', precision: 2,
                        caption: $translate.instant('ShipmentVehicleAmount') + ' (A)', alignment: 'right',
                        headerCellTemplate: function (header, info) {
                            $("<div>").html(info.column.caption.replace(/\n/g, "<br/>")).appendTo(header);
                        }
                    },
                    {
                        dataField: 'shipmentAmount', format: 'currency', precision: 2,
                        caption: $translate.instant('ShipmentShipmentAmount') + ' (B)', alignment: 'right',
                        headerCellTemplate: function (header, info) {
                            $("<div>").html(info.column.caption.replace(/\n/g, "<br/>")).appendTo(header);
                        }
                    },
                    {
                        caption: $translate.instant('PriceCheck') + '\n(A-B)', alignment: 'right',
                        cellTemplate: function (ele, info) {
                            var checkResult = '';
                            if (_.isNumber(info.data.vehicleAmount) && _.isNumber(info.data.shipmentAmount)) {
                                var diff = info.data.vehicleAmount - info.data.shipmentAmount;
                                if (diff === 0) {
                                    checkResult = $translate.instant('Equal');
                                }
                                else {
                                    checkResult = diff.formatAmount();
                                }
                            }
                            else {
                                checkResult = '/';
                            }

                            ele.text(checkResult);
                        },
                        headerCellTemplate: function (header, info) {
                            $("<div>").html(info.column.caption.replace(/\n/g, "<br/>")).appendTo(header);
                        }
                    },
                    {
                        caption: $translate.instant('State'), alignment: 'left',
                        cellTemplate: function (ele, info) {
                            if (info.data.state === enums.ShipmentCheckStatusEnum.Normal) { // (!_.isNumber(info.data.vehicleAmount) || !_.isNumber(info.data.shipmentAmount)) {
                                ele.text($translate.instant('NormalStatus')).append('&nbsp;<i class="fa fa-check-circle" style="color: green;" aria-hidden="true"></i>');
                            }
                            else if (info.data.state === enums.ShipmentCheckStatusEnum.Unbalance) { // (info.data.vehicleAmount !== info.data.shipmentAmount) {
                                ele.text($translate.instant('Unbalance')).append('&nbsp;<i class="fa fa-exclamation-circle" style="color: red;" aria-hidden="true"></i>');
                            }
                            else {
                                ele.text($translate.instant('CantFind')).append('&nbsp;<i class="fa fa-question-circle" style="color: grey;" aria-hidden="true"></i>');
                            }
                        }
                    },
                    {
                        dataField: 'finalAmount', format: 'currency', precision: 2,
                        caption: $translate.instant('FinalAmount'), alignment: 'right'
                    },
                    {
                        caption: $translate.instant('Action'), alignment: 'left',
                        cellTemplate: function (ele, info) {
                            if (info.data.state === enums.ShipmentCheckStatusEnum.Normal) {
                                // Nothing to do.
                            }
                            else {
                                $('<a/>').css({ 'color': '#923', 'cursor': 'pointer' })
                                    .text($translate.instant('ManualInput'))
                                    .on('dxclick', function () {
                                        scope.$parent.selectedManualInput = info.data;
                                        scope.manualInput(info.data);
                                    }).appendTo(ele);
                            }
                        }
                    }
                ];

                scope.deleteFromIssuingList = function (data) {
                    messagebox.confirm($translate.instant('ConfirmDeleteVehicle'), '').then(function (isConfirm) {
                        if (isConfirm) {
                            var idx = _.findIndex(scope.shipmentDataSource, { vin: data.vin });
                            scope.shipmentDataSource.splice(idx, 1);
                        }
                    });
                };

                scope.manualInput = function (data) {
                    scope.manualInputModel = scope.$parent.manualInputModel = data;
                    scope.preIssueEntity.isOpenManualInput = true;
                };

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

                //确认并进入下一页
                scope.next = function () {
                    scope.preIssueEntity.page = 1;
                };

                scope.prev = function () {
                    scope.preIssueEntity.page = 0;
                };

                scope.confirm = function () {

                    scope.printGDInvoice();
                    scope.$close();
                };

            }];

            $q.all([
                vatOutputInvoiceManageService.getGdInvoiceInventory(),
                vatOutputInvoiceManageService.getCheckShipmentList(_.pluck($scope.selectedItems, 'vin')),
            ]).then(function (data) {
                if (data) {
                    if (data[0] && data[0].data && data[0].data.data) {
                        $scope.preIssueEntity = data[0].data.data;
                    } else {
                        $scope.preIssueEntity.inventory = 0;
                        $scope.preIssueEntity.thresholdValue = 100;
                        $scope.preIssueEntity.thresholdScale = 0.1;
                    }

                    if (data[1] && data[1].data) {
                        $scope.shipmentDataSource = _.map($scope.selectedItems, function (x) {
                            var shipment = _.findWhere(data[1].data, { vin: x.vin });
                            return {
                                vin: x.vin,
                                vehicleAmount: x.amountAdjusted,
                                shipmentAmount: _.isEmpty(shipment) ? '/' : shipment.vehiclePriceafterDiscounts,
                                state: _.isEmpty(shipment) ? enums.ShipmentCheckStatusEnum.CantFind
                                    : (Math.abs(shipment.vehiclePriceafterDiscounts - x.amountAdjusted) < 1 ? enums.ShipmentCheckStatusEnum.Normal
                                      : enums.ShipmentCheckStatusEnum.Unbalance),
                                finalAmount: _.isEmpty(shipment) ? '/'
                                    : (Math.abs(shipment.vehiclePriceafterDiscounts - x.amountAdjusted) < 1 ? x.amountAdjusted : null)
                            };
                        });
                    } else {
                        messagebox.warning('PleaseContactAdministrator');
                        return;
                    }
                }
                else {
                    messagebox.warning('PleaseContactAdministrator');
                    return;
                }

                var parentElem = angular.element($document[0].querySelector('#pre-issue-pop'));
                var modalInstance = $uibModal.open({
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    backdrop: 'static',
                    templateUrl: 'pre-issue-page.html',
                    controller: preIssueController,
                    windowClass: 'pre-issue-popup',
                    appendTo: parentElem,
                    scope: $scope
                });
            });
        };

        $scope.refreshIssueGDBD = function () {
            var reasonId = $scope.manualInputModel.manualInput.reasonList[0];
            var reason = _.where($scope.manualInputReasons, { id: reasonId });
            if (reason && reason[0].dictionaryKey == 'ManualInputReason2') {
                var idx = _.findIndex($scope.shipmentDataSource, { vin: $scope.selectedManualInput.vin });
                $scope.shipmentDataSource.splice(idx, 1);
            }
        }
        //--------------打印前确认--------------//end

        $scope.importShipmentList = function () {
            $state.go('outputInvoiceManage.importShipmentList');
        };

        //设置dataGrid分页
        $scope.pagingOptions = {
            pageIndex: 1,  //当前页码
            totalItems: 100,  //总数据
            totalPages: 10,//总页数
            maxSize: 10, //分页数字的限制。
            pageSize: constant.page.pageSizeArrary[1],  //每页多少条数据 
            pageSizeString: constant.page.pageSizeArrary[1].toString()
        };

        //分页里面的处理
        $scope.pagingService = {
            setPage: function (pageNo) {

                //$scope.currentPage = pageNo;
            },
            //分页的时候改变数字
            pageIndexChanging: function () {
                if ($scope.pagingOptions.pageIndex > $scope.pagingOptions.totalPages) {
                    $scope.pagingOptions.pageIndex = $scope.pagingOptions.totalPages;
                }

                $log.log('Page changed to: ' + $scope.pagingOptions.pageIndex);
                dataService.search();
            },

            //每页显示的数据下拉改变
            pageSizeSelectionChanged: function () {
                $scope.pagingOptions.pageSize = parseInt($scope.pagingOptions.pageSizeString);
                dataService.search();
            }
        };
        $scope.refreshTable = function () {
            dataService.search();
        };
        $scope.printGDInvoice = function () {

            // TODO: Save reasons for each VIN amount adjusting

            if (!$scope.shipmentDataSource || $scope.shipmentDataSource.length === 0) {
                messagebox.warning('SelectBdInvoiceCheck');
                return;
            }

            var selectedItems = _.chain($scope.selectedItems).filter(function (x) {
                return _.some($scope.shipmentDataSource, { vin: x.vin });
            }).map(function (x) {
                var rtn = angular.copy(x);
                var s = _.findWhere($scope.shipmentDataSource, { vin: rtn.vin });
                if (!_.isEmpty(s)) {
                    rtn.amountAdjusted = s.finalAmount;
                    if (!_.isEmpty(s.manualInput)) {
                        rtn.manualInput = s.manualInput;
                    }
                }

                return rtn;
            }).value();

            if (_.some(selectedItems, function (x) { return !_.isNumber(x.amountAdjusted); })) {
                messagebox.warning('FinalAmountEmpty');
                return;
            }

            if (selectedItems && selectedItems.length > 0) {

                for (var i = 0; i < selectedItems.length; i++) {
                    var row = selectedItems[i];

                    var tax = thisService.getTax(row);
                    var totalAmount = tax + row.amountAdjusted;

                    if (totalAmount > thisService.LimitAmount) {
                        var str = 'Issuing amount out of setting quota (' + thisService.LimitAmount.formatAmount() + ').';
                        messagebox.warning(str);
                        return;
                    }
                }

            }

            $state.go('outputInvoiceManage.gdInvoicePrint', { invoiceList: selectedItems });
        };


        var thisService = {
            LimitAmount: 0,

            getinvoiceQuota: function () {
                vatOutputInvoiceManageService.getInvoiceQuota().success(function (result) {
                    if (result.result) {
                        var str = result.data;
                        thisService.LimitAmount = parseInt(result.data);

                    }
                });
            },
            getTax: function (data) {
                var rateStr = data.vatRateorLevyRate.replace('%', '');

                var taxRateDecimal = parseInt(rateStr);
                data.taxRateDecimal = taxRateDecimal / 100;

                var tax = data.amountAdjusted * taxRateDecimal;

                tax = tax / 100;
                return tax;
            },
        };

        (function () {
            init();
            //获取折扣率,之后刷新列表
            vatOutputInvoiceManageService.getMarkupRatio().then(function (data) {
                if (data && data.data) {
                    if (data.data.currentRate) {
                        $scope.searchOptions.markupRatio = data.data.currentRate;
                    } else {
                        $scope.searchOptions.markupRatio = 0;
                    }

                    $scope.invoiceMarkupRatioEntity = data.data;
                    $scope.invoiceMarkupRatioEntity.rate = null;
                    $scope.invoiceMarkupRatioEntity.effectiveDate = null;
                } else {
                    $scope.searchOptions.markupRatio = 0;
                }
            })
            .then(vatOutputInvoiceManageService.getInvoiceQuota)
            .then(function (data) {
                var quotaValue;
                if (data && data.data && data.data.data) {
                    $scope.searchOptions.invoiceQuota = data.data.data;
                    //这里需要显示成account
                    quotaValue = data.data.data;
                } else {
                    $scope.searchOptions.invoiceQuota = quotaValue = 10000000;
                }
                $scope.invoiceQuotaEntity.maxValue = parseFloat(quotaValue).formatAmount(2);
            })
            .then(dataService.getBdList)
            .then(dataService.search)
            .then(function () {
                $scope.setInvoiceGridHeight();
            });

            vatOutputInvoiceManageService.getAmountCheckManualInputReason().then(function (data) {
                if (data && data.data) {
                    $scope.manualInputReasons = data.data;
                }
                else {
                    $scope.manualInputReasons = [];
                }
            });

            $scope.search = dataService.search;
        })();
    }
]);