invoiceModule.controller('invoiceManageMainUploadElectronicInvoiceController', ['$scope', '$log', '$document', '$uibModal', 'SweetAlert', '$translate', '$q', 'apiInterceptor', '$interval', 'region', '$timeout', 'InvoiceManageService', 'Upload',
function ($scope, $log, $document, $uibModal, SweetAlert, $translate, $q, apiInterceptor, $interval, region, $timeout, InvoiceManageService,Upload) {
            'use strict';
        
            //分页的设置
            $scope.pagingOptions = {
                pageIndex: 1,  //当前页码
                totalItems: 100,  //总数据
                totalPages: 10,//总页数
                maxSize: 10, //分页数字的限制。
                pageSize: constant.page.pageSizeArrary[1],  //每页多少条数据 
                pageSizeString: constant.page.pageSizeArrary[1].toString(),
                firstPage: $translate.instant('PagingFirstPage'),
                previousPage: $translate.instant('PagingPreviousPage'),
                nextPage: $translate.instant('PagingNextPage'),
                lastPage: $translate.instant('PagingLastPage'),
            };

            $scope.searchFilterOptions = [];
            $scope.searchEntity = [];

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



            var fileUploadInfo = {
                fileList: [],
                path: "C:\\Users\\admin\\Desktop\\Scan\\Temp",
                strEx: '.jpg',
                userId: '90CEF6C1C1C0762000D2'
            };
            var nResult = -1;

            var chunkSize = 100000;
            var resumable = true;
            var uploadInvoiceUrl = apiInterceptor.webApiHostUrl + '/invoiceManage/UploadInvoiceFile';

            //发票上传
            $scope.invoiceUpload = {
                //加载核心
                loadRecogKenal: function () {
                    nResult = objBillOcr.InitRecogForm(fileUploadInfo.userId);
                    if (nResult != 0) {
                        SweetAlert.warning("核心加载失败,返回值:" + nResult);
                        return false;
                    }
                    return true;
                },
                //释放核心
                freeRecogKenal: function () {
                    objBillOcr.UninitRecogForm();
                },
                //扫描上传
                scanUpload: function () {
                    if (!invoiceUpload.loadRecogKenal())
                        return;
                    //设置要识别的票据类型 
                    objBillOcr.SetFormTypes(document.IDScanRecog.BillType.value, 3);
                    objBillOcr.SetDeviceAdvancedParams(6, 0);
                    objBillOcr.SetDeviceAdvancedParams(10, 10);
                    var bHavePaper = 1;
                    //扫描
                    while (bHavePaper) {
                        var fileItem = {};
                        var dateNow = new Date().toDateString('yyyyMMddHHmmss');
                        var imagePath = fileUploadInfo.path + "\\" + dateNow + fileUploadInfo.strEx;
                        fileItem.filePath = imagePath;
                        fileItem.fileName = dateNow;
                        nResult = objBillOcr.AcquireNewImage(imagePath);
                        if (nResult != 0) {
                            fileItem.message = "扫描失败,返回值:" + nResult;
                            fileItem.status = false;
                        }
                        fileUploadInfo.fileList.push(fileItem);
                        bHavePaper = objBillOcr.IsHavePaper();
                    }
                    //to do
                    invoiceUpload.initFiles();

                    //遍历识别
                    fileUploadInfo.fileList.forEach(function (item) {
                        //对扫描成功的进行识别
                        if (item.status) {
                            nResult = objBillOcr.LoadImages(item.filePath);
                            if (nResult != 0) {
                                item.message = "加载图片不成功,返回值:" + nResult;
                                item.status = false;
                            }
                            nResult = objBillOcr.RecognizeForm();
                            if (nResult != 0) {
                                item.message = "识别不成功,返回值:" + nResult;
                                item.status = false;
                            }
                            else
                                item.status = true;
                            var nFieldNum = objBillOcr.GetRecogCellCount();
                            var itemData = {};
                            if (nFieldNum > 0) {
                                for (var i = 0; i < nFieldNum; ++i) {
                                    var strFieldName = objBillOcr.GetFieldName(i);
                                    strResult += strFieldName;
                                    strResult += ":";
                                    var strResultName = objBillOcr.GetRecognizeResult(i);
                                    if (strFieldName == "票据类型") {
                                        if (strResultName == "1") {
                                            strResultName = "普票";
                                        }
                                        else {
                                            strResultName = "专票";
                                        }

                                    }
                                    itemData[strFieldName] = strResultName;
                                }
                            }
                            item.itemData = itemData;
                            //to do
                            invoiceUpload.updateFileStatus(item);
                        }
                    });
                    invoiceUpload.freeRecogKenal();
                },

                initFiles: function () {
                    //to do
                    //根据文件List更新UI
                },
                updateFileStatus: function (fileItem) {
                    //to do 
                    //根据文件识别情况更新UI
                },
                //上传文件
                uploadInvoiceFile: function (files, inputInvoice) {
                    if (files && files.length) {
                        //allFilesCount = files.length;
                        //evidenceCount = 0;
                        for (var i = 0; i < files.length; i++) {
                            var file = files[i];
                            if (!file.$error) {
                                var tempFileName = PWC.newGuid() + '.dat';
                                var token = $('input[name="__RequestVerificationToken"]').val();
                                Upload.upload({
                                    url: uploadInvoiceUrl,
                                    data: {
                                        cancel: false,
                                        filename: file.name,
                                        tempFileName: tempFileName,
                                        file: file,
                                        inputInvoice: inputInvoice
                                    },
                                    resumeChunkSize: resumable ? chunkSize : null,
                                    headers: {
                                        'Access-Control-Allow-Origin': '*',
                                        Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken,
                                        from: 'taxAdmin@cn.pwc.com'
                                    },
                                    __RequestVerificationToken: token,
                                    withCredentials: true
                                }).then(uploadInvoiceSuccess);
                            }
                        }
                    }
                },

                //上传成功
                uploadInvoiceSuccess: function (resp) {
                    //to do
                }
            };

             //内部处理
            var memoryService = {
                //发票来源列表构造
                populateInvoiceSourceTypList: function () {
                    $scope.searchFilterOptions.invoiceSourceList = memoryService.translateEnumValue(constant.inputInvoice.invoiceSourceTypeArray);
                },

                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;
                },
            };



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

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

                var isShowClearButton = false;

                $scope.searchEntityOptions = {
                    selectinvoiceSourceTypeOptions: {
                        displayExpr: displayExpr,
                        valueExpr: valueExpr,
                        bindingOptions: {
                            value: 'searchEntity.invoiceSourceType',
                            dataSource: 'searchFilterOptions.invoiceSourceList'
                        },
                        onValueChanged: function (data) {
                            $scope.showPoOptions = false;
                            $scope.showStaffOptions = false;
                            if (data.value == constant.inputInvoice.invoiceSourceType.InvoiceNonRawMaterialPurchase.id) {
                                $scope.showPoOptions = true;
                            }
                            else if (data.value == constant.inputInvoice.invoiceSourceType.InvoiceClaim.id) {
                                $scope.showStaffOptions = true;
                            }
                        },
                        placeholder: $scope.translated.pleaseSelect,
                        showClearButton: isShowClearButton,
                        noDataText: $scope.translated.NoData,
                    },
                    //全选
                    checkAllOptions: {
                        onValueChanged: function (e) {
                            var row = e.model.template;
                            if (row) {
                                row.isCheckAll = e.value;
                                row.currentInvoiceList.forEach(function (item) {
                                    item.isCheckAll = e.value;
                                });
                            }
                            console.log(e.element);
                        }
                    },
                    //员工编号
                    staffIdOPtions: {
                        bindingOptions: {
                            value: 'searchEntity.staffID',
                        },
                        placeholder: $scope.pleaseInput,
                        showClearButton: isShowClearButton,
                    },
                    //po number
                    PoNumberOptions: {
                        bindingOptions: {
                            value: 'searchEntity.poNumber',
                        },
                        placeholder: $scope.pleaseInput,
                        showClearButton: isShowClearButton,
                    }
                };
            };

            //完成上传
            $scope.uploadToServer = function () {
                $scope.uploadInvoiceList;
            };

            var initInvoiceList = function () {
                $scope.uploadInvoiceList = [];

                for (var i = 0; i < 3; i++) {

                    var currentInvoiceList = [{
                        id: 0,
                        value: '58913988777',
                        status: constant.uploadStatus.success,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 0,
                        value: '58913988777',
                        status: constant.uploadStatus.success,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 0,
                        value: '58913988777',
                        status: constant.uploadStatus.success,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 0,
                        value: '58913988777',
                        status: constant.uploadStatus.success,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 0,
                        value: '58913988777',
                        status: constant.uploadStatus.success,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 0,
                        value: '58913988777',
                        status: constant.uploadStatus.success,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 1,
                        value: '58913988007',
                        status: constant.uploadStatus.failure,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 2,
                        value: '58913988807',
                        status: constant.uploadStatus.failure,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 3,
                        value: '58213988807',
                        status: constant.uploadStatus.success,
                        time: '2017/08/20 12:30'
                    }, {
                        id: 4,
                        value: '68913988807',
                        status: constant.uploadStatus.duplicate,
                        time: '2017/08/20 12:30'
                    }];

                    var invoice = {
                        id: i,
                        value: i + ' invoice',
                        isCheckAll: false,
                        currentInvoiceList: currentInvoiceList
                    }
                    $scope.uploadInvoiceList.push(invoice);

                }
            };


            (function initialize() {
                $log.debug('invoiceManageMainUploadElectronicInvoiceController.ctor()...');
                initInvoiceList();
                initControlsOptions();
                memoryService.populateInvoiceSourceTypList();
            })();
        }
]);