vatModule.controller('specialVatInvoiceController', ['$log', '$timeout', '$scope', '$translate', 'vatOutputInvoiceManageService',
    'SweetAlert', 'orgService', 'enums', 'modalAdapterService',
    function ($log, $timeout, $scope, $translate, vatOutputInvoiceManageService, SweetAlert,
        orgService, enums, modalAdapterService) {
        //分页的设置
        var dateFormat = 'yyyy-MM-dd';
        $scope.pleaseSelect = $translate.instant("ChoosePlaceholder");
        $scope.pleaseInput = $translate.instant('InputPlaceholder');
        $scope.pagingOptions = {
            pageIndex: 1,  //当前页码
            totalItems: 0,  //总数据
            pageSize: constant.page.pageSizeArrary[1],  //每页多少条数据 
        };
        $scope.specialSearchEntity = {
            invoiceNumberVaule: null,
            VRLValue: null,
            issuedPeriodFromValue: null,
            issuedPeriodToValue: null,
            entityCodeValue: null,
            statusValue: [],
            revertStatusList:[]
        };
        $scope.specialInvoiceVariables = {
            selectedTableRows: [],
            selectedTotalAmount: 0.00,
            pageName: $translate.instant('IssuedInvoiceSpecial'),
            selectedInvoice:null
           
        };
        $scope.specialInvoice = {
            invoiceNumberOptions: {
                bindingOptions: {
                    'value': 'specialSearchEntity.invoiceNumberVaule'
                },
                showClearButton: true,
                placeholder: $scope.pleaseInput
            },
            VRLOptions: {
                bindingOptions: {
                    'dataSource': 'allDBVRL',
                    'value': 'specialSearchEntity.VRLValue'
                },
                showClearButton: true,
                placeholder: $scope.pleaseSelect
            },
            issuedPeriodFromOptions: {
                type: "date",
                dateSerializationFormat:dateFormat,
                displayFormat: dateFormat,
                bindingOptions: {
                    'value': 'specialSearchEntity.issuedPeriodFromValue'
                },
                width: '100%',
                showClearButton: true,
                placeholder: $scope.pleaseSelect
            },
            issuedPeriodToOptions: {
                type: "date",
                dateSerializationFormat: dateFormat,
                displayFormat: dateFormat,
                bindingOptions: {
                    'value': 'specialSearchEntity.issuedPeriodToValue'
                },
                width: '100%',
                showClearButton: true,
                placeholder: $scope.pleaseSelect
            },
            entityOptions:{
                bindingOptions: {
                    'value': 'specialSearchEntity.entityCodeValue',
                    'dataSource':'entitySource'
                },
                showClearButton: true,
                displayExpr: 'name',
                valueExpr: 'id',
                placeholder: $scope.pleaseSelect
            },
            statusOptions:{
                bindingOptions: {
                    'value': 'specialSearchEntity.statusValue',
                    'dataSource': 'specialStatus'
                },
                showClearButton: true,
                showDropButton: true,
                multiline: false,
                showSelectionControls: true,
                applyValueMode: "useButtons",
                displayExpr: 'name',
                valueExpr: 'id',
                //fieldTemplate: function (selectedItems, fieldElement) {                   
                //    selectedItems = Array.isArray(selectedItems) ? selectedItems : [selectedItems];
                   
                //    var selCount = selectedItems.length,
                //         $textBox = $('<div>', { class: "input-field" }).dxTextBox({});
                   
                //    var $field = $("<div>", { class: "tag-container" }).text(
                //        selCount > 1 ? selCount + " selected" : selCount===1?selectedItems[0].name:null
                //    );

                //    return fieldElement.append($field).append($textBox);
                //},              
                placeholder: $scope.pleaseSelect
            },
            specialGridContainer: {
                //height:'260px',
                bindingOptions: {
                    dataSource: 'specialInvoiceList',
                    'height': 'height'
                },
                loadPanel: {
                    enabled: false,
                },
                noDataText:$translate.instant('NoDataText'),
                columnAutoWidth:true,
                showRowLines: true,
                showBorders: true,
                columnChooser: {
                    enabled: true
                },
                paging: {
                    enabled: false
                },
                selection:{
                    mode: 'multiple',
                    showCheckBoxesMode: 'always'
                },
                onSelectionChanged: function (e) {
                    $scope.specialInvoiceVariables.selectedTotalAmount = 0.00;
                    $scope.specialInvoiceVariables.selectedTableRows = e.selectedRowsData;
                    _.each(e.selectedRowsData, function (item) {
                        $scope.specialInvoiceVariables.selectedTotalAmount += item.totalAmount;
                    });
                },
                headerFilter:{
                    visible: false,
                    texts: {
                        cancel: $translate.instant('ENCancel'),
                        emptyValue: $translate.instant('Blank'),
                        ok:$translate.instant('Confirm')
                    }
                },
                columns: [
                    { dataField: 'vrl', caption: $translate.instant('VRL'),allowHeaderFiltering:false,visible:false },
                    { dataField: 'buyerOrganizationCode', caption: $translate.instant('Entity'), allowHeaderFiltering: false },
                    { dataField: 'gdInvoiceNumber', caption: $translate.instant('InvoiceNo'), allowHeaderFiltering: false },
                    { dataField: 'gdInvoiceCode', caption: $translate.instant('InvoiceCode'), allowHeaderFiltering: false },
                    { dataField: 'buyerOrganizationName', caption: $translate.instant('BuyerName'), allowHeaderFiltering: false },
                    { dataField: 'buyerOrganizationTaxID', caption: $translate.instant('BuyerTaxID'), allowHeaderFiltering: false },
                    {
                        dataField: 'totalAmount', caption: $translate.instant('Amount'),
                        format: { type: 'fixedPoint', precision: 2 }, allowHeaderFiltering: false
                    },
                     {
                         dataField: 'totalTaxAmount', caption: $translate.instant('TaxAmount'),
                         format: { type: 'fixedPoint', precision: 2 }, allowHeaderFiltering: false
                     },
                    {
                        dataField: 'gdIssuedDate', caption: $translate.instant('IssuedDate'),
                        dataType: 'date', format: dateFormat, allowHeaderFiltering: false
                    },
                    {
                        dataField: 'status', caption: $translate.instant('Status'),
                        calculateDisplayValue: function (rowData) {
                            return $translate.instant($scope.specialSearchEntity.revertStatusList[rowData.status]);
                        }
                        //headerFilter: {
                        //    dataSource: {
                        //        load: function () {
                        //           return _.map(enums.GDInvoiceStatusEnum, function (item, key) {                                       
                        //               return {
                        //                   text: $translate.instant(key),
                        //                   value: ["status", "=", item]
                        //               };
                        //            });
                        //        }
                        //    }
                        //}
                    },
                    {
                        caption: $translate.instant('Details'),
                        cellTemplate: 'detailTemplate', allowHeaderFiltering: false
                    }

                ]
            }
        };


        $scope.eventService = {
            checkBeforCancel: function () {
                var list = $scope.specialInvoiceVariables.selectedTableRows;
                //过月的不能cancel
                var currentMonth = new Date().getMonth();//1-12
                var notValidMonthCount = 0;
                var notValidStatus = true;
                var isRed = false;
                _.each(list, function (item) {
                    var m = new Date(item.gdIssuedDate).getMonth();
                    notValidMonthCount = m === currentMonth ? notValidMonthCount : ++notValidMonthCount;
                    if (item.status !== enums.GDInvoiceStatusEnum.issued) {
                        notValidStatus = false;
                    } 
                    if (item.isRedInvoice) {
                        //红票不能cancel
                        isRed = true;
                    }
                    
                });
                var result = {
                    pass: notValidMonthCount === 0 && notValidStatus && !isRed,
                    notMatchMonth: notValidMonthCount,
                    notValidStatus: notValidStatus,
                    isRedInvoice: isRed
                }
                return result;
            },
            cancelInvoiceCore: function () {
                var dto = {
                    items: $scope.specialInvoiceVariables.selectedTableRows,
                    reprint: $scope.isReprint,
                    userName: null,
                    userID: null
                }
                //need call baiwang jie kou
                vatOutputInvoiceManageService.cancelGDInvoice(dto).success(function (response) {
                    if (response.result) {
                        //_.each($scope.specialInvoiceVariables.selectedTableRows, function (item) {
                        //    item.status = enums.GDInvoiceStatusEnum.cancelled;
                        //});
                        modalAdapterService.close(constant.OutputInvoiceCancalDialog, 'special-vat-page');
                        $scope.eventService.refreshInvoiceDataGrid();
                    }
                }).error(function () {
                    SweetAlert.error('', $translate.instant('CommonFail'));
                });
            },
            cancelFapiao: function (reprint) {
                if (!$scope.specialInvoiceVariables.selectedTableRows || $scope.specialInvoiceVariables.selectedTableRows.length < 1) {
                    SweetAlert.warning($translate.instant('SelectBdInvoiceCheck'));
                    return;
                }
                var result=$scope.eventService.checkBeforCancel();
                if (result.pass) {
                    $scope.title = reprint ? $translate.instant("CancelReprintInvoiceGDTitle") : $translate.instant("CancelInvoiceGDTitle")
                   $scope.isReprint = reprint ? reprint : false;
                   modalAdapterService.open(constant.OutputInvoiceCancalDialog, 'special-vat-page');
                }else
                {
                    var message =result.notMatchMonth===0?"": $translate.instant('HasNotMatchMonth') + result.notMatchMonth + $translate.instant('Separator');
                    message = result.notValidStatus ? message : message + $translate.instant('HasNotMatchStatus');
                    message = result.isRedInvoice ? message + $translate.instant('RedInvoiceWarrning') : message;
                    SweetAlert.warning('', message);
                }
               
            },
            cancelandPrintFapiao:function(){
                $scope.eventService.cancelFapiao(true);
            },
            getQueryBasicData: function () {
                $scope.specialStatus = _.map(enums.GDInvoiceStatusEnum, function (item, key) {
                    return { id: item, name: $translate.instant(key) };
                });
                orgService.getBdList().success(function (res) {
                    $scope.entitySource=  _.map(res,function(item){
                        return { id: item.code, name: item.code + item.name };
                    });
                    $scope.allDBVRL = _.filter(_.uniq(_.pluck(res, 'vehicleroutinglocation')),
                        function (item) { return item !== null });
                });
                
            },
            refreshInvoiceDataGrid: function () {
                var dataDto = {
                    parameters:$scope.specialSearchEntity,
                        pagingInfo: $scope.pagingOptions
                }
                vatOutputInvoiceManageService.getSpecailGBInvoiceList(dataDto).success(function (response) {
                    $scope.specialInvoiceList = response.list;
                    $scope.pagingOptions.totalItems = response.pageInfo.totalCount;
                }).error(function () {
                    SweetAlert.error('', $translate.instant('CommonFail'));
                });
     
            },
            showDetail: function (rowData) {
                $scope.specialInvoiceVariables.selectedInvoice = rowData;
                $scope.$broadcast("openGDDetailDialog");
            },
            //隐藏或者展示搜索框
            showOrHideSearchBox: function () {
                $scope.hasShowMoreSearchBox = !$scope.hasShowMoreSearchBox;
                // $scope.eventService.refreshInvoiceDataGrid();
                $timeout(function () {
                    $scope.setInvoiceGridHeight();
                }, 500);

            }
        };

      
        (function () {
            $scope.specialSearchEntity.revertStatusList = _.invert(enums.GDInvoiceStatusEnum);
            $scope.eventService.getQueryBasicData();
            $scope.eventService.refreshInvoiceDataGrid();
            $scope.hasShowMoreSearchBox = false;
            //设置表格高度
            $timeout(function () {
                $scope.setInvoiceGridHeight();
            }, 500);
        })();
    }
])