citModule.controller('citDistributionTableController', ['$rootScope','$scope', '$log', '$filter','$translate', '$timeout', 'SweetAlert', '$q', 'uiGridConstants', '$interval', 'citPreviewService', 'citReportService','browserService', 'vatSessionService', 'region', 'enums', 'vatExportService',
    function ($rootScope,$scope, $log,$filter, $translate, $timeout, SweetAlert, $q, uiGridConstants, $interval, citPreviewService, citReportService, browserService, vatSessionService, region, enums, vatExportService) {
        'use strict';

        $scope.startDate = new Date(vatSessionService.project.year, 0, 1);
        $scope.endDate = new Date(vatSessionService.project.year, 11, 31);
        $scope.dateFormat = $translate.instant('dateFormat4Year');
        $scope.startMonth = vatSessionService.month;
        $scope.endMonth = vatSessionService.month;
        $scope.totalMoneyAmount = 0;
        $scope.totalTaxAmount = 0;
        $scope.totalBusinessIncome = 0;
        $scope.totalEmployeeRemuneration = 0;
        $scope.totalTotalAssets = 0;


        var minDate = [1, vatSessionService.project.year];
        // var minDate = moment().startOf('month').subtract(0, 'months');
        var maxDate = [12, vatSessionService.project.year];
        var setDate = [
            [vatSessionService.project.year],
            [vatSessionService.project.year]];

        //初始化期间
        var initPeriods = function () {
            var curMonth = new Date().getMonth() + 1;

            $scope.queryParams = {
                pageInfo: {},
                periodStart: '',
                periodEnd: '',
                totalBusinessIncome: $scope.totalBusinessIncome,
                totalEmployeeRemuneration:$scope.totalEmployeeRemuneration,
                totalTotalAssets:$scope.totalEmployeeRemuneration,
                projectId: vatSessionService.project.id
            };
        };

        //从数据库中load数据
        var loadJournalEntryDataFromDB = function (pageIndex) {
            initJournalEntryPagination();
            $scope.curJournalEntryPage = pageIndex;

            //初始化查询信息
            $scope.queryParams = {
                pageInfo: {
                    totalCount: $scope.queryJournalEntryResult.pageInfo.totalCount,
                    pageIndex: pageIndex,
                    pageSize: $scope.queryJournalEntryResult.pageInfo.pageSize,
                    totalPage: 0
                },
                periodStart: '',
                periodEnd: '',
                totalBusinessIncome: $scope.totalBusinessIncome,
                totalEmployeeRemuneration:$scope.totalEmployeeRemuneration,
                totalTotalAssets:$scope.totalEmployeeRemuneration,
                projectId: vatSessionService.project.id
            };

            $scope.getDataFromDatabase($scope.queryParams);
        };

        $scope.getDataFromDatabase = function (queryParams){
            citReportService.getDistributionTables(queryParams).success(function (resp) {
                debugger;
                if (resp.data) {
                    // minDate = data.
                    var index = 1;
                    resp.data.list.forEach(function (v) {
                        v.index = index++;
                    });
                    $scope.gridOptions.data = resp.data.list;
                    $scope.queryJournalEntryResult.pageInfo = resp.data;
                    computeJournalEntryPage();
                    // $scope.ledgerName = data.list[0].ledgerName;
                    // $scope.currencyCode = data.list[0].currencyCode;
                    // $scope.status = data.list[0].status;
                    // $scope.importDate = $filter('date')(data.list[0].date, "yyyy-MM-dd hh:mm:ss");
                }
            });
        };


        //点击任意一页加载数据事件
        var loadIncomeInvoiceDataByPage = function (pageIndex) {
            loadJournalEntryDataFromDB(pageIndex);
        };

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

            if ($scope.queryJournalEntryResult.pageInfo && $scope.queryJournalEntryResult.pageInfo.total > 0) {

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

                //计算本页记录数
                if ($scope.queryJournalEntryResult.pageInfo.pageNum === totalPage) {
                    $scope.curPageItemCount = $scope.queryJournalEntryResult.pageInfo.total % $scope.queryJournalEntryResult.pageInfo.pageSize;
                }
                else {
                    $scope.curPageItemCount = $scope.queryJournalEntryResult.pageInfo.pageSize;
                }

                $scope.queryJournalEntryResult.pageInfo.totalPage = totalPage;

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

                $('#totalInvoicePage').css('display', 'inline-block');
            } else {
                //如果查询结果为0,则直接设置本页记录数为0
                $scope.curPageItemCount = 0;
                var createPage = $("#totalInvoicePage").createPage({
                    pageCount: 0,
                    current: $scope.curJournalEntryPage,
                    backFn: function (p) {
                        //单击回调方法,p是当前页码
                        loadIncomeInvoiceDataByPage(p);
                    }
                });

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

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

            $scope.curJournalEntryPage = 1;
        };

        //将选择了的查询条件显示在grid上方
        var doDataFilter = function (removeData) {
            if ($scope.queryParams.periodStart > $scope.queryParams.periodEnd) {
                $scope.queryParams.periodEnd = $scope.queryParams.periodStart;
            }

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

                    // if ($scope.queryParams.subjectCode === null) {
                    //     $scope.queryParams.subjectCode = '';
                    // }
                    // if ($scope.queryParams.subjectName === null) {
                    //     $scope.queryParams.subjectName = '';
                    // }
                    // if ($scope.queryParams.orgCode === null) {
                    //     $scope.queryParams.orgCode = '';
                    // }
                    // if ($scope.queryParams.orgName === null) {
                    //     $scope.queryParams.orgName = '';
                    // }
                    // if ($scope.queryParams.documentDate === null) {
                    //     $scope.queryParams.documentDate = '';
                    // }
                });
            }

            loadJournalEntryDataFromDB(1);
            if ($scope.criteriaList.length > 6) {
                $scope.criteriaListFirstRow = $scope.criteriaList.slice(0, 6);
                $scope.criteriaListSecondRow = $scope.criteriaList.slice(6, $scope.criteriaList.length);
            }
            else {
                $scope.criteriaListFirstRow = $scope.criteriaList.slice(0, $scope.criteriaList.length);
            }
            $('.filter-button').popover("hide");
        };

        //去掉所有的查询条件,重新load数据
        var doDataFilterReset = function () {
            $scope.queryParams = {
                pageInfo: {},
                periodStart: '',
                periodEnd: '',
                subjectCode: null,
                subjectName: null,
                orgCode: null,
                orgName: null,
                documentDate: null,
                projectId: vatSessionService.project.id
            };
            $scope.queryParams.periodStart = $scope.startMonth;
            $scope.queryParams.periodEnd = $scope.endMonth;
            loadJournalEntryDataFromDB(1);
            $('.filter-button').popover("hide");
        };

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

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

        //初始化时间控件
        var initDatePickers = function () {
            //认证开始时间
            var ele1 = $("#certificationDateStart");
            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.queryParams.certificationDateStart);
            //认证结束时间
            var ele2 = $("#certificationDateEnd");
            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.queryParams.certificationDateEnd);
        };

        var downloadJE = function () {
            citReportService.initExportDTData($scope.queryParams).success(function (data, status, headers) {
                if(status===204){
                    SweetAlert.warning("没有数据可以下载");
                    return;
                }
                vatExportService.exportToExcel(data, status, headers, 'A202000.xlsx');
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        };

        $scope.startCalculateData = function () {
            citReportService.generateDistributionTable($scope.queryParams).success(function (data) {
debugger;
                $scope.totalBusinessIncome = data.data.totalBusinessIncome;
                $scope.totalEmployeeRemuneration = data.data.totalEmployeeRemuneration;
                $scope.totalTotalAssets = data.data.totalTotalAssets;
                loadJournalEntryDataFromDB(1);
                // if(status===204){
                //     SweetAlert.warning("没有数据可以下载");
                //     return;
                // }
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
            });
        };

        (function initialize() {
            $log.debug('citDistributionTableController.ctor()...');
            $('#input-invoice-period-picker').focus(function () {
                $('.filter-button').popover("hide");
            });
            //初始化month-picker
            $('#input-invoice-period-picker').rangePicker({
                minDate: minDate,
                maxDate: maxDate,
                setDate: setDate,
                ConfirmBtnText: $translate.instant('Confirm'),
                CancelBtnText: $translate.instant('ButtonCancel')
            })
                .on('datePicker.done', function (e, result) {
                    //开始月份
                    var startMonth = result[0][1] * 100 + result[0][0];
                    //结束月份
                    var endMonth = result[1][1] * 100 + result[1][0];
                    $scope.startMonth = startMonth;
                    $scope.endMonth = endMonth;

                    $scope.queryParams.periodStart = startMonth;
                    $scope.queryParams.periodEnd = endMonth;
                    loadJournalEntryDataFromDB(1);
                });

            //格式化Grid
            $scope.gridOptions = {
                rowHeight: constant.UIGrid.rowHeight,
                showColumnFooter: true,
                selectionRowHeaderWidth: constant.UIGrid.rowHeight,
                // expandableRowTemplate: '<div ui-grid="row.entity.subGridOptions" style="height:150px;"></div>',
                virtualizationThreshold: 50,//默认加载50条数据,避免在数据展示时,只显示前面4条
                enableSorting: false,
                enableColumnMenus: false,
                enableHorizontalScrollbar : 1,
                columnDefs: [
                    { name: $translate.instant('TaxPayerNumber'), width: 250, cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.taxPayerNumber}}<span></div>' },
                    { name: $translate.instant('OrgName'), width: 350,cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.orgName}}<span></div>'
                        , footerCellTemplate: '<div class="ui-grid-cell-contents" translate="Subtotal"> </div>'},
                    { name: $translate.instant('BusinessIncome'), width: 200,cellTemplate: '<div class="ui-grid-cell-contents"><span >{{row.entity.businessIncome}}</span></div>'
                        , footerCellTemplate: '<div class="ui-grid-cell-contents">'+$scope.totalBusinessIncome+'</div>'},
                    { name: $translate.instant('EmployeeRemuneration'), width: 200,cellTemplate: '<div class="ui-grid-cell-contents"><span >{{row.entity.employeeRemuneration}}</span></div>'
                        , footerCellTemplate: '<div class="ui-grid-cell-contents">'+$scope.totalEmployeeRemuneration+'</div>'},
                    { name: $translate.instant('TotalAssets'), width: 200,cellTemplate: '<div class="ui-grid-cell-contents"><span >{{row.entity.totalAssets}}</span></div>'
                        , footerCellTemplate: '<div class="ui-grid-cell-contents">'+$scope.totalTotalAssets+'</div>'},
                    { name: $translate.instant('DistributionRatio'), width: 200,cellTemplate: '<div class="ui-grid-cell-contents"><span >{{row.entity.distributionRatio}}</span></div>'
                        , footerCellTemplate: '<div class="ui-grid-cell-contents"><span>100<span></div>'},
                    // { name: $translate.instant('DistributionAmount'), width: 200,cellTemplate: '<div class="ui-grid-cell-contents"><span >{{row.entity.distributionAmount}}</span></div>'
                    //     , footerCellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.orgName}}<span></div>'},
                    ]
            };

            $scope.doDataFilter = doDataFilter;
            $scope.doDataFilterReset = doDataFilterReset;
            $scope.prepareSummary = prepareSummary;
            $scope.showPopover = showPopover;
            $scope.downloadJE = downloadJE;

            initPeriods();
            initJournalEntryPagination();
            //初始化查询条件-期间范围
            $scope.queryParams.periodStart = vatSessionService.year * 100 + vatSessionService.month;
            $scope.queryParams.periodEnd = vatSessionService.year * 100 + vatSessionService.month;
            $scope.queryParams.organizationId = vatSessionService.project.organizationID;
            if($rootScope.currentLanguage === 'en-us'){
                $('.periodInput')[0].style.left = "280px";
            }else{
                $('.periodInput')[0].style.left = "150px";
            }
            loadJournalEntryDataFromDB(1);
        })();
    }
]);