invoiceModule.controller('invoiceManageRefundController', ['$scope', '$log', '$document', '$uibModal', 'SweetAlert', '$translate', '$q', '$interval', 'region', '$timeout', 'InvoiceManageService',
function ($scope, $log, $document, $uibModal, SweetAlert, $translate, $q, $interval, region, $timeout, InvoiceManageService) {
    'use strict';

    $scope.hasShowMoreSearchBox = false;
    $scope.selectedPlaceholder = 0;
    $scope.translated = {
        NoData: $translate.instant('NoDataText'),
        pleaseSelect: $translate.instant("ChoosePlaceholder"),
        pleaseInput: $translate.instant('InputPlaceholder'),
    };
    $scope.filterStatusIDList = [3, 4, 7];

    //消息弹框
    var messageBox = {
        getMsg: function (resultMsg, hasTranslated) {
            hasTranslated = hasTranslated || false;
            var msg = resultMsg;
            if (!hasTranslated) {
                msg = $translate.instant(resultMsg);
            }
            return msg;
        },

        success: function (resultMsg, hasTranslated) {
            var msg = this.getMsg(resultMsg, hasTranslated)
            SweetAlert.success(msg);
        },

        warning: function (resultMsg, hasTranslated) {
            var msg = this.getMsg(resultMsg, hasTranslated)
            SweetAlert.warning(msg);
        },

        //有确认和取消按钮
        confirm: function (title, text, customClass) {
            var deferred = $q.defer();
            SweetAlert.swal({
                title: title,
                text: text,
                html: true,
                type: "warning",
                customClass: customClass || '',
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                allowOutsideClick: false,
                confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: true,
                closeOnCancel: true
            },
              function (isConfirm) {
                  deferred.resolve(isConfirm);
              });

            return deferred.promise;
        },

        //没有取消按钮
        info: function (title, text, customClass) {
            var deferred = $q.defer();

            SweetAlert.swal({
                title: title,
                text: text,
                html: true,
                type: "warning",
                customClass: customClass || '',
                showCancelButton: false,
                confirmButtonColor: "#DD6B55",
                allowOutsideClick: false,
                confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: true,
                closeOnCancel: false
            },
              function (isConfirm) {
                  deferred.resolve(isConfirm);
              });

            return deferred.promise;
        },
    };

    //模态框
    var modalService = {
        modalInstance: null,
        open: function () {
            var parentElem = parentSelector ? angular.element($document[0].querySelector(parentSelector)) : undefined;

            var modalInstance = $uibModal.open({
                animation: true,
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                templateUrl: 'template.html', //模板
                windowClass: 'pupupModal', //弹框页面的css
                scope: $scope,
                appendTo: parentElem,
            });

            thisModalService.modalInstance = modalInstance;
        },
        close: function (result) {
            if (thisModalService.modalInstance) {
                thisModalService.modalInstance.close(result);
            }
        },
        cancel: function () {
            if (thisModalService.modalInstance) {
                thisModalService.modalInstance.dismiss('cancel');
            }
        }
    };


    //获取数据服务
    var getService = {
        //查询的数据源准备
        getInvoiceFilterBasicData: function () {
            var deferred = $q.defer();
            InvoiceManageService.getInvoiceFilterBasicData().success(function (data) {
                if (data) {
                    if (!$scope.searchFilterOptions) {
                        $scope.searchFilterOptions = {};
                    }
                    // console.log('data' + JSON.stringify(data));
                    var statusList = _.filter(data.invoiceStatusList, function (item) {
                        return $scope.filterStatusIDList.indexOf(item.id) > -1;
                    });
                    memoryService.translateDictionary(statusList);
                    memoryService.translateDictionary(data.invoiceRefundReasonList);
                    memoryService.translateDictionary(data.invoiceEntityList);
                    memoryService.translateDictionary(data.invoiceTypeList);
                    memoryService.translateDictionary(data.invoiceSourceList);
                    memoryService.translateDictionary(data.invoiceUploadTypeList);
                    //退票理由
                    $scope.refundReasons = data.invoiceRefundReasonList;

                    $scope.searchFilterOptions = {
                        invoiceStatusList: statusList,
                        invoiceEntityList: data.invoiceEntityList,
                        invoiceTypeList: data.invoiceTypeList,
                        invoiceSourceList: data.invoiceSourceList,
                        invoiceUploadList: data.invoiceUploadTypeList
                    };

                    deferred.resolve(data);
                }
            });
            return deferred.promise;
        },
        recognizeInvoice: function () {
            InvoiceManageService.invoiceManualRecognize($scope.selectedItem).success(function () {

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


    //内部处理
    var memoryService = {
        repaintInvoiceGrid: function () {
            $timeout(function () { 
                $scope.setInvoiceGridHeight();
            }, 100);
            //var grid = $('#invoiceRefundGrid').dxDataGrid('instance');
            //if ($scope.hasShowMoreSearchBox) {
            //    grid.option({ height: '300px' });
            //} else {
            //    grid.option({ height: '400px' });
            //}
            //grid.repaint();
        },
        translateDictionary: function (list) {
            _.each(list, function (item) {
                item.value = $translate.instant(item.value);

            });
        }
       
    };

    //button的事件
    $scope.eventService = {

        //发票识别
        manualRecognize: function () {
            //排除待匹配状态
            var notFitList = _.where($scope.selectedItem,  {
                status:7
            });
            if (notFitList && notFitList.length > 0) {
                var message = $translate.instant('NotMappingCondition').replace('@', notRecognizationList.length);
                SweetAlert.warning('', message);
            }else
            {
                getService.recognizeInvoice();
            }
        },
        //退票
        refundInovice: function () {
            $scope.showRefundModal = true;
        },
        refreshTable: function () {           
            var grid = $('#invoiceRefundGrid').dxDataGrid('instance');
            grid.clearSelection();
            grid.refresh();
            memoryService.repaintInvoiceGrid();
        }

    };

    //搜索框的处理
    $scope.searchboxService = {
        //隐藏或者展示搜索框
        showOrHideSearchBox: function () {
            $scope.hasShowMoreSearchBox = !$scope.hasShowMoreSearchBox;
            memoryService.repaintInvoiceGrid();
        },

        //根据条件搜索发票
        searchInvoice: function () {
            //set page index, avoid the pageIndex not 1
            $scope.paging.pagingOptions.pageIndex = 1;
            $scope.eventService.refreshTable();
        },
    };

    //分页的设置
    $scope.paging = {
        pagingOptions : {
            pageIndex: 1,  //当前页码
            totalItems: 100,  //总数据
            totalPages: 10,//总页数
            maxSize: 10, //分页数字的限制。
            pageSize: constant.page.pageSizeArrary[1],  //每页多少条数据 
            pageSizeString: constant.page.pageSizeArrary[1].toString(),
        },
    };
       
  
 
    var InitInvoiceGrid = function () {
        var refundDataSource = new DevExpress.data.CustomStore({
            load: function (loadOptions) {
                var pagingDto = { totalCount: null };
                pagingDto.pageSize = $scope.paging.pagingOptions.pageSize || 10;
                pagingDto.pageIndex = $scope.paging.pagingOptions.pageIndex;

                var invoiceParams = {
                    InvoiceQuery: $scope.searchEntity,
                    pagingDto: pagingDto,
                };
                var deferred = $q.defer();
                InvoiceManageService.getInputInvoiceRefundList(invoiceParams).success(function (result) {
                    if (result) {                        
                        // deferred.resolve({ data: result.list, totalCount: result.pageInfo.totalCount });
                        $scope.paging.pagingOptions.totalItems = result.pageInfo && result.pageInfo.totalCount;
                        deferred.resolve(result.list);

                    };

                })
                .error(function () {
                    deferred.reject("Data Loading Error");
                });
                return deferred.promise;

            },
            key: 'id'           
        });
        $scope.invoiceRefundGridOptions = {
            //height:"400px",
            dataSource: {
                store: refundDataSource
            },           
            selection: {
                mode: "multiple",
                //selectAllMode: "page",
                showCheckBoxesMode: "always"
            },
            loadPanel: {
                enabled: false
            },
            paging: {
                enabled: false                
            },
            hoverStateEnabled: true,
            ////dx paging
            //remoteOperations: {
            //    sorting: true,
            //    paging: true
            //},
            //paging: {
            //    enabled: true,
            //    pageSize: 10
            //},
            //pager: {
            //    showPageSizeSelector: true,
            //    allowedPageSizes: [5, 10, 20],
            //    showInfo: false
            //},
            allowColumnResizing: true,
            columnAutoWidth: true,
            showRowLines: true,
            showColumnLines: true,
            rowAlternationEnabled: false,
            showBorders: true,
            noDataText: $translate.instant('NoDataText'),
            onSelectionChanged: function (data) {
                $scope.selectedItem = data.selectedRowsData;
                $scope.selectedItemIDs = _.pluck(data.selectedRowsData, 'id');
                $scope.selectedPlaceholder = data.selectedRowsData.length;
                $scope.disabled = !$scope.selectedItemIDs.length;
            },
            //onRowPrepared: function (info) {
            //    if (info.rowType != 'header' && info.data.status !==4) {
            //        $(info.columns[0]).attr('disabled', true);
            //    }


            //},
            onCellPrepared: function (e) {
                if (e.rowType === "data" & e.column.command === 'select' && e.data.status === constant.inputInvoice.statusType.InvoiceHasRefund.id) {
                    e.cellElement.find('.dx-select-checkbox').hide();
                    e.cellElement.off();
                }
            },
            columns: [
                   {
                       dataField: 'invoiceCode', caption: $translate.instant('InvoiceFPDM'),
                   },
                    { dataField: 'invoiceNumber', caption: $translate.instant('InvoiceFPHM') },
                    { dataField: 'buyerName', caption: $translate.instant('BuyerName') },
                    { dataField: 'buyerTaxNumber', caption: $translate.instant('BuyerTaxNumber') },
                    { dataField: 'sellerName', caption: $translate.instant('SellerName') },
                    { dataField: 'sellerTaxNumber', caption: $translate.instant('SellerTaxNumber') },
                    { dataField: 'totalPriceLowerCase ', caption: $translate.instant('FaceTaxAmount') }, //税额合计小写
                    { dataField: 'taxAmount', caption: $translate.instant('InvoiceSE') },  //税额
                    { dataField: 'invoiceDate', caption: $translate.instant('InvoiceDate') }, //开票日期
                    {
                        dataField: 'invoiceEntityType', caption: $translate.instant('InvoiceEntity'),
                        calculateDisplayValue: function (data) {
                            return $translate.instant(data.invoiceEntityTypeString);
                        }
                    },
                    {
                        dataField: 'invoiceType', caption: $translate.instant('InvoiceFPLX'),
                        calculateDisplayValue: function (data) {
                            return $translate.instant(data.invoiceTypeString);
                        }

                    },
                    {
                        dataField: 'UploadType', caption: $translate.instant('InvoiceModeWay'),
                        calculateDisplayValue: function (data) {
                            return $translate.instant(data.uploadTypeString);
                        }

                    },
                    { dataField: 'uploadDate', caption: $translate.instant('UploadDate') },
                    {
                        dataField: 'invoiceSourceType', caption: $translate.instant('InvoiceSource'),
                        calculateDisplayValue: function (data) {
                            return $translate.instant(data.invoiceSourceTypeString);
                        }
                    }, //发票来源
                    {
                        dataField: 'status', caption: $translate.instant('InvoiceStatus'),
                        calculateDisplayValue: function (data) {
                            return $translate.instant(data.statusString);
                        }
                    }
            ]

        };
    };

    var initDatePicker = function () {
        $('#invoiceDatePicker,#uploadDatepicker').datepicker({
            language: region
        });
    };

    //搜索框初始化
    var initSearchBoxContorls = function () {

        $scope.searchEntity = {};

        var isShowClearButton = true;
        var dxHeight = "30px";
        $scope.searchEntityOptions = {
            //1. 购买方
            selectboxBuyerNameOptions: {
                bindingOptions: {
                    value: 'searchEntity.buyerName',
                },
                placeholder: $scope.pleaseSelect,
                showClearButton: isShowClearButton,
                noDataText: $scope.translated.NoData,
                height: dxHeight
            },
            //2. 销售方
            txtSellerNameBoxOptions: {
                bindingOptions: {
                    value: 'searchEntity.sellerName',
                },
                placeholder: $scope.pleaseInput,
                showClearButton: isShowClearButton,
                height: dxHeight
                //onValueChanged: function (data) {
                //    $scope.searchEntity.sellerName = data.value;
                //}
            },
            //3. 发票号码
            txtInvoiceNumberOptions: {
                bindingOptions: {
                    value: 'searchEntity.invoiceNumber',
                },
                placeholder: $scope.pleaseInput,
                showClearButton: isShowClearButton,
                height: dxHeight
            },
            //4.发票状态,已经上传,已补录。。
            selectstatusOptions: {

                displayExpr: "value",
                valueExpr: "id",
                bindingOptions: {
                    value: 'searchEntity.status',
                    dataSource: 'searchFilterOptions.invoiceStatusList'
                },
                placeholder: $scope.pleaseSelect,
                showClearButton: isShowClearButton,
                noDataText: $scope.translated.NoData,
                height: dxHeight
            },
            //5.开票日期,目前是boostrap控件
            //invoiceDateFrom,invoiceDateTo
            //6.发票来源
            selectinvoiceSourceTypeOptions: {
                displayExpr: "value",
                valueExpr: "id",
                bindingOptions: {
                    value: 'searchEntity.invoiceSourceType',
                    dataSource: 'searchFilterOptions.invoiceSourceList'
                },
                placeholder: $scope.pleaseSelect,
                showClearButton: isShowClearButton,
                noDataText: $scope.translated.NoData,
                height: dxHeight
            },
            //7.发票类型,普票和专票
            selectInvoiceTypeOptions: {
                displayExpr: "value",
                valueExpr: "id",
                bindingOptions: {
                    value: 'searchEntity.invoiceType',
                    dataSource: 'searchFilterOptions.invoiceTypeList'
                },
                placeholder: $scope.pleaseSelect,
                showClearButton: isShowClearButton,
                noDataText: $scope.translated.NoData,
                height: dxHeight
            },
            //8. UploadDate,   upload 日期,目前是boostrap控件, uploadDateFrom,uploadDateTo
            //9. amount
            txtAmountOptions: {
                bindingOptions: {
                    value: 'searchEntity.amount',
                },
                placeholder: $scope.pleaseInput,
                showClearButton: isShowClearButton,
                noDataText: $scope.translated.NoData,
                height: dxHeight
            },
            //10/发票实体,纸票或者电子票
            selectInvoiceEntityTypeOptions: {
                displayExpr:  'value',

                valueExpr: "id",
                bindingOptions: {
                    value: 'searchEntity.invoiceEntityType',
                    dataSource: 'searchFilterOptions.invoiceEntityList'
                },
                placeholder: $scope.pleaseSelect,
                showClearButton: isShowClearButton,
                noDataText: $scope.translated.NoData,
                height: dxHeight
            },
            selectInvoiceUploadOptions: {
                displayExpr: "value",
                valueExpr: "id",
                bindingOptions: {
                    value: 'searchEntity.invoiceUploadType',
                    dataSource: 'searchFilterOptions.invoiceUploadList'
                },
                placeholder: $scope.pleaseSelect,
                showClearButton: isShowClearButton,
                noDataText: $scope.translated.NoData,
                height: dxHeight
            },
            faceTaxFromOptions: {
                bindingOptions: {
                    value: 'searchEntity.AmountFrom'
                },
                height: dxHeight
            },
            faceTaxToOptions: {
                bindingOptions: {
                    value: 'searchEntity.AmountTo'
                },
                height: dxHeight
            }

        };
    };

    //初始化控件
    var initControls = function () {
        initDatePicker();
        initSearchBoxContorls();
        InitInvoiceGrid();
    };

    //初始化数据
    var initData = function () {
        $scope.searchFilterOptions = {};
        getService.getInvoiceFilterBasicData();

        //搜索框的处理
        $scope.hasShowMoreSearchBox =true;
        $scope.searchboxService.showOrHideSearchBox();
    };

    (function initialize() {
        $log.debug('invoiceManageRefundController.ctor()...');
        $scope.disabled = true;
        $scope.showRefundModal = false;
        initControls();
        initData();

    })();
}

]);