vatModule.controller('vatPreviewCustomInvoiceSheetController', ['$scope', '$log', '$translate', '$timeout', 'apiInterceptor', 'Upload', 'dataImportService', 'SweetAlert', '$q', 'uiGridConstants', 'projectService', 'uiGridGroupingConstants', 'vatImportService', 'i18nService', 'browserService', '$interval', 'region', 'vatSessionService', 'vatExportService',
    function ($scope, $log, $translate, $timeout, apiInterceptor, Upload, dataImportService, SweetAlert, $q, uiGridConstants, projectService, uiGridGroupingConstants, vatImportService, i18nService, browserService, $interval, region, vatSessionService,vatExportService) {
        'use strict';

        $scope.currentEditingValue = "";

        // **********************************************************************
        //Date range picker:
        $scope.startDate = new Date(vatSessionService.project.year, 0, 1);
        $scope.endDate = new Date(vatSessionService.project.year, 11, 31);
        $scope.dateFormat = $translate.instant('dateFormat4YearMonthDay');

        var minDate = [1, vatSessionService.project.year];
        var maxDate = [12, vatSessionService.project.year];
        var setDate = [
            [vatSessionService.month, vatSessionService.project.year],
            [vatSessionService.month, vatSessionService.project.year]];

        //Date range picker:
        // **********************************************************************

        $scope.filterData = {
            periodFrom: 0,
            periodTo: 0,
            invoiceStartDate: null,
            invoiceEndDate: null,
            payNum: null,
            taxAmountFrom: null,
            taxAmountTo: null,
            invoiceAmountFrom: null,
            invoiceAmountTo: null

        };

        $scope.criteriaList = [];

        // current CATEGORY:


        $scope.monthList = [$translate.instant('Month01'),
                            $translate.instant('Month02'),
                            $translate.instant('Month03'),
                            $translate.instant('Month04'),
                            $translate.instant('Month05'),
                            $translate.instant('Month06'),
                            $translate.instant('Month07'),
                            $translate.instant('Month08'),
                            $translate.instant('Month09'),
                            $translate.instant('Month10'),
                            $translate.instant('Month11'),
                            $translate.instant('Month12')
        ];


        $scope.filterData.periodFrom = vatSessionService.month;
        $scope.filterData.periodTo = vatSessionService.month;


        // NEW STUFF:
        $scope.pagination = {
            totalCount: 0,
            pageIndex: 1,
            pageSize: 100
        };


        // ****************************************************************************************
        //************ EXCEL EXPORT FUNCTION ***************/


        //导出进项发票数据
        var downloadCustomInvoice = function () {


            if ($scope.filterData !== null && $scope.filterData !== "") {

               var criteria = JSON.stringify($scope.filterData);
                if (browserService.isIE() || browserService.isEdge())
                    criteria = encodeURIComponent(criteria);
            }
            else
                criteria = "";

            vatImportService.getExportCustomInvoiceList(criteria).success(function (data, status, headers) {
                if(status===204){
                    SweetAlert.warning("没有数据可以下载");
                    return;
                }
                vatExportService.exportToExcel(data, status, headers, 'CustomInvoice.xlsx');
            });
        };
        //************ EXCEL EXPORT FUNCTION ***************/
        // ****************************************************************************************
        


        // ************************************************************************************************
        // function to get data from Backend
        $scope.getDataFromDatabase = function (from, to, criteria, paginationInformation) {
          
 
                // always Jsonized the pagination:
                if (paginationInformation !== null && paginationInformation !== "") {
                    var pagination = JSON.stringify(paginationInformation);
//                    if (browserService.isIE() || browserService.isEdge())
                        pagination = encodeURIComponent(pagination);
                }
                else
                    pagination = "";
            

            if (criteria !== null && criteria !== "") {

                criteria = JSON.stringify($scope.filterData);
//                if (browserService.isIE() || browserService.isEdge())
                    criteria = encodeURIComponent(criteria);
            }
            else
                criteria = "";


            vatImportService.getCustomsInvoiceDataForDisplay(from, to, criteria, pagination).success(function (customInvoices) {
                var newData = JSON.parse(customInvoices);

                    $scope.gridOptions.data = newData.List;


                    $scope.pagination.totalCount = newData.PageInfo.TotalCount;
                    $scope.pagination.pageIndex = newData.PageInfo.PageIndex;
                    $scope.pagination.pageSize = newData.PageInfo.PageSize;

                    computeIncomeInvoiceItemPage();

                    $('.filter-button').popover("hide");
                
            });
        };


        $scope.updateACustomPrice = function (customId, invoiceAmount) {

            
            vatImportService.updateACustomPrice(customId, invoiceAmount).success(function (customInvoices) {

                SweetAlert.success($translate.instant('UpdateSuccess'));
            });
        };

        // function to get data from Backend
        // ************************************************************************************************


        // ************************************************************************************************
        // SETUP UI GRID TREE:
        var treeData;

        // 国际化;
        // i18nService.setCurrentLang("zh-cn");

        $scope.gridOptions = {
            rowHeight: 50,
            selectionRowHeaderWidth: 50,
            enableFullRowSelection: false,
            enableRowSelection: false,
            enableSorting: false,
            enableFiltering: false,
            enableColumnMenus: false,
            enableRowHeaderSelection: false,
            enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
            enableGridMenu: false,
            enableSelectAll: false,
            exporterLinkLabel: 'get it here',
            exporterCsvFilename: 'CustomInvoices.csv',
            exporterOlderExcelCompatibility: true,

            exporterHeaderFilterUseName: true,
            exportCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;

                $scope.gridApiTotal = gridApi;

                //updating cell: price
                gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {

                    var invoiceAmount = PWC.stringNumberFormat(newValue);
                    if (newValue === oldValue) {

                    }

                    else if (invoiceAmount.trim() !== "" && !isNaN(parseFloat(invoiceAmount)) && isFinite(invoiceAmount)) {
                        $scope.updateACustomPrice(rowEntity.customsId, invoiceAmount);
                        $scope.$apply();
                    }
                    else {
                        //gridApi.edit.raise.cancelCellEdit(rowEntity, colDef);
                        //gridApi.edit.on.cancelCellEdit(rowEntity, colDef);
                        SweetAlert.warning($translate.instant('UpdateFailed'));
                        $scope.getDataFromDatabase($scope.filterData.periodFrom, $scope.filterData.periodTo, $scope.filterData, $scope.pagination);
                    }
                });

                $interval(function () {
                    $scope.gridApiTotal.core.handleWindowResize();
                }, 500, 60 * 60 * 8);
            },

            columnDefs: [
            {

                field: 'recordNumber', name: $translate.instant('ImportErrorPopUpNoCol'), enableCellEdit: false, width: '100',
                cellTemplate: '<div class="paddingLeft"><span>{{row.entity.recordNumber}}<span></div>'
            },
            {
                field: 'periodId', name: $translate.instant('PeriodId'), headerCellClass: 'alignCenter', enableCellEdit: false,
                cellTemplate: '<div class="alignCenter"><span>{{row.entity.periodId}}</span></div>'
            },
             {
                 field: 'issueDate', name: $translate.instant('CustomsIssueDate'), enableCellEdit: false,
                 cellTemplate: '<div class="paddingLeft"><span>{{row.entity.issueDate}}<span></div>'
             },


            {
                field: 'payNum', name: $translate.instant('CustomsPayNum'), enableCellEdit: false,
                cellTemplate: '<div class="paddingLeft"><span>{{row.entity.payNum}}<span></div>'
            },
             {
                 field: 'invoiceAmount', enableCellEdit: true, enableCellEditOnFocus: true, name: $translate.instant('Amount'), headerCellClass: 'alignRight', width: '150',
                 cellTemplate: '<div class="alignRight"><span>{{row.entity.invoiceAmount}}</span></div>'
             },

              {
                  field: 'invoiceTaxAmount', enableCellEdit: false, name: $translate.instant('InvoiceSE'), headerCellClass: 'alignRight',
                  cellTemplate: '<div class="alignRight"><span>{{row.entity.invoiceTaxAmount}}</span></div>'
              },

              {
                  field: 'auditResult', name: $translate.instant('CustomsAuditResult'), enableCellEdit: false,
                  cellTemplate: '<div class="paddingLeft"><span>{{row.entity.auditResult}}</span></div>'
              }


            ]
        };
        // SETUP UI GRID TREE:
        // ************************************************************************************************


        // Get initial Data from Backend to fill the UI grid Tree:
        $scope.getDataFromDatabase($scope.filterData.periodFrom, $scope.filterData.periodTo, "", $scope.pagination);


        // ************************************************************************************************
        // Export Data Gird To CSV
        //$scope.export = function () {
        //    var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
        //    $scope.gridApi.exporter.csvExport("all", "visible", myElement);
        //};
        // Export Data Gird To CSV
        // ************************************************************************************************

       
        // ************************************************************************************************
        // Reset Data Filter:
        $scope.doDataFilterReset = function () {
            var from = $scope.filterData.periodFrom;
            var to = $scope.filterData.periodTo;


            $scope.filterData = {
                periodFrom: from,
                periodTo: to,
                invoiceStartDate: null,
                invoiceEndDate: null,
                payNum: null,
                taxAmountFrom: null,
                taxAmountTo: null,
                invoiceAmountFrom: null,
                invoiceAmountTo: null

            };
            // $scope.criteriaList = [];

            //$scope.pagination.pageIndex = 1;
            //$scope.getDataFromDatabase($scope.filterData.periodFrom,$scope.filterData.periodTo, $scope.filterData, $scope.pagination);


        }
        // Reset Data Filter:
        // ************************************************************************************************


        // NEW STUFF

        //计算页数,创建分页栏
        var computeIncomeInvoiceItemPage = function () {

            $scope.curPageItemCount = 0;
            if ($scope.pagination && $scope.pagination.totalCount > 0) {

                
                var totalPage = parseInt($scope.pagination.totalCount / $scope.pagination.pageSize);
                totalPage = $scope.pagination.totalCount % $scope.pagination.pageSize == 0 ? totalPage : totalPage + 1;


                if ($scope.pagination.pageIndex === totalPage) {
                    $scope.curPageItemCount = $scope.pagination.totalCount % $scope.pagination.pageSize;
                }
                else {
                    $scope.curPageItemCount = $scope.pagination.pageSize;
                }



                $scope.pagination.totalPage = totalPage;

                var createPage = $("#totalInvoicePage").createPage({
                    pageCount: totalPage,
                    current: $scope.pagination.pageIndex,
                    backFn: function (p) {
                        //单击回调方法,p是当前页码
                        $scope.pagination.pageIndex = p;
                        $scope.getDataFromDatabase($scope.filterData.periodFrom, $scope.filterData.periodTo, $scope.filterData, $scope.pagination);
                    }
                });

                $('#totalInvoicePage').css('display', 'inline-block');
            } else {
                var createPage = $("#totalInvoicePage").createPage({
                    pageCount: 0,
                    current: $scope.pagination.pageIndex,
                    backFn: function (p) {
                        //单击回调方法,p是当前页码
                        $scope.pagination.pageIndex = p;
                        $scope.getDataFromDatabase($scope.filterData.periodFrom, $scope.filterData.periodTo, $scope.filterData, $scope.pagination);
                    }
                });

                $('#totalInvoicePage').css('display', 'inline-block');
            }
        };


        //初始化分页信息
        var initIncomeInvoiceItemPagination = function () {
            $scope.queryIncomeInvoiceItemResult = {
                list: [],
                pageInfo: {
                    totalCount: -1,
                    pageIndex: 1,
                    pageSize: 10,
                    totalPage: 0,
                }
            }

            $scope.curIncomeInvoiceItemPage = 1;
        };


        // NEW STUFF

        // ************************************************************************************************
        // Perform Data filter


        var prepareSummary = function () {
            // do something before show popover
        };

        //在popover打开时执行事件
        var showPopover = function () {
            $timeout(function () {
                initDatePickers();
            }, 500);
        };

        $scope.doDataFilter = function (removeData) {

            //$scope.filterData.periodFrom = $scope.monthFrom.selected.id;
            //$scope.filterData.periodTo = $scope.monthTo.selected.id;


            if ($scope.filterData.periodFrom > $scope.filterData.periodTo) {
                $scope.filterData.periodTo = $scope.filterData.periodFrom;
            }

            // Filter number validations:
            // fixed a bug when the amount has illegal chars:
            $scope.filterData.taxAmountFrom = (!PWC.isNullOrEmpty($scope.filterData.taxAmountFrom)) ?  PWC.stringNumberFormat($scope.filterData.taxAmountFrom) : "";
            $scope.filterData.taxAmountTo = (!PWC.isNullOrEmpty($scope.filterData.taxAmountTo)) ? PWC.stringNumberFormat($scope.filterData.taxAmountTo) : "";
            $scope.filterData.invoiceAmountFrom = (!PWC.isNullOrEmpty($scope.filterData.invoiceAmountFrom)) ?  PWC.stringNumberFormat($scope.filterData.invoiceAmountFrom) : "";
            $scope.filterData.invoiceAmountTo = (!PWC.isNullOrEmpty($scope.filterData.invoiceAmountTo)) ?  PWC.stringNumberFormat($scope.filterData.invoiceAmountTo) : "";



            // Filter validations:
            if (!PWC.isNullOrEmpty($scope.filterData.taxAmountFrom) && !PWC.isNullOrEmpty($scope.filterData.taxAmountTo) &&
                $scope.filterData.taxAmountFrom > $scope.filterData.taxAmountTo)
            {
                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                    function(isConfirm){
                        if (isConfirm) {
                            $("#filterButton").click();
                        }

                    });
 
            }
            else if (!PWC.isNullOrEmpty($scope.filterData.invoiceAmountFrom) && !PWC.isNullOrEmpty($scope.filterData.invoiceAmountTo) &&
                $scope.filterData.invoiceAmountFrom > $scope.filterData.invoiceAmountTo) {
                
                swal({ title: "", text: $translate.instant('AmountWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                     function (isConfirm) {
                         if (isConfirm) {
                             $("#filterButton").click();
                         }

                     });
            }

            else if (!PWC.isNullOrEmpty($scope.filterData.invoiceStartDate) && !PWC.isNullOrEmpty($scope.filterData.invoiceEndDate) &&
                $scope.filterData.invoiceStartDate > $scope.filterData.invoiceEndDate)
            {
   
                swal({ title: "", text: $translate.instant('DateWarningSearch'), type: "warning", confirmButtonText: $translate.instant('Confirm') },
                    function (isConfirm) {
                        if (isConfirm) {
                            $("#filterButton").click();
                        }

                    });
            }
            else {


                //设置需要去掉的查询条件的值为空
                if (!PWC.isNullOrEmpty(removeData)) {
                    var removeItem = removeData.split("|");
                    removeItem.forEach(function (v) {
                        $scope.filterData[v] = null;

                    });
                }

                //********************************************************************************
                // add to Criteria List for display on top of the grid:
                var crits = $scope.filterData;

                $scope.criteriaList = [];



                var crit = [];
                if (!PWC.isNullOrEmpty(crits.payNum)) {
                    crit = new Object;
                    crit.name = $translate.instant('CustomsPayNum');
                    crit.valueFrom = crits.payNum;
                    crit.propertyName = "payNum";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.invoiceStartDate) || !PWC.isNullOrEmpty(crits.invoiceEndDate)) {
                    if (new Date(crits.invoiceStartDate.replace(/[\.-]/g, '/')) > new Date(crits.invoiceEndDate.replace(/[\.-]/g, '/'))) {
                        $scope.criteriaList = [];
                        SweetAlert.warning($translate.instant('InvoiceDateQueryError'));
                        return;
                    }
                    crit = new Object;
                    crit.name = $translate.instant('CustomsIssueDate');
                    crit.valueFrom = crits.invoiceStartDate;
                    crit.valueTo = crits.invoiceEndDate;
                    crit.propertyName = "invoiceStartDate|invoiceEndDate";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.taxAmountFrom) || !PWC.isNullOrEmpty(crits.taxAmountTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('InvoiceSE');
                    crit.valueFrom = crits.taxAmountFrom + "";
                    crit.valueTo = crits.taxAmountTo + "";
                    crit.propertyName = "taxAmountFrom|taxAmountTo";

                    $scope.criteriaList.push(crit);
                }

                if (!PWC.isNullOrEmpty(crits.invoiceAmountFrom) || !PWC.isNullOrEmpty(crits.invoiceAmountTo)) {
                    crit = new Object;
                    crit.name = $translate.instant('Amount');
                    crit.valueFrom = crits.invoiceAmountFrom + "";
                    crit.valueTo = crits.invoiceAmountTo + "";
                    crit.propertyName = "invoiceAmountFrom|invoiceAmountTo";

                    $scope.criteriaList.push(crit);
                }


                // add to Criteria List for display on top of the grid:
                //********************************************************************************



                //var criteria = JSON.stringify($scope.filterData);
                //if (browserService.isIE() || browserService.isEdge())
                //    criteria = encodeURIComponent(criteria);
                $scope.pagination.pageIndex = 1;
                $scope.getDataFromDatabase($scope.filterData.periodFrom, $scope.filterData.periodTo, $scope.filterData, $scope.pagination);
            }
        };


        // Perform Data filter
        // ************************************************************************************************

        //在popover打开时执行事件
        var showPopover = function () {
            $timeout(function () {
                initDatePickers();
            }, 500);
        };
        //初始化时间控件
        var initDatePickers = function () {
            //认证开始时间

            var ele1 = $("#customInvoiceDateStart");
            ele1.datepicker({
                startDate: $scope.startDate,
                endDate: $scope.endDate,
                language: region,
                autoclose: true,//选中之后自动隐藏日期选择框
                clearBtn: true,//清除按钮
                todayBtn: false,//今日按钮
                format: $scope.dateFormat//日期格式,详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
            });
            ele1.datepicker("setDate", $scope.filterData.invoiceStartDate);
            //认证结束时间
            var ele2 = $("#customInvoiceDateEnd");
            ele2.datepicker({
                startDate: $scope.startDate,
                endDate: $scope.endDate,
                language: region,
                autoclose: true,//选中之后自动隐藏日期选择框
                clearBtn: true,//清除按钮
                todayBtn: false,//今日按钮
                format: $scope.dateFormat//日期格式,详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
            })
            ele2.datepicker("setDate", $scope.filterData.invoiceEndDate);



        };


        //开始
        (function initialize() {

            //初始化month-picker
            $('#input-invoice-period-picker').rangePicker({
                minDate: minDate,
                maxDate: maxDate,
                setDate: setDate,
                months: $scope.monthList,//['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                ConfirmBtnText: $translate.instant('Confirm'),
                CancelBtnText: $translate.instant('ButtonCancel')
            })
                .on('datePicker.show', function (ev, picker) {

                    $('.filter-button').popover("hide");
                })

             .on('datePicker.done', function (e, result) {
                 //开始月份
                 var startMonth = result[0][0];
                 //结束月份
                 var endMonth = result[1][0];
                 $scope.filterData.periodFrom = startMonth;
                 $scope.filterData.periodTo = endMonth;

                 $scope.pagination.pageIndex = 1;
                 $scope.getDataFromDatabase($scope.filterData.periodFrom, $scope.filterData.periodTo, $scope.filterData, $scope.pagination);
             });


            $scope.downloadCustomInvoice = downloadCustomInvoice;



            // Reposition Header when the window is resized
            $(window).on('resize', function () {
                // SetUiGridHeader();
            });

            $scope.showPopover = showPopover;

        })();
    }
]);

//vatModule.directive('onFinishRender', ['$timeout', function ($timeout) {
//    return {
//        restrict: 'A',
//        link: function (scope, element, attr) {
//            if (scope.$last === true) {
//                $timeout(function () {
//                    scope.$emit(attr.onFinishRender);
//                }, 500);
//            }
//        }
//    }
//}]);