vatModule.controller('vatTaxDifferenceController', ['$log', '$location','$q', '$scope', '$translate', '$compile', '$uibModal', 'vatPreviewService', 'vatDifferenceService', 'vatSessionService',
    function ($log, $location,$q ,$scope, $translate, $compile, $uibModal, vatPreviewService, vatDifferenceService, vatSessionService) {
        'use strict';
        $log.debug('vatTaxDifferenceController.ctor()...');
        //grid configuration
        $scope.grid = {
            differenceOptions: {
                height:'600px',
                bindingOptions: {
                    dataSource: 'differenceList'
                },
                keyExpr: "id",
                noDataText: $translate.instant('AccountVoucher_DataGrid_NoDataText'),
                parentIdExpr: "head_ID",
                expandedRowKeys: [1],
                showBorders: false,
                showColumnLines: false,
                showRowLines:false,
                columnAutoWidth: true,
                autoExpandAll:true,
                columns: [
                    { dataField: 'typeName', caption: $translate.instant('IncomeType') },
                    { dataField: 'description', caption: $translate.instant('Description') },
                    { dataField: 'amount', caption: $translate.instant('Amount'), format: { type: 'fixedPoint', precision: 2 } }
                ],
                selection: {
                    mode: "single"
                },
                onSelectionChanged: function (e) {
                    var row = e.selectedRowsData[0];
                    //row.clickType = 2;
                    if (row.clickType === 1) {                       
                        $location.path('/vat/generateReport/reportView?id=' + row.reportID + '&templateid=' + row.templateID +
                            '&name=本期销售情况明细(附表一)&templatecode=VAT001');
                        $location.url($location.path());
                    }
                    else if (row.clickType === 2) {
                        $scope.queryVoucherDto.listQueryCondition = [];
                        $scope.queryVoucherDto.listQueryCondition.push({ conditionName: "科目代码", searchKeyWord: "1", searchValue: row.typeName });
                        //显示凭证
                        //  getService.getVoucherList(row.name);
                        $scope.curVoucherItemPage = 1;
                        computeVoucherItemPage(false);
                        getService.voucherDataLoad($scope.curVoucherItemPage);
                        getService.showVoucherModal();
                    }
                },
                onRowPrepared: function (info) {
                    if (info.rowType != 'header') {
                        if (info.data.head_ID === "0") {
                            info.rowElement.addClass('top-category');
                        }
                    }

                }
            },
            reasonOptions: {
                height: '600px',
                bindingOptions: {
                    dataSource: 'reasonList'
                },
                keyExpr: "id",
                parentIdExpr: "head_ID",
                expandedRowKeys: [1],
                showBorders: false,
                showColumnLines: false,
                showRowLines: false,
                columnAutoWidth: true,
                autoExpandAll: true,
                columns: [
                    { dataField: 'name', caption: $translate.instant('DifferenceReason') },
                    { dataField: 'desc', caption: $translate.instant('Description') },
                    { dataField: 'amount', caption: $translate.instant('Amount'), format: { type: 'fixedPoint', precision: 2 } }
                ],
                onRowPrepared: function (info) {
                    if (info.rowType != 'header') {
                        if (info.data.head_ID==="0") {
                            info.rowElement.addClass('top-category');
                        }

                        if (info.data.id === 'total') {
                            info.rowElement.addClass('table-summary');
                        }
                    }

                }
              
            }
        };
        $scope.toggleAllMasterRows = function ($event) {
            var expand = "dx-datagrid-group-closed";
            var collapse = "dx-datagrid-group-opened";
            if ($($event.target).hasClass(expand)) {
                $scope.gridInstance.expandAll(-1);
                $($event.target).removeClass(expand);
                $($event.target).addClass(collapse);
            } else {
                $scope.gridInstance.collapseAll(-1);
                $($event.target).removeClass(collapse);
                $($event.target).addClass(expand);
            }
        };
        $scope.openSingularVoucher = function (date, period, group, vid) {
            var modalInstance = $uibModal.open({
                animation: false,
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                backdrop: "static",
                templateUrl: 'vat-preview-voucher-singular-voucher.html',
                scope: $scope,
                windowClass: "vat-preview-voucher-singular-voucher"
            });

            var singularVoucher = $scope.singularVoucher;
            singularVoucher.date = new Date(date).dateTimeToString("yyyyMMdd");
            singularVoucher.period = period;
            singularVoucher.group = group;
            singularVoucher.groupNum = vid;

            vatPreviewService.getVoucherByConditon($scope.queryVoucherDto.mainRelation, $scope.queryVoucherDto.allJe, period, vid, group, $scope.queryVoucherDto.listQueryCondition).success(function (data) {
                data.data.forEach(function (v) {
                    v.debit = PWC.round(v.debit, 2);
                    v.credit = PWC.round(v.credit, 2);
                });
                singularVoucher.dataList = data.data;
            });

            modalInstance.opened.then(function () {
                singularVoucher.gridColumns = angular.copy(singularVoucher.VOUCHER_COLUMNS);
            });

            singularVoucher.close = function () {
                modalInstance.dismiss('cancel');
            };
        };
        //计算页数,创建分页栏
        var computeVoucherItemPage = function (fristLoad) {

            if (!fristLoad) {
                vatPreviewService.voucherSelectAdvancedCount($scope.queryVoucherDto.mainRelation, $scope.queryVoucherDto.isEntryShow, $scope.queryVoucherDto.allJe, $scope.queryVoucherDto.listQueryCondition).success(function (data) {
                    if (data && !data.result&&data.resultMsg) {
                        SweetAlert.warning($translate.instant(data.resultMsg));
                        return false;
                    }
                    $scope.queryVoucherDto.pagingInfo.totalCount = data.data;

                    if ($scope.queryVoucherDto.pagingInfo && $scope.queryVoucherDto.pagingInfo.totalCount > 0) {

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

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

                        $('#totalVoucherPage').css('display', 'inline-block');
                    } else {
                        var createPage = $("#totalVoucherPage").createPage({
                            pageCount: 0,
                            current: $scope.curVoucherItemPage,
                            backFn: function (p) {
                                //单击回调方法,p是当前页码
                                getService.voucherDataLoad(p);
                            }
                        });

                        $('#totalVoucherPage').css('display', 'inline-block');
                    }
                });
            } else {
                var createPage = $("#totalVoucherPage").createPage({
                    pageCount: 0,
                    current: $scope.curVoucherItemPage,
                    backFn: function (p) {
                        //单击回调方法,p是当前页码
                        getService.voucherDataLoad(p);
                    }
                });

                $('#totalVoucherPage').css('display', 'inline-block');
            }
            return true;
        };
        $scope.queryVoucherDto = {
            mainRelation: '7',
            allJe: false,
            pagingInfo: {
                "totalCount": 0,
                "pageIndex": 1,
                "pageSize": 100
            },
            listQueryCondition: [],
            isEntryShow:false
        }; 

        var getService = {
            getDifferenceList: function () {
                vatDifferenceService.getTaxDifferenceList(vatSessionService.project.id, vatSessionService.month)
                .success(function (res) {
                    $scope.differenceList = res;
                })
                .error(function () {
                    alert("error");
                });
               
            },
            getReasonList: function () {
                $scope.reasonList = [
                    {
                        "id": "1", "head_ID": "0", "name": "预提未发放的折扣及赠料", "desc": "", "amount": 50639
                    },
                    {
                        "id": "1-1", "head_ID": "1", "name": "当前折扣净发生额", "desc": "", "amount": 50639
                    },
                    {
                        "id": "1-1-1", "head_ID": "1-1", "name": "61858.229840.88", "desc": "系统自动生成已实现折让", "amount": 50639
                    },
                    {
                        "id": "1-2", "head_ID": "1", "name": "当前赠料净发生额", "desc": "", "amount": 0
                    },
                    {
                        "id": "1-2-1", "head_ID": "1-2", "name": "61858.229840.55", "desc": "预提月末赠料", "amount": 0
                    },
                    {
                        "id": "1-3", "head_ID": "1", "name": "当期其他折扣/赠料净发生额", "desc": "", "amount": 0
                    },
                    {
                        "id": "1-3-1", "head_ID": "1-3", "name": "61858.229840.66", "desc": "预提系统自动生成未实现折让", "amount": 0
                    },
                    {
                        "id": "1-3-2", "head_ID": "1-3", "name": "61858.229840.77", "desc": "手工计算未实现折让", "amount": 0
                    },
                    {
                        "id": "1-3-3", "head_ID": "1-3", "name": "61858.229840.99", "desc": "手工计算已实现折让", "amount": 0
                    },
                    {
                        "id": "2", "head_ID": "0", "name": "延期付款利息(赊销)", "desc": "", "amount": -5999
                    },
                    {
                        "id": "2-1", "head_ID": "2", "name": "会计当月确认的延期付款利息", "desc": "", "amount": -5999
                    },
                    {
                        "id": "2-1-1", "head_ID": "2-1", "name": "61858.121201.03", "desc": "", "amount": -5999
                    },
                    {
                        "id": "3", "head_ID": "0", "name": "资产处置收入", "desc": "", "amount": -3
                    },
                    {
                        "id": "3-1", "head_ID": "3", "name": "固定资产处置收入", "desc": "", "amount": -3.39
                    },
                    {
                        "id": "3-1-1", "head_ID": "3-1", "name": "858013.793101.100", "desc": "固定资产清理收入", "amount": -3
                    },
                    {
                        "id": "3-1-2", "head_ID": "3-1", "name": "858013.486901.08", "desc": "固定资产清理收入-先按无收入处置再变卖", "amount": 0
                    },
                     {
                         "id": "4", "head_ID": "0", "name": "委贷利息", "desc": "", "amount": 5388
                     },
                    {
                        "id": "4-1", "head_ID": "4", "name": "会计当月确认的委贷利息", "desc": "", "amount": 23185
                    },
                    {
                        "id": "4-1-1", "head_ID": "4-1", "name": "858013.472902.01", "desc": "资金池收入", "amount": 24576
                    },
                    {
                        "id": "4-1-2", "head_ID": "4-1", "name": "剔除增值税", "desc": "", "amount": -1391
                    },
                     {
                         "id": "4-2", "head_ID": "4", "name": "本月税控系统开具发票的委贷利息收入", "desc": "", "amount": 28574
                     },
                    {
                        "id": "4-2-1", "head_ID": "4-2", "name": "6%税率(金融服务)", "desc": "", "amount": 28574
                    },
                    {
                        "id": "5", "head_ID": "0", "name": "其他(手工修改)", "desc": "", "amount": 0
                    },
                    {
                        "id": "5-1", "head_ID": "5", "name": "XXXXX", "desc": "", "amount": 0
                    },
                    {
                        "id": "total", "head_ID": "0", "name": "核对会计差异总计", "desc": "", "amount": 50025
                    },
                    {
                        "id": "not-recognize-total", "head_ID": "0", "name": "未识别税会差异", "desc": "", "amount": 0
                    }
                ];
            },
            voucherDataLoad: function ( pageIndex) {
                $scope.queryVoucherDto.pagingInfo.pageIndex = pageIndex;                
                vatDifferenceService.taxDifferenceByVoucher($scope.queryVoucherDto).success(function (listData) {
                    //listData.data.debitSum = PWC.round(listData.data.debitSum, 2);
                    //listData.data.creditSum = PWC.round(listData.data.creditSum, 2);
                    listData.data.voucherMainList.forEach(function (v) {
                        v.debitSum = PWC.round(v.debitSum, 2);
                        v.creditSum = PWC.round(v.creditSum, 2);
                    });
                    $scope.voucherDataList = listData.data.voucherMainList;
                    //var dataGrid = $('#gridContainer').dxDataGrid('instance');
                    //dataGrid.refresh();
                   // initDataGrid();
                    //vatPreviewService.getSelectWhereString($scope.queryVoucherDto.mainRelation, $scope.queryVoucherDto.allJe, $scope.queryVoucherDto.listQueryCondition).success(function (queryString) {
                    //    showVoucherCount(listData.data.itemIDCount, listData.data.vidCount, listData.data.debitSum, listData.data.creditSum, queryString);
                    //});
                    
                });
                computeVoucherItemPage(false);
            },
            showVoucherModal: function () {
                var modalInstance = $uibModal.open({
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'voucher.html',
                    scope: $scope,
                    backdrop: 'static',
                    windowClass: 'difference-modal'
                });

                $scope.cancel = function () {
                    modalInstance.dismiss('cancel');
                };

                //paintVoucherGrid();
            },
            getVoucherDataFromDatabase : function (mainRelation, allJe, period, vID, group, queryCondition) {
                var deferred = $q.defer();
                vatPreviewService.getVoucherByConditon(mainRelation, allJe, period, vID, group, queryCondition).success(function (dataList) {
                    deferred.resolve(dataList);

                }).error(function () {
                    deferred.reject();
                });
                return deferred.promise;
            }
        };
        var initData = function () {
            getService.getDifferenceList();
            getService.getReasonList();
        };
        $scope.datagridOptions = {
            height:'300px',
            bindingOptions: {
                dataSource: 'voucherDataList',
            },
            scrolling: {
                mode: "virtual"
            },
            sorting: {
                mode: "none"
            },
            selection: {
                mode: "single"
            },
            width:'98%',
            columnAutoWidth: true,
            showBorders: true,
            allowColumnResizing: true,
            showRowLines: true,
            showColumnLines: true,
            noDataText: $translate.instant('AccountVoucher_DataGrid_NoDataText'),
            columns: [
                {
                    dataField: "period",
                    caption: $translate.instant('AccountVoucher_DataGrid_ColPeriod'),
                    sortIndex: 0,
                    sortOrder: 'asc'
                    
                },
                {
                    alignment: "center",
                    dataField: "date",
                    dataType: "date",
                    caption: $translate.instant('AccountVoucher_DataGrid_ColDate'),
                    format: "yyyy-MM-dd",
                    sortIndex: 1,
                    sortOrder: 'asc'
                  
                },
                {
                    dataField: "group",
                    caption: $translate.instant('AccountVoucher_DataGrid_ColGroup'),
                    sortIndex: 2,
                    sortOrder: 'asc'                   
                },
                {
                    dataField: "vid",
                    caption: $translate.instant('AccountVoucher_DataGrid_ColVID'),
                    sortIndex: 3,
                    sortOrder: 'asc'                    
                },
                {
                    dataField: "debitSum",
                    caption: $translate.instant('AccountVoucher_DataGrid_ColDebitSum'),
                    alignment: "right"
                },
                {
                    dataField: "creditSum",
                    caption: $translate.instant('AccountVoucher_DataGrid_ColCreditSum'),
                    alignment: "right"
                }
            ],
            //onRowClick: function (e) {
            //    var component = e.component;
            //    var prevClickTime = component.lastClickTime;
            //    component.lastClickTime = new Date();
            //    if (prevClickTime && (component.lastClickTime - prevClickTime < 300)) {
            //        //Double click code                         
            //        $scope.openSingularVoucher(e.data.date, e.data.period, e.data.group, e.data.vid);
            //    }
            //},
            masterDetail: {
                enabled: true,
                template: function (container, options) {
                    var currentVoucherData = options.data;
                    $scope.queryVoucherDto.period = currentVoucherData.period;
                    $scope.queryVoucherDto.vID = currentVoucherData.vid;
                    $scope.queryVoucherDto.group = currentVoucherData.group;
                    container.addClass("internal-grid-container");
                    $("<div>")
                        .addClass("internal-grid")
                        .dxDataGrid({
                            columnAutoWidth: true,
                            loadPanel: {
                                enabled: false
                            },
                            showBorders: true,
                            sorting: {
                                mode: "none"
                            },
                            selection: {
                                mode: "single"
                            },
                            columns: [
                                {
                                    dataField: "summary",
                                    caption: $translate.instant('AccountVoucher_DataGrid_ColSummary')
                                   
                                },
                                //{
                                //    dataField: "customerCodeAndNameShow",
                                //    caption: $translate.instant('AccountVoucher_DataGrid_ColCustomerCodeAndNameShow') ,
                                //    //width: 170
                                //},
                                {
                                    dataField: "acctCodeAndNameShow",
                                    caption: $translate.instant('AccountVoucher_DataGrid_ColAcctCodeAndNameShow'),
                                    sortIndex: 1,
                                    sortOrder: 'asc'
                                },
                                {
                                    dataField: "stdCodeAndNameShow",
                                    caption: $translate.instant('AccountVoucher_DataGrid_ColStdCodeAndNameShow'),
                                    sortIndex: 0,
                                    sortOrder: 'asc'
                                },
                                {
                                    dataField: "debit",
                                    caption: $translate.instant('AccountVoucher_DataGrid_ColDebit'),
                                    alignment: "right"
                                },
                                {
                                    dataField: "credit",
                                    caption: $translate.instant('AccountVoucher_DataGrid_ColCredit'),
                                    alignment: "right"
                                }
                            ],
                            dataSource: {
                                store: new DevExpress.data.CustomStore({
                                    load: function (loadOptions) {
                                        return getService.getVoucherDataFromDatabase('7', false, currentVoucherData.period, currentVoucherData.vid, currentVoucherData.group, $scope.queryVoucherDto.listQueryCondition).then(function (data) {
                                            data.data.forEach(function (v) {
                                                v.debit = PWC.round(v.debit, 2);
                                                v.credit = PWC.round(v.credit, 2);
                                            });
                                            return {
                                                data: data.data,
                                                totalCount: data.data.length
                                            };
                                        }, function () {
                                            return $q.reject($translate.instant("DataLoadingError"));
                                        });
                                    }
                                })
                            }
                        }).appendTo(container);
                }
            },
            onCellPrepared: function (e) {
                if (e.rowType === "header" && $(e.cellElement).hasClass("dx-command-expand")) {
                    var btn = $("<div class='dx-datagrid-group-closed'></div>");
                    btn.attr("ng-click", "toggleAllMasterRows($event)");
                    e.cellElement.empty();
                    e.cellElement.append($compile(btn)($scope));
                }
            },
            onContentReady: function () {
                $log.debug("onContentReady voucher");
            },
            onInitialized: function (e) {
                $scope.gridInstance = e.component;
            }
        };
        (function () {
            initData();
            
        })();
    }
]);