vatModule.controller('vatBillDetailController', ['$scope', '$log', '$translate', '$timeout', 'SweetAlert', '$q',
    '$interval', 'dxDataGridService', '$http', 'apiConfig', 'vatSessionService',
    function ($scope, $log, $translate, $timeout, SweetAlert, $q, $interval, dxDataGridService, $http, apiConfig, vatSessionService) {
        'use strict';
        $log.debug('vatBillDetailController.ctor()...');

        //表格配置
        $scope.revenueGridOptions = $.extend(true, {}, dxDataGridService.BASIC_GRID_OPTIONS, {
            columns: [

                {
                    dataField: 'serialNo',
                    caption: $translate.instant('BillDtlColSerialNo'),
                    fixed: true,
                    allowHeaderFiltering: true, cellTemplate: function (container, options) {
                        try {
                            $("<span>" + (options.rowIndex + 1) + "</span>")
                                .appendTo(container);
                        } catch (e) {
                            $log.error(e);
                        }
                    }
                },
                {
                    dataField: 'subject',
                    caption: $translate.instant('BillDtlColSubject'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'customer',
                    caption: $translate.instant('BillDtlColCustCompany'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'billType',
                    caption: $translate.instant('BillDtlColType'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'billContent',
                    caption: $translate.instant('BillDtlColContent'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'billAmount',
                    caption: $translate.instant('BillDtlColAmount'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'billTaxRat',
                    caption: $translate.instant('BillDtlColTaxRate'),
                    fixed: true,
                    allowHeaderFiltering: true,
                    calculateCellValue: function (data) {
                        return (data.billTaxRat * 100) + '%';
                    }
                },
                {
                    dataField: 'billTaxAmount',
                    caption: $translate.instant('BillDtlColTaxAmount'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'oano',
                    caption: $translate.instant('BillDtlColOANo'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'department',
                    caption: $translate.instant('BillDtlColDepartment'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'billDate',
                    caption: $translate.instant('BillDtlColDate'),
                    fixed: true
                },
                {
                    dataField: 'billCode',
                    caption: $translate.instant('BillDtlColCode'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'billNumber',
                    caption: $translate.instant('BillDtlColNumber'),
                    fixed: true,
                    allowHeaderFiltering: true
                },
                {
                    dataField: 'revenueConfName',
                    caption: $translate.instant('BillDtlColRevenueType'),
                    fixed: true,
                    allowHeaderFiltering: true,
                    cellTemplate: function (container, options) {
                        try {
                            if (options.data.revenueConfName == null) {
                                $('<i class="fa fa-exclamation-circle fa-1x" style="color: yellow" aria-hidden="true "></i>&nbsp;&nbsp;')
                                    .appendTo(container);
                            } else {
                                $("<span>" + options.data.revenueConfName + "</span>")
                                    .appendTo(container);
                            }
                        } catch (e) {
                            $log.error(e);
                        }
                    }
                }, {
                    dataField: '',
                    caption: $translate.instant('BillDtlHandle'),
                    fixed: true,
                    width: '80px',
                    alignment: 'center',
                    cellTemplate: function (container, options) {
                        try {
                            if (options.data.revenueCofId) {
                                $('<i class="fa fa-pencil-square-o" style="cursor: pointer"></i>&nbsp;&nbsp;')
                                    .on('click', function () {
                                        $scope.editRevenue(options.data);
                                    }).appendTo(container);
                            }
                        } catch (e) {
                            $log.error(e);
                        }
                    }
                },
            ],
            bindingOptions: {
                dataSource: 'pageConfDataSource'
            }
        });


        //编辑
        $scope.editRevenue = function (data) {
            $scope.formParam = data;
            $('#editRevenueTypeDiv').modal('show');
        };

        //关闭配置框
        $scope.cancelModal = function () {
            $('#configForm')[0].reset();
        };

        $scope.initDatePicker = function () {
            var ele1 = $("#periodDatepicker");
            ele1.datepicker({
                todayHighlight: true,
                viewMode: "days",
                language: "zh-CN",
                startView: 'days',
                maxViewMode: 'years',
                minViewMode: 'days',
                orientation: "bottom",
                autoclose: true, //选中之后自动隐藏日期选择框
                clearBtn: true, //清除按钮
                todayBtn: false, //今日按钮
                format: $scope.dateFormat //日期格式,详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
            });
        };
        //刷新页面
        $scope.refreshGrid = function () {
            $scope.searchParam.projectId = vatSessionService.project.id;
            var month = vatSessionService.month < 10 ? ("0" + vatSessionService.month) : vatSessionService.month;
            $scope.searchParam.period = "" + vatSessionService.year + month;
            $scope.searchParam.queryDate = vatSessionService.year + "-" + month;
            $scope.searchParam.pageInfo = {
                pageIndex: $scope.pagingOptions.pageIndex,
                totalItems: $scope.pagingOptions.totalItems,
                pageSize: $scope.pagingOptions.pageSize
            };
            console.log('searchParam:' + JSON.stringify($scope.searchParam));
            $http.post('/billDetail/queryPage', $scope.searchParam, apiConfig.createVat())
                .success(function (res) {
                    if (res && res.list) {
                        $scope.pageConfDataSource = res.list;
                        $scope.pagingOptions.totalItems = res.pageInfo.totalCount;
                    } else {
                        SweetAlert.error($translate.instant('SystemError'));
                    }
                })
        };
        //搜索框的处理
        $scope.searchboxService = {

            showOrHideSearchBox: function () {
                $scope.hasShowMoreSearchBox = !$scope.hasShowMoreSearchBox;
            },
            search: function () {
                $scope.pagingOptions.pageIndex = 1;
                $scope.refreshGrid();
            },
            resetBox: function () {
                $scope.searchParam = {};
            }
        };
        $scope.revenueTypeAarry = [];
        $scope.editRevenueTypeAarry = [];
        $scope.getRevenueType = function () {
            var month = vatSessionService.month < 10 ? ("0" + vatSessionService.month) : vatSessionService.month;
            $http.post('/revenueConf/queryAll', {
                startDate: vatSessionService.year + "-" + month,
                endDate: vatSessionService.year + "-" + month,
                orgId: vatSessionService.project.organizationID
            }, apiConfig.createVat())
                .success(function (res) {
                    if (res) {
                        angular.forEach(res, function (d) {
                            $scope.revenueTypeAarry.push({'key': d.name, 'val': d.id});
                            $scope.editRevenueTypeAarry.push({'key': d.name, 'val': d.id});
                        })
                    } else {
                        SweetAlert.error($translate.instant('GetRevenueTypeError'));
                    }
                })
        };
        $scope.billTypeAarry = [];
        $scope.getBillType = function () {
            var month = vatSessionService.month < 10 ? ("0" + vatSessionService.month) : vatSessionService.month;
            var period = "" + vatSessionService.year + month;
            $http.post('/billDetail/queryBillTypeGroupBy?projectId=' + vatSessionService.project.id + '&period=' + period, {}, apiConfig.createVat())
                .success(function (res) {
                    if (res) {
                        angular.forEach(res, function (d) {
                            $scope.billTypeAarry.push({'key': d, 'val': d});
                        })
                    } else {
                        SweetAlert.error($translate.instant('GetRevenueTypeError'));
                    }
                })
        };
        //添加配置
        $scope.updateBillDetail = function () {
            $http.post('/billDetail/update', {
                id: $scope.formParam.id,
                revenueCofId: $scope.formParam.revenueCofId
            }, apiConfig.createVat())
                .success(function (res) {
                    if (res && 0 === res.code) {
                        SweetAlert.success($translate.instant('BillDtlUpdateSuccess'));
                        $scope.refreshGrid();
                        $('#editRevenueTypeDiv').modal('hide');
                    } else {
                        SweetAlert.error($translate.instant('SystemError'));
                    }
                })
        };
        (function initialize() {

            $scope.formParam = {};
            //日期
            $scope.dateFormat = $translate.instant('dateFormat4YearMonthDay');

            //分页的设置
            $scope.pagingOptions = {
                pageIndex: 1,  //当前页码
                totalItems: 0,  //总数据
                pageSize: 20  //每页多少条数据
            };

            $scope.hasShowMoreSearchBox = true;

            $scope.searchParam = {};
            $scope.editRevenueType = 0;
            $scope.searchOptions = {
                revenueTypeOptions: {
                    displayExpr: 'key',
                    valueExpr: 'val',
                    bindingOptions: {
                        value: 'searchParam.revenueCofId'
                    },
                    dataSource: $scope.revenueTypeAarry
                },
                editRevenueTypeOptions: {
                    displayExpr: 'key',
                    valueExpr: 'val',
                    bindingOptions: {
                        value: 'formParam.revenueCofId'
                    },
                    dataSource: $scope.editRevenueTypeAarry
                },
                billTypeOptions: {
                    displayExpr: 'key',
                    valueExpr: 'val',
                    bindingOptions: {
                        value: 'searchParam.billType'
                    },
                    dataSource: $scope.billTypeAarry
                },
                taxRateOptions: {
                    displayExpr: 'key',
                    valueExpr: 'val',
                    bindingOptions: {
                        value: 'searchParam.billTaxRat'
                    },
                    dataSource: [
                        {'key': '0%', 'val': 0},
                        {'key': '1.5%', 'val': 0.015},
                        {'key': '3%', 'val': 0.03},
                        {'key': '5%', 'val': 0.05},
                        {'key': '6%', 'val': 0.06},
                        {'key': '10%', 'val': 0.1},
                        {'key': '16%', 'val': 0.16},
                    ]
                }
            };

            function init() {
                $scope.getRevenueType();
                $scope.getBillType();
                $scope.refreshGrid();
                $scope.initDatePicker();
            }

            init()

        })();
    }
]);