invoiceModule.controller('outputInvoiceEditController', ['$scope', '$log', '$document', '$uibModal', 'messagebox',
    '$translate', '$q', 'apiInterceptor', '$interval', 'region', '$timeout', '$location', 'InvoiceManageService',
    'vatOutputInvoiceManageService', 'userService', '$state', 'SweetAlert', 'enums',
    function($scope, $log, $document, $uibModal, messagebox, $translate, $q, apiInterceptor, $interval, region,
        $timeout, $location, InvoiceManageService, vatOutputInvoiceManageService, userService, $state, SweetAlert, enums) {
        'use strict';

        var parentSelector = '.output-invoice-edit-wrapper';

        $scope.pleaseSelect = $translate.instant("ChoosePlaceholder");
        $scope.pleaseInput = $translate.instant('InputPlaceholder');


        //分页的设置
        $scope.pagingOptions = {
            pageIndex: 1, //当前页码
            totalItems: 100, //总数据
            totalPages: 10, //总页数
            maxSize: 10, //分页数字的限制。
            pageSize: constant.page.pageSizeArrary[1], //每页多少条数据 
            pageSizeString: constant.page.pageSizeArrary[1] + '',
            firstPage: $translate.instant('PagingFirstPage'),
            previousPage: $translate.instant('PagingPreviousPage'),
            nextPage: $translate.instant('PagingNextPage'),
            lastPage: $translate.instant('PagingLastPage'),
        };

        $scope.searchEntity = {};
        $scope.datagrid = {};
        $scope.hasShowMoreSearchBox = false;


        var uploadIndexPageUrl = "/invoiceManagement/main/uploadIndex";


        $scope.translated = {
            NoData: $translate.instant('NoDataText'),
            pleaseSelect: $translate.instant("ChoosePlaceholder"),
            pleaseInput: $translate.instant('InputPlaceholder'),
        };

        //模态框
        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));
                        $scope.searchFilterOptions = {
                            invoiceStatusList: memoryService.translateEnumValue(data.invoiceStatusList),
                            invoiceEntityList: memoryService.translateEnumValue(data.invoiceEntityList),
                            invoiceTypeList: memoryService.translateEnumValue(data.invoiceTypeList),
                            invoiceSourceList: memoryService.translateEnumValue(data.invoiceSourceList),
                            invoiceUploadTypeList: memoryService.translateEnumValue(data.invoiceUploadTypeList),
                        };

                        deferred.resolve(data);
                    }
                });
                return deferred.promise;
            },

            //筛选invoice list
            getInputInvoiceList: function() {
                var deferred = $q.defer();

                var invoiceParams = {
                    InvoiceQuery: $scope.searchEntity,
                    pagingDto: $scope.pagingOptions,
                };

                InvoiceManageService.getInputInvoiceList(invoiceParams).success(function(data) {
                    if (data) {
                        $scope.pagingOptions.totalItems = data.pageInfo && data.pageInfo.totalCount;
                        if (data && data.list) {
                            data.list.forEach(function(item) {
                                item.statusString = $translate.instant(item.statusString);
                                item.invoiceEntityTypeString = $translate.instant(item.invoiceEntityTypeString);
                                item.invoiceSourceTypeString = $translate.instant(item.invoiceSourceTypeString);
                                item.invoiceTypeString = $translate.instant(item.invoiceTypeString);
                                item.uploadTypeString = $translate.instant(item.uploadTypeString);
                                item.uploadDate = moment(item.uploadDate).format(constant.date.dateFormatUppercase);
                                item.invoiceDate = moment(item.invoiceDate).format(constant.date.dateFormatUppercase);
                            });
                        }
                        $scope.invoiceGridDataSource = data.list;
                        deferred.resolve(data);
                    };
                });
                return deferred.promise;
            }

        };

        //添加数据服务
        var addService = {

        };

        //更新数据服务
        var updateService = {
            //发票识别,手动识别
            invoiceManualRecognize: function(invoiceIDList) {
                var deferred = $q.defer();
                InvoiceManageService.invoiceManualRecognize(invoiceIDList).success(function(data) {
                    if (data) {
                        deferred.resolve(data);
                    }
                });
                return deferred.promise;
            },
            //发票验真
            invoiceExamination: function(invoiceIDList) {
                var deferred = $q.defer();
                InvoiceManageService.invoiceExamination(invoiceIDList).success(function(data) {
                    if (data) {
                        deferred.resolve(data);
                    }
                });
                return deferred.promise;
            },
            //变更发票状态
            updateInvoiceStatus: function(invoiceIDList, invoiceStatusID) {
                var deferred = $q.defer();
                InvoiceManageService.updateInvoiceStatus(invoiceIDList, invoiceStatusID).success(function(data) {
                    if (data) {
                        deferred.resolve(data);
                    }
                });
                return deferred.promise;
            },
        };

        //删除数据服务
        var deleteService = {

        };

        //内部处理
        var memoryService = {
            repaintInvoiceGrid: function() {
                $scope.setInvoiceGridHeight();
            },
            //翻译查询的数据源
            translateEnumValue: function(data) {
                if (!data || data.length == 0) return null;

                data.forEach(function(item) {
                    item.value = $translate.instant(item.value);
                });
                return data;
            },
            //分页下拉
            populatePagingSelection: function() {
                var pagingSelection = [];
                var pageArray = constant.page.pageSizeArrary;
                for (var i = 0; i < pageArray.length; i++) {
                    var selection = { id: pageArray[i], value: pageArray[i] };
                    pagingSelection.push(selection);
                }
                $scope.pagingOptions.pagingSelection = pagingSelection;
            },
        };

        //button的事件
        $scope.eventService = {
            //上传
            gotoUploadIndexPage: function() {
                $location.path(uploadIndexPageUrl);
            },

            checkHasItemSelected: function() {
                if (!$scope.datagrid.selectedItems || $scope.datagrid.selectedItems.length == 0) {
                    messagebox.warning("请至少选择一条记录", true);
                    return false;
                }
                return true;
            },

            //发票识别,已上传、已补录:识别
            invoiceManualRecognize: function() {

                if (!$scope.eventService.checkHasItemSelected()) {
                    return false;
                }

                //只有已上传、已补录,可以做识别
                var filterResult = _.filter($scope.datagrid.selectedItems, function(item) {
                    return item.status !== constant.inputInvoice.statusType.InvoiceHasUpload.id &&
                        item.status !== constant.inputInvoice.statusType.InvoiceHasAddRecord.id
                });

                if (filterResult.length > 0) {
                    messagebox.success("只有已上传或者已补录的发票可以做发票识别", true);
                    return;
                }
                var selectedInvoiceIDList = _.pluck($scope.datagrid.selectedItems, 'id');

                updateService.invoiceManualRecognize(selectedInvoiceIDList).then(function(data) {
                    if (data) {
                        messagebox.success("发票识别成功", true);
                    }
                });
            },
            //发票验真,只有识别成功的才可以做验真。
            invoiceExamination: function() {
                if (!$scope.eventService.checkHasItemSelected()) {
                    return false;
                }
                //只有识别成功的才可以做验真。
                var filterResult = _.filter($scope.datagrid.selectedItems, function(item) {
                    return item.status !== constant.inputInvoice.statusType.InvoiceIdentifySuccess.id;
                });

                if (filterResult.length > 0) {
                    messagebox.success("只有识别成功的发票可以做验真", true);
                    return;
                }
                var selectedInvoiceIDList = _.pluck($scope.datagrid.selectedItems, 'id');

                updateService.invoiceExamination(selectedInvoiceIDList).then(function(data) {
                    if (data) {
                        messagebox.success("发票验真成功", true);
                    }
                });
            },
            //退票
            refundInovice: function() {
                if (!$scope.eventService.checkHasItemSelected()) {
                    return false;
                }
                var selectedInvoiceIDList = _.pluck($scope.datagrid.selectedItems, 'id');
                var status = stant.inputInvoice.statusType.InvoiceHasRefund.id;
                messagebox.confirm("确认要把选中的发票进行退票处理吗?", '').then(function(isConfirm) {
                    if (isConfirm) {
                        updateService.updateInvoiceStatus(selectedInvoiceIDList, status).then(function(data) {
                            if (data) {
                                messagebox.success("退票成功", true);
                            }
                        });
                    }
                });

            },
            //发票认证
            verifyInvoice: function() {
                //上传excel
            },
            //失效
            expireInvoice: function() {
                if (!$scope.eventService.checkHasItemSelected()) {
                    return false;
                }
                var selectedInvoiceIDList = _.pluck($scope.datagrid.selectedItems, 'id');
                var status = stant.inputInvoice.statusType.InvoiceHasExpired.id;
                messagebox.confirm("确认要把选中的发票进行失效处理吗?", '').then(function(isConfirm) {
                    if (isConfirm) {
                        updateService.updateInvoiceStatus(selectedInvoiceIDList, status).then(function(data) {
                            if (data) {
                                messagebox.success("处理成功", true);
                            }
                        });
                    }
                });
            },
            //显示Mapping 界面
            showMapping: function() {
                $scope.isOpenMapping = true;
            }
        }

        //datagrid内部的事件
        $scope.dataGridService = {
            //发票识别
            manualRecognizInvoice: function(data) {

                var selectedInvoiceIDList = [];
                if (data) {
                    selectedInvoiceIDList.push(data.id);
                }
                if (selectedInvoiceIDList.length > 0) {
                    updateService.invoiceManualRecognize(selectedInvoiceIDList).then(function(data) {
                        if (data) {
                            messagebox.success("发票识别成功", true);
                        }
                    });
                }
            },
            //发票验真
            invoiceExamination: function(data) {
                var selectedInvoiceIDList = [];
                if (data) {
                    selectedInvoiceIDList.push(data.id);
                }
                if (selectedInvoiceIDList.length > 0) {
                    updateService.invoiceExamination(selectedInvoiceIDList).then(function(data) {
                        if (data) {
                            messagebox.success("发票验真成功", true);
                        }
                    });
                }
            },
            //手动验真
            manualVerifyInvoice: function(data) {},
            //退票
            refundInovice: function() {
                var selectedInvoiceIDList = [];
                if (data) {
                    selectedInvoiceIDList.push(data.id);
                }
                if (selectedInvoiceIDList.length > 0) {
                    var status = stant.inputInvoice.statusType.InvoiceHasRefund.id;
                    messagebox.confirm("确认要把选中的发票进行退票处理吗?", '').then(function(isConfirm) {
                        if (isConfirm) {
                            updateService.updateInvoiceStatus(selectedInvoiceIDList, status).then(function(data) {
                                if (data) {
                                    messagebox.success("退票成功", true);
                                }
                            });
                        }
                    });
                }
            },
            //票账匹配
            matchTicketAccount: function(data) {

            },
            //手动验真
            invoiceManualExamination: function(data) {

            },
        }

        //搜索框的处理
        $scope.buttonService = {
            //手工拉取数据
            manualUpdateSFData: function() {
                var deferred = $q.defer();
                vatOutputInvoiceManageService.ManualUpdateSFData().success(function(data) {
                    deferred.resolve({ data: data });
                }).error(function() {
                    deferred.reject("Data Loading Error");
                });
                return deferred.promise;
            }
        }

        //分页里面的处理
        $scope.pagingSercice = {
            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);
                mainModule.loadInvoiceData();
            },

            //每页显示的数据下拉改变
            pageSizeSelectionChanged: function() {
                $scope.pagingOptions.pageSize = parseInt($scope.pagingOptions.pageSizeString);
                // getService.getInputInvoiceList();
                mainModule.loadInvoiceData();
            },
        };


        var loadInvoiceGridData = function() {


            getService.getInputInvoiceList($scope.searchEntity);

            $timeout(function() {
                memoryService.repaintInvoiceGrid();
            }, 50);

        }

        //初始化invoice datagrid 树
        var InitInvoiceGrid = function() {
            $scope.invoiceGridOptions = {
                bindingOptions: {
                    dataSource: 'invoiceGridDataSource'
                },
                // keyExpr: "ID",
                selection: {
                    mode: "multiple",
                    showCheckBoxesMode: 'always'
                },
                paging: {
                    enabled: false,
                },
                columnFixing: {
                    enabled: true
                },
                allowColumnResizing: true,
                columnAutoWidth: true,
                showRowLines: true,
                showColumnLines: true,
                rowAlternationEnabled: true,
                hoverStateEnabled: true,
                showBorders: true,
                noDataText: $translate.instant('NoDataText'),
                selectAllText: $translate.instant('SelectAll'),
                onContentReady: function(e) {
                    $scope.invoiceGridInstance = e.component;
                },
                onCellPrepared: function(e) {
                    //已退票,已失效不显示checkbox
                    if (e.rowType === "data" & e.column.command === 'select' &&
                        (e.data.status === constant.inputInvoice.statusType.InvoiceHasRefund.id ||
                            e.data.status === constant.inputInvoice.statusType.InvoiceHasExpired.id)) {
                        e.cellElement.find('.dx-select-checkbox').hide();
                        //e.cellElement.find('.dx-select-checkbox').addClass('dx-state-disabled');
                        e.cellElement.off();
                    }
                },
                onSelectionChanged: function(data) {
                    $scope.datagrid.selectedItems = data.selectedRowsData;
                    //$scope.selectedItemIDs = _.pluck(data.selectedRowsData, 'id');
                    //$scope.selectedPlaceholder = data.selectedRowsData.length;
                    //$scope.disabled = !$scope.selectedItemIDs.length;
                },
                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: 'amount', caption: $translate.instant('FaceTaxAmount') }, //税额合计小写
                    { dataField: 'taxAmount', caption: $translate.instant('InvoiceSE') }, //税额
                    { dataField: 'invoiceDate', caption: $translate.instant('InvoiceDate') }, //开票日期
                    { dataField: 'invoiceEntityTypeString', caption: $translate.instant('InvoiceEntity') },
                    { dataField: 'invoiceTypeString', caption: $translate.instant('InvoiceFPLX') },
                    { dataField: 'uploadDate', caption: $translate.instant('UploadDate') },
                    { dataField: 'invoiceSourceTypeString', caption: $translate.instant('InvoiceSource') }, //发票来源
                    { dataField: 'uploadTypeString', caption: $translate.instant('UploadType') },
                    { dataField: 'statusString', caption: $translate.instant('InvoiceStatus') },
                    {
                        dataField: 'id',
                        caption: $translate.instant('Operation'),
                        cellTemplate: function(container, options) {
                            try {
                                var data = options.data;
                                var invoiceStatusType = constant.inputInvoice.statusType;
                                //已上传、已补录:识别
                                if (data.status == invoiceStatusType.InvoiceHasUpload.id || data.status == invoiceStatusType.InvoiceHasAddRecord.id) {
                                    $("<span class='span-btn' />")
                                        .text('识别')
                                        .on('click', function() {
                                            $scope.dataGridService.manualRecognizInvoice(data);
                                        })
                                        .appendTo(container);
                                }
                                //识别成功:验真
                                else if (data.status == invoiceStatusType.InvoiceIdentifySuccess.id) {
                                    $("<span class='span-btn' />")
                                        .text('验真')
                                        .on('click', function() {
                                            $scope.dataGridService.invoiceExamination(data);
                                        })
                                        .appendTo(container);
                                }
                                //无法识别:退票
                                else if (data.status == invoiceStatusType.InvoiceUnrecognize.id) {
                                    $("<span class='span-btn' />")
                                        .text('退票')
                                        .on('click', function() {
                                            $scope.dataGridService.refundInovice(data);
                                        })
                                        .appendTo(container);
                                }
                                //验真失败:手动验真
                                else if (data.status == invoiceStatusType.InvoiceVerifyFailure.id) {
                                    $("<span class='span-btn' />")
                                        .text('手动验真')
                                        .on('click', function() {
                                            $scope.dataGridService.invoiceManualExamination(data);
                                        })
                                        .appendTo(container);
                                }
                                //待匹配:票账匹配,退票 
                                else if (data.status == invoiceStatusType.InvoicePendingMatch.id) {
                                    $("<span class='span-btn' />")
                                        .text('票账匹配')
                                        .on('click', function() {
                                            $scope.dataGridService.matchTicketAccount(data);
                                        })
                                        .appendTo(container);

                                    $("<span class='span-btn' />")
                                        .text('退票')
                                        .on('click', function() {
                                            $scope.dataGridService.refundInovice(data);
                                        })
                                        .appendTo(container);
                                }
                            } catch (e) {
                                $log.error(e);
                            }
                        }
                    },
                ],

                masterDetail: {
                    enabled: true,
                    template: "detail"
                },
                detailGridOptions: function(invoiceID) {
                    return {
                        dataSource: new DevExpress.data.DataSource({
                            load: function(loadOptions) {
                                var deferred = $q.defer();
                                return InvoiceManageService.getInputInvoiceItemList(invoiceID).success(function(response) {
                                    deferred.resolve({ data: response, totalCount: response.length });
                                }).error(function() {
                                    deferred.reject("Data Loading Error");
                                });
                                return deferred.promise;
                            }
                        }),
                        noDataText: $translate.instant('NoDataText'),
                        columnAutoWidth: true,
                        //showBorders: true,
                        allowColumnResizing: true,
                        columns: [{
                                dataField: 'productionName',
                                caption: $translate.instant('ProductAndService')
                            },
                            {
                                dataField: 'specification',
                                caption: $translate.instant('Specifications')
                            },
                            {
                                dataField: 'unit',
                                caption: $translate.instant('Unit')
                            },
                            {
                                dataField: 'quantity',
                                caption: $translate.instant('Quantity')
                            },
                            {
                                dataField: 'unitPrice',
                                caption: $translate.instant('UnitPrice')
                            },
                            {
                                dataField: 'amount',
                                caption: $translate.instant('Amount')

                            },
                            {
                                dataField: 'taxRate',
                                caption: $translate.instant('TaxRate')
                            },
                            {
                                dataField: 'taxAmount',
                                caption: $translate.instant('TaxAmount')
                            },
                            {
                                dataField: 'remark',
                                caption: $translate.instant('Remark')
                            },
                            {
                                dataField: 'id',
                                caption: $translate.instant('Operation'),
                                cellTemplate: function(container, options) {
                                    try {
                                        var data = options.data;
                                        // 打印预览
                                        $("<span class='span-btn' />")
                                            .text('Preview')
                                            .on('click', function() {
                                                $scope.preview(data);
                                            })
                                            .appendTo(container);


                                    } catch (e) {
                                        $log.error(e);
                                    }
                                }
                            }

                        ]
                    }
                }
            };
        };

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

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

            var valueExpr = "id";
            var displayExpr = "value";

            var isShowClearButton = true;


            $scope.minDate = new Date(2000, 0, 1);
            $scope.maxDate = new Date(2029, 11, 31);
            $scope.searchEntityOptions = {
                //1. entity name
                txtEntityNameOptions: {
                    bindingOptions: {
                        value: 'searchEntity.entityName',
                    },
                    // placeholder: $scope.pleaseSelect,
                    showClearButton: isShowClearButton,
                    noDataText: $scope.translated.NoData,
                },
                //2. last 
                lastModifiedDateOptions: {
                    min: $scope.minDate,
                    max: $scope.maxDate,
                    bindingOptions: {
                        value: 'searchEntity.lastModifiedBy'
                    }
                },
                txtVINOptions: {
                    bindingOptions: {
                        value: 'searchEntity.vin',
                    },
                    placeholder: $scope.pleaseInput,
                    showClearButton: isShowClearButton,
                    noDataText: $scope.translated.NoData,
                },

                txtInvoiceCaseNumberOptions: {
                    bindingOptions: {
                        value: 'searchEntity.caseNumber',
                    },
                    placeholder: $scope.pleaseInput,
                    showClearButton: isShowClearButton,
                    noDataText: $scope.translated.NoData,
                },
                txtCommissionableStoreOptions: {
                    bindingOptions: {
                        value: 'searchEntity.commissionableStore',
                    },
                    placeholder: $scope.pleaseInput,
                    showClearButton: isShowClearButton,
                    noDataText: $scope.translated.NoData,
                },
            };
        };

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

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

            $scope.invoiceOperateType = null;
            // memoryService.populatePagingSelection();
            // loadInvoiceGridData();
            // getService.getInvoiceFilterBasicData();
        };

        $scope.test = function() {
            // $scope.invoicePriceOperateType = constant.Operation.Edit;
            // $scope.invoicePriceModel = {
            //     subtotalforFinalPayment: 12
            // };

            $scope.invoiceOperateType = constant.Operation.Add;
            $scope.invoiceModel = {};
        };

        var mainModule = {
            OutputInvoiceEditedList: [],
            DetailsText: $translate.instant('Details'),
            Unstarted: $translate.instant('Waiting'),
            Completed: $translate.instant('Completed'),
            Processing: $translate.instant('Processing'),

            // 用户所属机构
            OwnerOrgModel: null,

            SalesOrgModel: {},

            TaxControlDiskModel: {},
            // 选中的发票列表
            SelectedInvoiceList: [],
            main: function() {
                initSearchBoxContorls();
                mainModule.initInvoiceGrid();

                mainModule.loadInvoiceData();

                memoryService.populatePagingSelection();

                $scope.searchList = mainModule.loadInvoiceData;

                $scope.preview = mainModule.preview;

                $scope.openSelectSalesInfoAndTaxControlDisk = mainModule.openSelectSalesInfoAndTaxControlDisk;

                $scope.cancelPrintBDInvoice = mainModule.cancelPrintBDInvoice;

                mainModule.loadOwnerOrg();
            },

            // 初始化发票表
            initInvoiceGrid: function() {

                $scope.invoiceGridDataSource = [];
                $scope.invoiceEditGridOptions = {
                    bindingOptions: {
                        dataSource: 'invoiceGridDataSource'
                    },
                    // keyExpr: "ID",
                    selection: {
                        mode: "multiple",
                        showCheckBoxesMode: 'always'
                    },
                    paging: {
                        enabled: true,
                    },
                    columnFixing: {
                        enabled: true
                    },
                    allowColumnResizing: true,
                    columnAutoWidth: true,
                    showRowLines: true,
                    showColumnLines: true,
                    // rowAlternationEnabled: true,
                    showBorders: true,
                    // height: '400px',
                    noDataText: $translate.instant('NoDataText'),
                    selectAllText: $translate.instant('SelectAll'),
                    columnChooser: {
                        enabled: true
                    },
                    onContentReady: function(e) {
                        $scope.invoiceGridInstance = e.component;
                    },
                    onSelectionChanged: function(data) {
                        mainModule.SelectedInvoiceList = data.selectedRowsData;
                    },
                    columns: [
                        { dataField: 'vehicleroutinglocation', caption: $translate.instant('VehicleroutinglocationText') },
                        { dataField: 'vin', caption: $translate.instant('VinNumber') },
                        { dataField: 'caseNumber', caption: $translate.instant('InvoiceCaseNumberText') },
                        { dataField: 'modelSeries', caption: $translate.instant('ModelSeries') },
                        { dataField: 'cabinConfiguration', caption: $translate.instant('CabinConfig') }, //发票来源
                        { dataField: 'brandandModelNumber', caption: $translate.instant('MakeAndModel') },
                        { dataField: 'commissionableStore', caption: $translate.instant('CommissionableStore') },
                        { dataField: 'registrationLocalName', caption: $translate.instant('RegistrationLocalName') },
                        { dataField: 'companyVATIDTaxID', caption: $translate.instant('CompanyTaxID'), visible: false }, //税额
                        {
                            dataField: 'subtotalforFinalPayment',
                            caption: $translate.instant('SubtotalForFinalPayment'),
                            format: { type: 'fixedPoint', precision: 2 }
                        },
                        {
                            dataField: 'id',
                            caption: $translate.instant('DetailsText'),
                            cellTemplate: function(container, options) {
                                try {
                                    var data = options.data;
                                    var invoiceStatusType = constant.inputInvoice.statusType;
                                    // 打印预览

                                    $("<span class='span-btn' />")
                                        .text(mainModule.DetailsText)
                                        .on('click', function() {
                                            $scope.preview(data);
                                        })
                                        .appendTo(container);


                                } catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        { dataField: 'importCertificateNumber', caption: $translate.instant('ImportCertificate'), visible: false }, //开票日期
                        { dataField: 'motorNumber', caption: $translate.instant('MotorNumber'), visible: false },
                        { dataField: 'ciqNumber', caption: $translate.instant('CIQNumber'), visible: false },
                        { dataField: 'lastModifiedBy', caption: $translate.instant('LastModifiedBy'), width: 90, visible: false },
                        { dataField: 'otherItem1', caption: $translate.instant('otherItem1'), visible: false },
                        { dataField: 'otherItem1Amount', caption: $translate.instant('otherItem1Amount'), visible: false },
                        { dataField: 'otherItem2', caption: $translate.instant('otherItem2'), visible: false },
                        { dataField: 'otherItem2Amount', caption: $translate.instant('otherItem2Amount'), visible: false },
                        { dataField: 'otherItem3', caption: $translate.instant('otherItem3'), visible: false },
                        { dataField: 'otherItem3Amount', caption: $translate.instant('otherItem3Amount'), visible: false },
                        // { dataField: 'status', caption: $translate.instant('Status') },
                        { dataField: 'bdFapiaoEntity', caption: $translate.instant('VehicleroutinglocationText'), visible: false },
                        { dataField: 'driverLicenseOrgCode', caption: $translate.instant('DriverLicense'), visible: false }, //税额合计小写

                    ],
                    masterDetail: {
                        enabled: true,
                        template: "paymentDetail"
                    },
                    paymentDetailOptions: function(payments) {
                        return {
                            dataSource: payments,
                            columnAutoWidth: true,
                            showBorders: true,
                            width: '92%',
                            height: '95%',
                            noDataText: $translate.instant('NoDataText'),
                            columns: [
                                { dataField: 'paymentAmount', caption: $translate.instant('PaymentAmount') },
                                {
                                    dataField: 'paymentDate',
                                    caption: $translate.instant('PaymentDate'),
                                    dataType: 'date',
                                    format: 'yyyy-MM-dd'
                                },
                                { dataField: 'payorName', caption: $translate.instant('PayorName') },
                                {
                                    dataField: 'UpdateTime',
                                    dataType: 'date',
                                    format: 'yyyy-MM-dd',
                                    caption: $translate.instant('UpdateTime')
                                }
                            ]
                        }
                    }

                };
            },

            // 获取编辑发票数据
            loadInvoiceData: function() {
                var model = {};
                vatOutputInvoiceManageService.getOutputInvoiceEditedList(model).success(function(data) {
                    mainModule.OutputInvoiceEditedList = mainModule.parseData(data);
                    // mainModule.computePageInfo(data);

                    mainModule.searchList(mainModule.OutputInvoiceEditedList);

                    $timeout(function() {
                        memoryService.repaintInvoiceGrid();
                    }, 50);
                });
            },

            showList: function(data) {
                $scope.invoiceGridDataSource = data;
                // $timeout(function() {
                //     $scope.invoiceGridDataSource = data;
                //     // memoryService.repaintInvoiceGrid();
                // }, 50);
            },
            // 计算分页信息
            computePageInfo: function(data) {
                if (!data) {
                    data = [];
                }

                $scope.pagingOptions.totalItems = data.length;
                var totalCount = data.length;
                var totalPage = parseInt(totalCount / $scope.pagingOptions.pageSize);
                totalPage = totalCount % $scope.pagingOptions.pageSize == 0 ? totalPage : totalPage + 1;
                $scope.pagingOptions.totalPages = totalPage;

                if ($scope.pagingOptions.pageIndex > totalPage) {
                    $scope.pagingOptions.pageIndex = totalPage;
                }

                if ($scope.pagingOptions.pageIndex < 1) {
                    $scope.pagingOptions.pageIndex = 1;
                }

                var startIndex = ($scope.pagingOptions.pageIndex - 1) * $scope.pagingOptions.pageSize;

                var endIndex = $scope.pagingOptions.pageIndex * $scope.pagingOptions.pageSize;

                if (endIndex > totalCount) {
                    endIndex = totalCount;
                }


                var result = data.slice(startIndex, endIndex);

                $timeout(function() {
                    $scope.invoiceGridDataSource = result;
                    memoryService.repaintInvoiceGrid();
                }, 10);
            },

            // 查找list
            searchList: function() {

                var filterFunction = function(row, field, searchText) {
                    if (searchText) {
                        searchText = searchText.trim().toLowerCase();

                        var temp = '';
                        if (row[field]) {
                            temp = row[field].trim().toLowerCase();
                        }

                        if (temp.indexOf(searchText) === -1) {
                            return false;
                        }
                    }

                    return true;
                };

                var result = _.filter(mainModule.OutputInvoiceEditedList, function(row) {

                    if (!filterFunction(row, 'vin', $scope.searchEntity.vin)) {
                        return false;
                    }

                    if (!filterFunction(row, 'caseNumber', $scope.searchEntity.caseNumber)) {
                        return false;
                    }

                    if (!filterFunction(row, 'commissionableStore', $scope.searchEntity.commissionableStore)) {
                        return false;
                    }

                    return true;
                });

                mainModule.showList(result);

            },

            // 转换时间格式
            parseData: function(result) {
                if (result && result.length > 0) {
                    result.forEach(function(row) {

                        if (row.lastModifiedBy) {
                            var d = window.PWC.parseFromLocalTimeString(row.lastModifiedBy);
                            row.lastModifiedBy = d.formatDateTime('yyyy-MM-dd');
                        }

                        var driverLicenseOrgCode = '';
                        if (row.driverLicense) {
                            driverLicenseOrgCode += row.driverLicense;
                        }

                        if (row.organizationCode) {
                            driverLicenseOrgCode += '/' + row.organizationCode;
                        }

                        row.driverLicenseOrgCode = driverLicenseOrgCode;

                        if (row.operateStatus === 0) {
                            row.status = "normal";
                        } else if (row.operateStatus === 1) {
                            row.status = "issued";
                        }
                    });
                }

                return result;
            },

            // 打印预览
            preview: function(data) {
                // body...
                $scope.invoiceModel = mainModule.parsePrintData(data);

                $scope.invoiceOperateType = constant.Operation.Edit;

                $scope.closeInvoiceModal = function(param) {
                    $state.go('outputInvoiceManage.issuedInvoiceBdView');
                };

                // 取消的时候,如果改变了数据,则重新刷新
                $scope.changeInvoiceModal = function(param) {
                    mainModule.loadInvoiceData();
                };
            },

            // 购房名称及身份证号码,组织机构代码
            getBuyerInfo: function(data) {

                var str = '';

                if (!data) {
                    return str;
                }

                // if (data.registrationLocalName) {
                //     str = data.registrationLocalName;
                // }

                if (data.driverLicense) {
                    str += data.driverLicense;
                }

                if (data.organizationCode) {
                    str += data.organizationCode;
                }

                return str;

            },

            // 转换为打印数据
            parsePrintData: function(data) {
                var invoiceModel = {
                    editInvoiceId: data.id,
                    buyerInfo: data.buyerInfo,
                    registrationLocalName: data.registrationLocalName,
                    buyerIDOrCode: '',
                    companyVATIDTaxID: data.companyVATIDTaxID,
                    category: '',
                    cabinConfiguration: data.cabinConfiguration,
                    producingPlace: data.producingPlace,
                    certificateNumber: data.certificateNumber,
                    importCertificateNumber: data.importCertificateNumber,
                    ciqNumber: data.ciqNumber,
                    motorNumber: data.motorNumber,
                    vin: data.vin,
                    subtotalforFinalPaymentCH: '',
                    subtotalforFinalPayment: data.subtotalforFinalPayment,
                    invoiceCode: '',
                    invoiceNumber: '',
                    salesUnitName: data.salesUnitName,
                    salesUnitPhoneNumber: data.salesUnitPhoneNumber,
                    salesTaxPayerNumber: data.salesTaxPayerNumber,
                    salesAccount: data.salesAccount,
                    salesAddress: data.salesAddress,
                    salesBankName: data.salesBankName,
                    vatRateorLevyRate: data.vatRateorLevyRate,
                    taxableSubtotal: data.taxableSubtotal,
                    mainTaxAuthoritiesCode: '',
                    excludeTaxPrice: null,
                    taxPaymentCertificateNumber: '',
                    organizationCode: data.organizationCode,
                    driverLicense: data.driverLicense,
                    deliveryStatus: data.deliveryStatus,
                    vehicleroutinglocation: data.vehicleroutinglocation,
                    caseNumber: data.caseNumber,
                    // 吨位
                    tonnage: data.tonnage,

                    // 限乘人数
                    capacity: data.capacity,

                    // 生产企业名称
                    manufacturer: '拓速乐佛利蒙总装厂',
                    governmentClassification: data.governmentClassification,
                    brandandModelNumber: data.brandandModelNumber,
                    reasonIDList: data.reasonIDList,
                    sameVehicleroutinglocationList: mainModule.OwnerOrgModel.sameVehicleroutinglocationList,

                    taxControlDisk: mainModule.TaxControlDiskModel
                };

                if (mainModule.SalesOrgModel) {
                    invoiceModel.salesUnitName = mainModule.SalesOrgModel.name;
                    invoiceModel.salesUnitPhoneNumber = mainModule.SalesOrgModel.phoneNumber;
                    invoiceModel.salesTaxPayerNumber = mainModule.SalesOrgModel.taxPayerNumber;
                    invoiceModel.salesAccount = mainModule.SalesOrgModel.bankAccountNumber;
                    invoiceModel.salesAddress = mainModule.SalesOrgModel.manufactureAddress;
                    invoiceModel.salesBankName = mainModule.SalesOrgModel.bankAccountName;
                }

                if (!invoiceModel.producingPlace) {
                    invoiceModel.producingPlace = '美国';
                }



                invoiceModel.subtotalforFinalPaymentCH = window.PWC.convertChineseCurrency(data.subtotalforFinalPayment);

                invoiceModel.buyerIDOrCode = mainModule.getBuyerInfo(data);

                return invoiceModel;
            },

            getBdInvoiceInventory: function() {
                if (!mainModule.SelectedInvoiceList || mainModule.SelectedInvoiceList.length === 0) {
                    SweetAlert.warning($translate.instant('SelectBdInvoiceCheck'));
                    return;
                }

                if (!mainModule.TaxControlDiskModel || !mainModule.TaxControlDiskModel.id) {
                    return;
                }


                vatOutputInvoiceManageService.getBdInvoiceInventory(mainModule.TaxControlDiskModel.id).then(function(data) {
                    if (data && data.data && data.data.data) {
                        $scope.preIssueEntity = data.data.data;
                    } else {
                        $scope.preIssueEntity.inventory = 0;
                        $scope.preIssueEntity.thresholdValue = 20;
                    }

                    var promise;
                    var result = true;

                    if ($scope.preIssueEntity.inventory === 0) {
                        // promise = messagebox.info($translate.instant("PaperInvoiceRunnOut"), '');
                        result = false;

                        // Paper 已经用完了
                        $scope.inventoryType = 1;
                        promise = $q.when(result);
                    } else if ($scope.preIssueEntity.inventory < $scope.preIssueEntity.thresholdValue) {
                        // promise = messagebox.info($translate.instant("PaperInvoiceRunningOut"), '');
                        promise = $q.when(result);

                        // Paper快完了
                        $scope.inventoryType = 2;
                    } else {

                        // paper 充足
                        $scope.inventoryType = 3;
                        promise = $q.when(result);
                    }

                    return promise;
                }).then(function() {

                    // 弹出选择框
                    // mainModule.openSelectSalesInfoAndTaxControlDisk();
                });
            },

            openSelectSalesInfoAndTaxControlDisk: function() {

                if (!mainModule.SelectedInvoiceList || mainModule.SelectedInvoiceList.length === 0) {
                    SweetAlert.warning($translate.instant('SelectBdInvoiceCheck'));
                    return;
                }

                $scope.inventoryType = 0;
                mainModule.SalesOrgModel = {};
                mainModule.TaxControlDiskModel = {};

                var editModel = {};
                $scope.editModel = editModel;

                var defaultSalesId = null;
                if (mainModule.OwnerOrgModel.sameVehicleroutinglocationList && mainModule.OwnerOrgModel.sameVehicleroutinglocationList.length === 1) {
                    mainModule.SalesOrgModel = mainModule.OwnerOrgModel.sameVehicleroutinglocationList[0];
                    defaultSalesId = mainModule.OwnerOrgModel.sameVehicleroutinglocationList[0].id;
                }

                $scope.selectSalesOrg = {};

                $scope.selectTaxControlDisk = {};

                var SalesChanged = function(data) {
                    $scope.selectSalesOrg = data;

                    $scope.selectTaxControlDisk = {};

                    if (data.taxControlDiskList && data.taxControlDiskList.length > 0) {
                        data.taxControlDiskList.forEach(function(row) {
                            row.name = row.taxControlDiskSerialNumber + row.taxControlDiskDescribe;
                        });

                        if (data.taxControlDiskList.length === 1) {
                            $scope.selectTaxControlDisk = data.taxControlDiskList[0];
                            mainModule.TaxControlDiskModel = $scope.selectTaxControlDisk;
                        }
                    }

                };


                var taxControlDiskChanged = function(model) {

                    mainModule.TaxControlDiskModel = model;
                    mainModule.getBdInvoiceInventory();
                };

                $scope.mainDxOptions = {
                    selectTaxControlDiskOptions: {
                        bindingOptions: {
                            dataSource: 'selectSalesOrg.taxControlDiskList',
                            value: 'selectTaxControlDisk.id',
                        },
                        onSelectionChanged: function(args) {
                            // mainModule.TaxControlDiskModel = args.selectedItem;

                            taxControlDiskChanged(args.selectedItem);
                        },
                        noDataText: $translate.instant('NoDataText'),
                        valueExpr: 'id',
                        displayExpr: 'name'
                    },
                    selectSalesOptions: {
                        dataSource: mainModule.OwnerOrgModel.sameVehicleroutinglocationList,
                        onSelectionChanged: function(args) {
                            mainModule.SalesOrgModel = args.selectedItem;
                            SalesChanged(args.selectedItem);
                        },
                        value: defaultSalesId,
                        valueExpr: 'id',
                        displayExpr: 'name'
                    },
                };


                $scope.mainDxValidateOptions = {
                    selectTaxControlDiskOptions: {
                        validationRules: [{
                            type: "required",
                            message: $translate.instant('TaxControlDiskRequire')
                        }]
                    },

                    selectSalesOptions: {
                        validationRules: [{
                            type: "required",
                            message: $translate.instant('BDRequire')
                        }]
                    },
                };


                var modalInstance = $uibModal.open({
                    animation: false,
                    backdrop: false,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'fapiaoIssuingConfirmModal.html',
                    //windowClass: 'printInvoiceListModal',
                    size: 'selectEntityDisk',
                    scope: $scope,
                    resolve: {
                        editModel: editModel
                    }
                });

                modalInstance.result.then(function(data) {
                    // $scope.templateModel = data;
                    $scope.isUpdate = true;
                    $scope.isReadOnly = true;
                    // $scope.onClosed({ model: data });
                    $scope.operateType = null;
                }, function() {
                    $scope.operateType = null;
                    $scope.isReadOnly = true;
                    $scope.isUpdate = false;
                    //$log.info('Modal dismissed at: ' + new Date());
                });


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

                    modalInstance.close($scope.editModel);

                    mainModule.openPrintProgressModal();
                };

                // 取消
                $scope.cancel = function() {

                    modalInstance.dismiss('cancel');
                };

            },

            // 弹框打印列表
            openPrintProgressModal: function() {
                // 弹框打印列表

                var taskList = [];
                mainModule.SelectedInvoiceList.forEach(function(row) {

                    var vinStr = row.vin ? '/' + row.vin : '';
                    var item = {
                        text: mainModule.Unstarted,
                        status: 'Unstarted',
                        name: row.modelSeries + vinStr
                    };

                    item.data = mainModule.parsePrintData(row);

                    taskList.push(item);

                    if (row.isNeedSendEmail == enums.IsNeedSendEmailEnum.Need) {
                        vatOutputInvoiceManageService.sendEmail(row.vin, row.id);
                        vatOutputInvoiceManageService.pendingForApprovalGdBdInvoice(row.vin);
                    }
                });

                var editModel = {};
                editModel.tasks = taskList;

                $scope.editModel = editModel;

                var modalInstance = $uibModal.open({
                    animation: false,
                    backdrop: false,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'printInvoiceListModal.html',
                    windowClass: 'printInvoiceListModal',
                    scope: $scope,
                    resolve: {
                        editModel: editModel
                    }
                });

                modalInstance.result.then(function(data) {
                    // $scope.templateModel = data;
                    $scope.isUpdate = true;
                    $scope.isReadOnly = true;
                    // $scope.onClosed({ model: data });
                    $scope.operateType = null;
                }, function() {
                    $scope.operateType = null;
                    $scope.isReadOnly = true;
                    $scope.isUpdate = false;
                    $log.info('Modal dismissed at: ' + new Date());
                });


                var saveData = function(model) {

                    modalInstance.close(model);
                };

                // 保存
                $scope.save = function() {
                    var model = $scope.editModel;

                    saveData(model);
                };

                // 取消
                $scope.cancel = function() {

                    $scope.editModel.isCancel = true;
                    modalInstance.dismiss('cancel');
                };

                var successCount = 0;

                // 循环打印到完成
                var printFunction = function(index) {

                    if ($scope.editModel.isCancel) {
                        return;
                    }

                    var row = $scope.editModel.tasks[index];
                    row.status = 'Processing';
                    row.text = mainModule.Processing;
                    row.deferTemp = $q.defer();
                    // primistList.push(row.deferTemp.promise);

                    vatOutputInvoiceManageService.addOutputInvoicePrinted(row.data, false).success(function(ret) {

                        if (ret.result) {
                            row.status = 'Completed';
                            row.text = mainModule.Completed;
                            successCount++;
                        } else {
                            row.status = 'Error';
                            row.text = $translate.instant(ret.resultMsg);
                        }

                        index++;
                        if (index === $scope.editModel.tasks.length) {
                            // 已经打印到最后一个,页面跳转

                            if (successCount === $scope.editModel.tasks.length) {
                                modalInstance.close();
                                $state.go('outputInvoiceManage.issuedInvoiceBdView');
                            }

                        } else {
                            printFunction(index);
                        }

                        // row.deferTemp.resolve(ret);
                    });
                };

                if ($scope.editModel.tasks && $scope.editModel.tasks.length > 0) {
                    printFunction(0);
                }


            },

            // 获取用户所属机构
            loadOwnerOrg: function() {
                userService.getUserOwnerOrganization().success(function(data) {

                    if (data) {
                        if (data.taxControlDiskList && data.taxControlDiskList.length > 0) {
                            data.taxControlDiskList.forEach(function(row) {

                                row.name = row.taxControlDiskSerialNumber + row.taxControlDiskDescribe;
                            });
                        }
                    }

                    mainModule.OwnerOrgModel = data;
                });
            },

            // 取消发票
            cancelPrintBDInvoice: function() {

                if (!mainModule.SelectedInvoiceList || mainModule.SelectedInvoiceList.length === 0) {
                    messageBox.warning('NoDataText', false);
                    return;
                }

                var msg = $translate.instant('Confirm') + ' ' + $translate.instant('Cancel') + '?';

                messagebox.confirm(msg, '', constant.teslaConfirmClassName).then(function(isConfirm) {
                    if (isConfirm) {

                        vatOutputInvoiceManageService.cancelBDEditList(mainModule.SelectedInvoiceList).success(function(ret) {
                            if (ret.result) {
                                SweetAlert.success($translate.instant('SaveSuccess'));
                                mainModule.loadInvoiceData();
                            } else {
                                swal($translate.instant('SaveFail'), $translate.instant('SaveFail'), 'warning');
                            }
                        });
                    }
                });

            }

        };


        (function initialize() {
            $log.debug('outputInvoiceEditController.ctor()...');
            mainModule.main();

        })();
    }
]);