vat-summary-dashboard.ctrl.js 26.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
vatDashboardModule.controller('SummaryDashboardController', ['$scope', '$log', '$translate', '$timeout', '$q', '$interval',
    'apiInterceptor', 'Upload', 'vatImportService', 'SweetAlert', 'uiGridConstants', 'vatSessionService', 'enums',
    'vatOperationLogService', 'projectService', 'vatCommonService', 'dashboardConfigSummaryService', 'modelConfigurationService',
    '$uibModal', 'canvasUtil','vatDashboardService',
    function ($scope, $log, $translate, $timeout, $q, $interval, apiInterceptor, Upload, vatImportService, SweetAlert,
        uiGridConstants, vatSessionService, enums, vatOperationLogService, projectService, vatCommonService,
        dashboardConfigSummaryService, modelConfigurationService, $uibModal, canvasUtil, vatDashboardService) {
        'use strict';

        var thisData = {


        };

        var thisConstant = {
            filterMonth: 'filterMonth',
            dateFormate: 'yyyy-MM',
            dashSignSeparator: '-',
            rowCountPerPage: 9,
            orgColumn: 'v1',
            prefixField: 'v',
            tableBeginXml: '<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="pct"/><w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/></w:tblPr><w:tblGrid>',
            tableEndXml: '</w:tbl>',
            tableColDefXml: '<w:gridCol w:w="2000"/>',
            tableColBeginXml: '</w:tblGrid><w:tr>',
            headerFirstCellBeginXml: '<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:tcBorders><w:bottom w:val="single" w:sz="12" w:space="0" w:color="A5A5A5" w:themeColor="accent3"/></w:tcBorders></w:tcPr><w:p><w:pPr><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:b/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr><w:t>',
            headerCellBeginXml: '<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:tcBorders><w:bottom w:val="single" w:sz="12" w:space="0" w:color="A5A5A5" w:themeColor="accent3"/></w:tcBorders></w:tcPr><w:p><w:pPr><w:jc w:val="right"/><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:b/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr><w:t>',
            headerCellEndXml: '</w:t></w:r></w:p></w:tc>',
            firstCellBeginXml: '<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:tcBorders><w:top w:val="single" w:sz="12" w:space="0" w:color="A5A5A5" w:themeColor="accent3"/><w:bottom w:val="single" w:sz="2" w:space="0" w:color="A5A5A5" w:themeColor="accent3"/></w:tcBorders></w:tcPr><w:p><w:pPr><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:b/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr><w:t>',
            cellBeginXml: '<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:tcBorders><w:top w:val="single" w:sz="12" w:space="0" w:color="A5A5A5" w:themeColor="accent3"/><w:bottom w:val="single" w:sz="2" w:space="0" w:color="A5A5A5" w:themeColor="accent3"/></w:tcBorders></w:tcPr><w:p><w:pPr><w:jc w:val="right"/><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体"/><w:color w:val="ED7D31" w:themeColor="accent2"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr><w:t>',
            rowBeginXml: '<w:tr>',
            rowEndXml: '</w:tr>',
            chartPrefix: 'chart-'
        };

        var thisDateService = {

            // 获取当前月份的上一个月时间
            getLastMonth: function () {
                var date = new Date();
                date.setMonth(date.getMonth() - 1);
                return date;
            },

            // 获取查询条件
            getQueryModel: function () {
                var arr = $scope.filterMonth.split(thisConstant.dashSignSeparator);
                var year = parseInt(arr[0]);
                var month = parseInt(arr[1]);

                var model = {
                    year: year,
                    period: month,
                    organizationIDList: $scope.selectedOrganizationList
                };

                return model;
            },

            // 验证有效月份
            validDateMonth: function () {
                var date = $scope.filterMonth + '-01';
                return window.PWC.checkDate(date);
            },

            // 转换为页面展示数据
            parseShowData: function (data) {
                if (data && data.length > 0) {
                    data.forEach(function (row) {
                        var values = _.values(row.header);
                        var keys = _.keys(row.header);
                        var length = keys ? keys.length : 0;
                        row.keys = keys;
                        row.headerObj = JSON.parse(row.headerObj);
                    });
                }

                return data;
            },

            // 查询汇总数据
            querySummaryProcess: function () {
                if (!thisDateService.validDateMonth) {
                    return;
                }

                var model = thisDateService.getQueryModel();
                vatSessionService.querySummayDashboardModel = model;
                dashboardConfigSummaryService.querySummaryData(model).success(function (data) {
                    // 进行数据转换
                    $scope.querySummaryResult = thisDateService.parseShowData(data);
                    var hasData = false;
                    if ($scope.querySummaryResult && $scope.querySummaryResult.length > 0) {
                        hasData = true;
                    }

                    $scope.hasData = hasData;

                    $timeout(function () {
                        thisDateService.drawTableList($scope.querySummaryResult);
                    }, 100);

                    // console.log(JSON.stringify($scope.querySummaryResult));
                });
            },

            drawTableList: function (data) {
                if (data && data.length > 0) {
                    data.forEach(function (row) {
                        thisDateService.drawTable(row);
                    });
                }
            },

            drawTable: function (node) {
                if (_.isEmpty(node.data)) {
                    node.isEmpty = true;
                }
                else {
                    node.isEmpty = false;
                    var vatGallery = thisDateService.createGalleryData(node);

                    var itemTemplate = function (item, index) {
                        var columns = thisDateService.createColumns(node);

                        return $('<div class="gallery-table"/>').dxDataGrid({
                            dataSource: item.dataValue,
                            width: '100%',
                            showRowLines: true,
                            showColumnLines: false,
                            noDataText: '',
                            cellHintEnabled: true,
                            showBorders: false,
                            format: { type: 'fixedPoint', precision: 2 },
                            columns: columns
                        });

                    };
                    var galleryWidget = $("#" + node.id).dxGallery({
                        dataSource: vatGallery,
                        // height: 260,
                        width: "458px",
                        loop: false,
                        showIndicator: true,
                        noDataText: '',
                        showNavButtons: true,
                        itemTemplate: itemTemplate,

                    }).dxGallery("instance");
                }
            },
            // 构造GalleryData
            createGalleryData: function (node) {

                var index = Math.ceil(node.data.length / thisConstant.rowCountPerPage);
                // var x = node.data.length % thisConstant.rowCountPerPage;
                // if (x !== 0) {
                //     index = index + 1;
                // }

                var result = [];
                for (var i = 0; i < index; i++) {
                    var item = {};
                    item.id = i;
                    item.dataValue = [];
                    var start = i * thisConstant.rowCountPerPage;
                    for (var j = start; j < start + thisConstant.rowCountPerPage; j++) {
                        var rowData = angular.copy(node.data[j]);
                        if (!rowData) {
                            continue;
                        }

                        for (var k = 1; k < node.headerObj.length; k++) {
                            var dataModel = node.headerObj[k];
                            var field = thisConstant.prefixField + (k + 1);
                            if (dataModel.dataType === 1) {
                                rowData[field] = Number(rowData[field]).formatAmount();

                            } else if (dataModel.dataType === 3) {
                                rowData[field] = rowData[field] == 1 ? '是' : '否';
                            }
                            else {
                                var percentData = Number(rowData[field]) * 100;
                                rowData[field] = Number(percentData).formatAmount() + '%';
                            }
                        }
                        item.dataValue.push(rowData);
                    }

                    result.push(item);
                }

                return result;
            },

            // 构造列表
            createColumns: function (node) {
                var result = [];
                node.keys.forEach(function (key) {
                    var item = {};
                    item.dataField = key;
                    if (key === thisConstant.orgColumn) {
                        item.caption = $translate.instant('EntityName');
                    }
                    else {
                        item.format = { type: 'fixedPoint' };
                        item.cssClass = 'orange-color';
                        item.alignment = 'right';
                        item.caption = _.isEmpty(node.header[key]) ? key : node.header[key];
                    }

                    result.push(item);
                });

                return result;
            },

            isChangedArray: function (newValue, oldValue) {
                if (!newValue && !oldValue) {
                    return false;
                }

                if (!newValue) {
                    return true;
                }

                if (!oldValue) {
                    return true;
                }

                if (newValue.length !== oldValue.length) {
                    return true;
                }

                // 排序
                newValue = newValue.sort();
                oldValue = oldValue.sort();

                for (var i = 0; i < newValue.length; i++) {
                    if (newValue[i] !== oldValue[i]) {
                        return true;
                    }
                }

                return false;
            },
            querySummary: function (queryModel) {

                if (thisDateService.isChangedArray(queryModel, $scope.selectedOrganizationList)) {

                    $scope.selectedOrganizationList = queryModel;

                    var newValue = queryModel;

                    var model = thisDateService.getQueryModel();
                    if ($scope.hasCheckedDirtyData) {
                        thisDateService.querySummaryProcess();
                    }

                    if (!$scope.hasCheckedDirtyData) {
                        modelConfigurationService.organizationsHasDirtyData(newValue.join(','), model.year, 2).success(function (result) {
                            if (result) {
                                SweetAlert.swal({
                                    title: $translate.instant('OrganizationsHasDirtyData'),
                                    text: '',
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonColor: "#DD6B55",
                                    confirmButtonText: $translate.instant('Confirm'),
                                    cancelButtonText: $translate.instant('Cancel'),
                                    closeOnConfirm: true
                                }, function (isConfirm) {
                                    if (isConfirm) {

                                        var parentElem = angular.element($('#organizationDirtyProcessBarContainer'));
                                        $scope.processBarModalInstance = $uibModal.open({
                                            ariaLabelledBy: 'modal-title',
                                            ariaDescribedBy: 'modal-body',
                                            templateUrl: 'dirtyDataProcessBar.html',
                                            windowClass: 'data-table',
                                            appendTo: parentElem,
                                            backdrop: 'static',
                                            scope: $scope
                                        });

                                        $scope.intervalId = setInterval(timer, 50);

                                        //重新计算模型数据
                                        modelConfigurationService.updateOrganizationsModelDirtyData(newValue.join(','), model.year, 2).success(function () {
                                            $scope.hasCheckedFinished = true;
                                        });
                                    } else {
                                        thisDateService.querySummaryProcess();
                                    }
                                });
                            } else {
                                thisDateService.querySummaryProcess();
                            }
                        });
                        $scope.hasCheckedDirtyData = true;
                    }

                }
            },

            toggleChart: function ($event, node) {
                var target = $event.target;
                node.isShowChart = !node.isShowChart;
            }
        };

        $scope.progressBarValue = 0;
        $scope.processBarModalInstance = null;
        $scope.intervalId = null;

        function timer() {
            $scope.$apply(function () {
                $scope.progressBarValue++;
                if (!$scope.hasCheckedFinished) {
                    $scope.processBarMax++;
                }
            });
        }

        $scope.processBarMax = 100;
        $scope.hasCheckedFinished = false;
        $scope.progressBarOptions = {
            min: 0,
            width: "95%",
            bindingOptions: {
                value: 'progressBarValue',
                max: 'processBarMax'
            },
            statusFormat: function (value) {
                return "计算进度: " + (value * 100).toFixed(0) + "%";
            },
            onComplete: function (e) {
                //重新计算模型数据结束后加载图表。
                thisDateService.querySummaryProcess();
            }
        };

        $scope.hasCheckedDirtyData = false;

        var mainModule = {

            // 初始化参数
            initParams: function () {
                $scope.selectedOrganizationList = [];
                $scope.hasData = true;
                mainModule.initFilterMonth();

                mainModule.watchFilter();
            },

            // 初始化查询月份
            initFilterMonth: function () {

                var lastmonth = thisDateService.getLastMonth();

                $scope.filterMonth = lastmonth.formatDateTime(thisConstant.dateFormate);;

                var elem1 = $("#" + thisConstant.filterMonth);
                elem1.datepicker({
                    minViewMode: 1,
                    autoclose: true,
                    language: "zh-CN",
                    format: "yyyy-mm",
                });

                elem1.datepicker('setDate', lastmonth);
            },

            // 监视查询条件变更
            watchFilter: function () {

                // 机构选择改变时
                // $scope.$watch('selectedOrganizationList', function(newValue, oldValue) {
                //     // console.log(newValue.join(',') + '-' + $scope.filterMonth);
                //     if (thisDateService.isChangedArray(newValue, oldValue)) {
                //         var model = thisDateService.getQueryModel();
                //         if ($scope.hasCheckedDirtyData) {
                //             thisDateService.querySummaryProcess();
                //         }

                //         if (!$scope.hasCheckedDirtyData) {
                //             modelConfigurationService.organizationsHasDirtyData(newValue.join(','), model.year, 2).success(function(result) {
                //                 if (result) {
                //                     SweetAlert.swal({
                //                         title: $translate.instant('OrganizationsHasDirtyData'),
                //                         text: '',
                //                         type: "warning",
                //                         showCancelButton: true,
                //                         confirmButtonColor: "#DD6B55",
                //                         confirmButtonText: $translate.instant('Confirm'),
                //                         cancelButtonText: $translate.instant('Cancel'),
                //                         closeOnConfirm: true
                //                     }, function(isConfirm) {
                //                         if (isConfirm) {

                //                             var parentElem = angular.element($('#organizationDirtyProcessBarContainer'));
                //                             $scope.processBarModalInstance = $uibModal.open({
                //                                 ariaLabelledBy: 'modal-title',
                //                                 ariaDescribedBy: 'modal-body',
                //                                 templateUrl: 'dirtyDataProcessBar.html',
                //                                 windowClass: 'data-table',
                //                                 appendTo: parentElem,
                //                                 backdrop: 'static',
                //                                 scope: $scope
                //                             });

                //                             $scope.intervalId = setInterval(timer, 50);

                //                             //重新计算模型数据
                //                             modelConfigurationService.updateOrganizationsModelDirtyData(newValue.join(','), model.year, 2).success(function() {
                //                                 $scope.hasCheckedFinished = true;
                //                             });
                //                         } else {
                //                             thisDateService.querySummaryProcess();
                //                         }
                //                     });
                //                 } else {
                //                     thisDateService.querySummaryProcess();
                //                 }
                //             });
                //             $scope.hasCheckedDirtyData = true;
                //         }


                //     }
                // });

                // 日期选择改变时
                $scope.$watch('filterMonth', function (newValue, oldValue) {
                    // console.log($scope.selectedOrganizationList.join(',') + '-' + $scope.filterMonth);
                    if (newValue !== oldValue) {
                        thisDateService.querySummaryProcess();
                    }
                });
            },

            // 入口函数
            main: function () {
                mainModule.initParams();
            },

            loadFile: function (url, callback) {
                JSZipUtils.getBinaryContent(url, callback);
            },

            generateDoc: function (doc) {
                var tableContent = thisConstant.tableBeginXml;
                var colNum = doc.keys.length;
                var rowNum = doc.data.length;
                for (var i = 0; i < colNum; i++) {
                    tableContent += thisConstant.tableColDefXml;
                }

                tableContent += thisConstant.tableColBeginXml;

                for (var i = 0; i < colNum; i++) {
                    tableContent = tableContent
                        + (i === 0 ? thisConstant.headerFirstCellBeginXml : thisConstant.headerCellBeginXml)
                        + doc.header[doc.keys[i]] + thisConstant.headerCellEndXml;
                }

                tableContent += thisConstant.rowEndXml;

                for (var j = 0; j < rowNum; j++) {
                    tableContent += thisConstant.rowBeginXml;

                    for (var i = 0; i < colNum; i++) {
                        var dataModel = doc.headerObj[i];
                        var data = doc.data[j][doc.keys[i]];
                        if (i > 0) {
                            if (dataModel.dataType === 1) {
                                data = Number(data).formatAmount();

                            } else if (dataModel.dataType === 3) {
                                data = data == 1 ? '是' : '否';
                            }
                            else {
                                var percentData = Number(data) * 100;
                                data = Number(percentData).formatAmount() + '%';
                            }
                        }

                        if (i === 0) {
                            tableContent = tableContent + thisConstant.firstCellBeginXml
                                + data + thisConstant.headerCellEndXml;
                        }
                        else {
                            tableContent = tableContent + thisConstant.cellBeginXml
                                + data + thisConstant.headerCellEndXml;
                        }
                    }

                    tableContent += thisConstant.rowEndXml;
                }

                tableContent += thisConstant.tableEndXml;

                return {
                    chartName: doc.name,
                    chartContent: thisConstant.chartPrefix + doc.id,
                    riskTip: _.isArray(doc.modelTips) ? doc.modelTips : [],
                    tableContent: tableContent
                };
            },

            generateDocImages: function () {
                var opts = {
                    centered: true,
                    getImage: function (tagValue, tagName) {
                        return canvasUtil.toBinaryData(document.getElementById(tagValue));
                    },
                    getSize: function (img, tagValue, tagName) {
                        return [550, 250];
                    }
                }

                var imageModule = new ImageModule(opts);
                return imageModule;
            },

            exportChart: function (chart) {
                var exportModel = mainModule.generateDoc(chart);

                var exportDocName = chart.name + '.docx';
                var templateName = '/ExportTemplate/DashboardExportTemplate.docx';

                mainModule.loadFile(templateName + '?_=' + Math.random(), function (err, content) {
                    if (err) { throw e };
                    var zip = new JSZip2(content);
                    var imageModule = mainModule.generateDocImages();
                    var doc = new docxtemplater().attachModule(imageModule).loadZip(zip);
                    doc.setData(exportModel);
                    try {
                        doc.render();
                    }
                    catch (err) {
                        $log.info(err);
                        swal({
                            title: '导出发生一个错误,请重试',
                            confirmButtonColor: "#dc6000",
                            confirmButtonText: "确定",
                            closeOnConfirm: true,
                            type: "error"
                        });
                        return;
                    }

                    var out = doc.getZip().generate({
                        type: "blob",
                        mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    });
                    saveAs(out, exportDocName);
                })
            }
        };

        //删除图表
        $scope.deleteChartConfig = function (id) {
            SweetAlert.swal({
                title: $translate.instant('ConfirmDelete'),
                text: $translate.instant('deleteChart') + "?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: true
            }, function (isConfirm) {
                if (isConfirm) {
                    vatDashboardService.deleteChartConfig(id).success(function () {
                        SweetAlert.success($translate.instant('DeleteSuccess'));
                        thisDateService.querySummaryProcess();
                    });
                }
            });
        };

        //重新计算模型完成时执行
        $scope.$watch('progressBarValue', function (newValue) {
            if (newValue == $scope.processBarMax) {
                $scope.processBarModalInstance.dismiss({ $value: 'cancel' });
                clearInterval($scope.intervalId);
            }
        });
     
        //开始
        (function initialize() {
            $log.debug('SummaryDashboardController.ctor()...');
            console.log('SummaryDashboardController');
            $scope.querySummary = thisDateService.querySummary;
            $scope.exportChart = mainModule.exportChart;
            $scope.toggleChart = thisDateService.toggleChart;
            mainModule.main();         
        })();
    }
]);