frameworkModule.controller('appSummaryController', ['$scope', '$log', '$state', '$translate', 'region', 'projectService', 'vatSessionService',
    'enums', 'citSessionService', 'vatReportService', 'tempStorageService', 'SweetAlert',
function ($scope, $log, $state, $translate, region, projectService, vatSessionService, enums, citSessionService, vatReportService, tempStorageService,
    SweetAlert) {

        // For Edmond: Dashboard Demo
        vatSessionService.querySummayDashboardModel = {
            year: 2017,
            period: 1
        };

        $scope.goToRiskPanel = function () {
            window.location = '/#/RiskPanel';
        }

        $scope.initCitDataProcessMockData = function () {
            var task = function (id, status, name, tasklevel, parentId, hasButton, seqNo) {
                this.id = id;
                this.name = _.isEmpty(name) ? $translate.instant(id) : name;
                this.status = status;
                this.text = $translate.instant(status);
                this.tasklevel = tasklevel;
                this.parentId = parentId;
                this.hasButton = hasButton;
                this.ngClassCol = '';
                this.seqNo = seqNo;
            };

            var result = [];
            result.push(new task(1, constant.DataProccessStatus.ToUpdate, $translate.instant('DataProcessDataName_UpdateTB'), 1, 0, true, 1));
            result.push(new task(2, constant.DataProccessStatus.Unstarted, $translate.instant('DataProcessDataName_GenerateReport'), 1, 0, false, 2));
            result.push(new task(3, constant.DataProccessStatus.ToUpdate, $translate.instant('DataProcessDataName_FinanceReport'), 2, 2, true, 3));
            result.push(new task(4, constant.DataProccessStatus.Unstarted, $translate.instant('DataProcessDataName_CITQuarterly'), 2, 2, false, 4));
            result.push(new task(5, constant.DataProccessStatus.Completed, $translate.instant('DataProcessDataName_CITFirstQuarterly'), 3, 4, true, 5));
            result.push(new task(6, constant.DataProccessStatus.Unstarted, $translate.instant('DataProcessDataName_CITSecondQuarterly'), 3, 4, true, 5));
            result.push(new task(7, constant.DataProccessStatus.NoData, $translate.instant('DataProcessDataName_CITThirdQuarterly'), 3, 4, true, 5));
            result.push(new task(8, constant.DataProccessStatus.NoData, $translate.instant('DataProcessDataName_CITForthQuarterly'), 3, 4, true, 5));
            result.push(new task(9, constant.DataProccessStatus.Unstarted, $translate.instant('DataProcessDataName_YearWorkPaper'), 2, 2, true, 6));
            result.push(new task(10, constant.DataProccessStatus.Unstarted, $translate.instant('DataProcessDataName_AnnualSettlement'), 2, 2, true, 7));
            result.push(new task(11, constant.DataProccessStatus.Completed, $translate.instant('DataProcessDataName_ModelAnalysis'), 1, 0, true, 8));
            return result;
        };

        $scope.dashboardOptions = {
            widgetButtons: false,
            widgetDefinitions: [
                {
                    name: 'ToDoList',
                    title: 'ToDoList',
                    directive: 'app-todo-list',
                    dataAttrName: 'items',
                    dataModelType: 'TodoListDataModel',
                    dataModelOptions: {
                    },
                    settingsModalOptions: {
                        templateUrl: "/app/dashboard/app-todo-list/config/config.html",
                        controller: "appTodoListConfigController",
                        backdrop: false
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("Todo list config resolved!");
                        $.extend(true, widget, result);
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("Todo list config have been dismissed: ", reason);
                    },
                    enableVerticalResize: false,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-4 col-lg-4',
                        height: '210px'
                    }
                },
                {
                    name: 'IndexAnalysis',
                    title: 'IndexAnalysis',
                    directive: 'app-index-analysis',
                    dataAttrName: 'chartConfig',
                    dataModelType: 'ChartConfigDataModel',
                    dataModelOptions: {
                        chartConfig: {}
                    },
                    settingsModalOptions: {
                        templateUrl: "app/dashboard/app-index-analysis/app-index-analysis-config.html",
                        controller: "appIndexAnalysisConfigController",
                        backdrop: false,
                        windowClass: 'index-analysis-config-modal'
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("Index analysis chart config resolved!");
                        $.extend(true, widget, result);
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("Index analysis chart config have been dismissed: ", reason);
                    },
                    titleAttr: 'chartConfig.name',
                    enableVerticalResize: false,
                    openConfigWhenAdding: true,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-12 col-lg-12',
                    }
                },
                {
                    name: 'TaxSummaryDashboard',
                    title: 'DashboardOTSubtotal',
                    directive: 'tax-summary-dashboard',
                    dataAttrName: 'tax-summary-dashboard',
                    dataModelOptions: {
                        name: "tax-summary-dashboard option data"
                    },
                    settingsModalOptions: {
                        templateUrl: "app/common/controls/tax-summary-dashboard/config/config.html",
                        controller: "taxSummaryDashboardConfigController",
                        backdrop: false
                    },
                    enableVerticalResize: false,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-12 col-lg-12',
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("TaxSummaryDashboard config resolved!");
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("TaxSummaryDashboard config have been dismissed: ", reason);
                    }
                },
                {
                    name: 'TaxAmountDashboard',
                    title: 'TaxAmountDashboard',
                    directive: 'tax-amount-dashboard',
                    dataAttrName: 'tax-amount-dashboard',
                    dataModelOptions: {
                        name: "taxAmountDashboard"
                    },
                    settingsModalOptions: {
                        templateUrl: "app/common/controls/tax-amount-dashboard/config/config.html",
                        controller: "taxAmountDashboardConfigController",
                        backdrop: false
                    },
                    enableVerticalResize: false,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-4 col-lg-4',
                        height: '210px'
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("TaxAmountDashboard config resolved!");
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("TaxAmountDashboard config have been dismissed: ", reason);
                    }
                },
                {
                    name: 'TaxAnnualAmountDashboard',
                    title: 'TaxAnnualAmountDashboard',
                    directive: 'tax-annual-amount-dashboard',
                    dataAttrName: 'tax-annual-amount-dashboard',
                    dataModelOptions: {
                        name: "taxAnnualAmountDashboard"
                    },
                    enableVerticalResize: false,
                    hideWidgetSettings: true,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-4 col-lg-4',
                        height: '210px'
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("TaxAnnualAmountDashboard config resolved!");
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("TaxAnnualAmountDashboard config have been dismissed: ", reason);
                    }
                },
                {
                    name: 'DashboardTaxRiskAlert',
                    title: 'MenuRiskAlert',
                    directive: 'dashboard-tax-risk-alert',
                    dataAttrName: 'dashboard-tax-risk-alert',
                    dataModelOptions: {
                        name: "dashboardTaxRiskAlert option data"
                    },
                    enableVerticalResize: false,
                    hideWidgetSettings: true,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-12 col-lg-12',
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("DashboardTaxRiskAlert config resolved!");
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("DashboardTaxRiskAlert config have been dismissed: ", reason);
                    }
                },
                {
                    name: 'DashboardTaxCashFlowAnalysis',
                    title: 'TaxCashFlowAnalysis',
                    directive: 'dashboard-tax-cash-flow-analysis',
                    dataAttrName: 'dashboard-tax-cash-flow-analysis',
                    dataModelOptions: {
                        name: "dashboardTaxCashFlowAnalysis option data"
                    },
                    settingsModalOptions: {
                        templateUrl: "/app/dashboard/tax-cash-flow-analysis/config/config.html",
                        controller: "dashboardTaxCashFlowAnalysisConfigController",
                        backdrop: false,
                        size: "dashboard-tax-cash-flow-analysis-config"
                    },
                    enableVerticalResize: false,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-12 col-lg-12',
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("DashboardTaxCashFlowAnalysis config resolved!");
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("DashboardTaxCashFlowAnalysis config have been dismissed: ", reason);
                    }
                },
                {
                    name: 'DashboardDeferredTaxAnalysis',
                    title: 'DeferredTaxAnalysis',
                    directive: 'dashboard-deferred-tax-analysis',
                    dataAttrName: 'chartConfig',
                    dataModelType: 'ChartConfigDataModel',
                    dataModelOptions: {
                        chartConfig: {}
                    },
                    settingsModalOptions: {
                        templateUrl: "/app/dashboard/deferred-tax-analysis/config/config.html",
                        controller: "dashboardDeferredTaxAnalysisConfigController",
                        backdrop: false,
                        size: "dashboard-deferred-tax-analysis-config"
                    },
                    enableVerticalResize: false,
                    openConfigWhenAdding: true,
                    size: {
                        widthClass: 'col-xs-12 col-sm-12 col-md-12 col-lg-12',
                    },
                    onSettingsClose: function (result, widget) {
                        $log.debug("DashboardDeferredTaxAnalysis config resolved!");
                        $.extend(true, widget, result);
                    },
                    onSettingsDismiss: function (reason, scope) {
                        $log.debug("DashboardDeferredTaxAnalysis config have been dismissed: ", reason);
                    }
                }
            ],
            defaultWidgets: [
                {
                    name: 'TaxAnnualAmountDashboard'
                },
                {
                    name: 'TaxAmountDashboard'
                },
                {
                    name: 'ToDoList'
                },
                {
                    name: 'TaxSummaryDashboard'
                }
            ],
            storage: {
                getItem: function (key) {
                    return tempStorageService.getTempStorage('admin', 'dashboard,' + key).then(function (rslt) {
                        return rslt && rslt.data;
                    });
                },
                setItem: function (key, value) {
                    return tempStorageService.setTempStorage('admin', 'dashboard,' + key, value);
                },
                removeItem: function (key) {
                    return tempStorageService.removeTempStorage('admin', 'dashboard,' + key);
                }
            },
            storageId: 'atmsDashboard',
            explicitSave: true
        };

        var projects = [];
        //点击区域的箭头图标,进入 YP_Demo机构 CIT项目的数据分析界面
        //http://cnshaappuwv023:30000/#/cit/analyzeReport/citModelAnalysis
        $scope.goCITAnalysis = function () {
            var project = _.findWhere(projects, {
                serviceTypeID: enums.serviceType.CIT,
                id: "8d8b13e7-07e1-4d84-8984-7b86e8ec6137"
            });
            if (project) {
                if (project.haveCreateProject) {
                    vatSessionService.project = project;
                    //写死1月份
                    vatSessionService.month = 1;
                    if (_.isUndefined(project.projectStatusList[vatSessionService.month])) { //如果当前期间还没有导入任何数据的话,就添加一条未开始状态的记录
                        projectService.setProjectStatus(project.id, vatSessionService.month, constant.ProjectStatusEnum.UnStarted)
                                .success(function (or) {
                                    if (or.result) {
                                        //添加完成后,在vatSessionService.project中添加新加入的数据
                                        project.projectStatusList[vatSessionService.month] = constant.ProjectStatusEnum.UnStarted;
                                        vatSessionService.project = project;
                                        if (project.serviceTypeID === enums.serviceType.CIT) {
                                            citSessionService.project = project;
                                            $state.go('cit.analyzeReport.citModelAnalysis');
                                        }
                                        else {
                                            //!!请把goRightPath()放在最内层的callback中,否则会在当前service没有执行完毕前就跳转到vat-layout.ctrl.js,
                                            //从而造成一些bug
                                            //  goRightPath();
                                        }
                                    }
                                });
                    }
                    else {
                       
                        if (project.serviceTypeID === enums.serviceType.CIT) {
                            citSessionService.project = project;
                            $state.go('cit.analyzeReport.citModelAnalysis');
                        }
                        else {
                            // goRightPath();
                        }
                    }
                }
            }

        };
        $scope.getYPDemoProjects = function () {
            //YP_Demo机构(2017) project 
            var index = 0;
            projectService.getProjectByID("8d8b13e7-07e1-4d84-8984-7b86e8ec6137").success(function (ps) {
                if (ps && ps.length > 0) {
                    ps.forEach(function (p) {
                        projects.push({
                            index: index++,
                            id: p.id,
                            name: p.name,
                            year: p.year,
                            code: p.code,
                            clientCode: p.clientCode,
                            isActive: p.isActive,
                            createTime: p.createTime,
                            updateTime: p.updateTime,
                            regionID: p.regionID,
                            industryID: p.industryID,
                            ruleType: p.ruleType,
                            organizationID: p.organizationID,
                            dbName: p.dbName,
                            serviceTypeID: p.serviceTypeID,
                            region: p.region,

                            haveCreateProject: p.haveCreateProject,
                            //yearDisplay: $scope.getYearDisplay(p),
                            // projectStatusDisplay: $scope.translateProjectStatus(p.haveCreateProject),
                            //serviceIcon: $scope.getServiceIcon(p.serviceTypeID),
                            //color: $scope.getColor(p.serviceTypeID),
                            organizationName: p.organizationName,
                            serviceTypeName: p.serviceTypeID === enums.serviceType.VAT ? "增值税" : "企业所得税",
                            industryName: p.industryName,
                            enterpriseAccountSetID: p.enterpriseAccountSetID,
                            templateGroupID: p.templateGroupID,
                            startPeriod: p.startPeriod,
                            endPeriod: p.endPeriod,
                            projectStatusList: p.projectStatusList, //Dictionary<int,int>类型,存放当前项目每个期间的状态的。第一个int:期间,第二个int:状态
                            importSubStatus: null, //当前项目,当前期间的子状态(是否导入Tb,序时账等等)     
                            workflow: null, //当前项目workflow数据
                            regionName: p.regionName,
                            //finalStatus: setLayoutStatusTitle(null), //(p.projectStatusList !== null && p.projectStatusList[1] !== undefined) ? setLayoutStatusTitle(p.projectStatusList[1]) : $scope.translateProjectStatus(p.haveCreateProject)
                            taxAmount: 0,
                            prepadidTaxAmount: 0,
                            taxRate: 0,
                            periodDate: (p.serviceTypeID === enums.serviceType.VAT) ? ($scope.currentSelectedYear + "." + $scope.currentSelectedMonth) : ($scope.currentSelectedYear + ""),
                            modelAbnormal: false,
                            riskWarning: false,
                            reportAbnormal: false,
                            citDataProcessMockData: $scope.initCitDataProcessMockData()
                        });
                    });
                }
            }).error(function () {
                SweetAlert.error('', $translate.instant("CommonFail"));
            });
        };
       // 点击机构的, 报表感叹号, 进入 YP_Demo机构 VAT项目的1月的纳税申报表附表一界面
        // http://cnshaappuwv023:30000/#/vat/generateReport/reportView?
        //id=0f221d2e-3a85-4d99-9bfa-8480fb97473b
        //&templateid=305158ab-4d07-4e10-bd14-560b3e30a53d
        //&name=%E6%9C%AC%E6%9C%9F%E9%94%80%E5%94%AE%E6%83%85%E5%86%B5%E6%98%8E%E7%BB%86(%E9%99%84%E8%A1%A8%E4%B8%80)
        //&templatecode=VAT001
        $scope.goVATSpecialReport = function () {
            var project = _.findWhere(projects, {
                serviceTypeID: enums.serviceType.VAT,
                id: "8d8b13e7-07e1-4d84-8984-7b86e8ec6137"
            });
            if (project) {
                if (project.haveCreateProject) {
                    //写死1月份
                    vatSessionService.month = 1;
                    vatSessionService.project = project;
                    //获取最新Vat001的report
                    vatReportService.getTemplate(project.id, vatSessionService.month).success(function (response) {
                        //  console.log(response);
                        if(response.result){
                            var reportData = _.findWhere(response.data, { templateCode: "VAT001"});
                            var param = {
                                id: reportData.id,
                                templateid: reportData.templateID,
                                name: reportData.templateName,
                                templatecode: reportData.templateCode
                            };
                            if (_.isUndefined(project.projectStatusList[vatSessionService.month])) { //如果当前期间还没有导入任何数据的话,就添加一条未开始状态的记录
                                projectService.setProjectStatus(project.id, vatSessionService.month, constant.ProjectStatusEnum.UnStarted)
                                        .success(function (or) {
                                            if (or.result) {
                                                //添加完成后,在vatSessionService.project中添加新加入的数据
                                                project.projectStatusList[vatSessionService.month] = constant.ProjectStatusEnum.UnStarted;
                                                vatSessionService.project = project;
                                                $state.go('vat.generateReport.reportView',param);
                                            }
                                        });
                            }
                            else {
                                vatSessionService.project = project;
                                //$state.go('vat.generateReport.reportView', param);
                                $state.go('vat.generateReport.reportView',
                                    {
                                        id: reportData.id,
                                        templateid: reportData.templateID,
                                        name: reportData.templateName,
                                        templatecode: reportData.templateCode
                                    });
                            }
                        }
                        else {
                            SweetAlert.error('', $translate.instant("CommonFail"));
                        }
                      
                    }).error(function () {
                        SweetAlert.error('', $translate.instant("CommonFail"));
                    });
                   
                }
            }
        };
    }
]);