frameworkModule.controller('appOverviewController', ['$rootScope', '$scope', '$timeout', '$q', '$log', '$translate', '$state', '$interval',
    'uiGridConstants', 'projectService', 'vatSessionService', 'orgService', 'serviceTypeService', 'userService', 'loginContext', 'enums',
    'citSessionService', 'region', 'SweetAlert', 'productService', 'localStorageService', 'assetsManageSessionService', 'serviceLogService',
    'ackUibModal', 'Upload', 'apiInterceptor',
    function ($rootScope, $scope, $timeout, $q, $log, $translate, $state, $interval, uiGridConstants, projectService, vatSessionService,
              orgService, serviceTypeService, userService, loginContext, enums, citSessionService, region, SweetAlert, productService,
              localStorageService, assetsManageSessionService, serviceLogService, ackUibModal, Upload, apiInterceptor) {
        'use strict';
        $log.debug('appOverviewController.ctor()...');
        var uploadUrl = apiInterceptor.webApiHostUrl + '/product/NewFile';
        var resumable = true;
        $scope.chunkSize = 100000;
        $scope.conditionChange = false;
        var token = $('input[name="__RequestVerificationToken"]').val();
        //$scope.randomDemoData = {
        //    projectId:null,
        //    taxAmount: 0,
        //    prepadidTaxAmount: 0,
        //    taxRate: 0
        //};

        //**********************************************************************************************
        $scope.dateFormat = $translate.instant('dateFormat4Year');
        //always select a month before current month: update the year if the current month is Jan.(1)
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth();
        //$scope.selectedDate = new Date(year, month - 1, 1);
        $scope.startDate = new Date(year - 20, 1, 1);
        $scope.endDate = new Date(year + 20, 1, 1);
        $scope.selectedDate = new Date(vatSessionService.year, vatSessionService.month - 1, 1);
        $scope.selectedStartDate = new Date(vatSessionService.year, vatSessionService.month - 1, 1);
        $scope.serviceTypeId = $scope.servicetypeid.toString();
        $scope.ongoingNum = 0;
        $scope.notBeginNum = 0;
        $scope.completedNum = 0;
        //*************************************************************************************************
        $scope.randomCounter = 0;
        $scope.allResults = [];
        $scope.checkedOrgs = {};
        $scope.orgList = [];
        $scope.orderYear = true;
        $scope.orderName = true;
        $scope.orderStatus = true;
        $scope.orderType = true;
        $scope.isFirst = true;
        $scope.haveVatPermission = false;
        $scope.haveCitPermission = false;
        $scope.orgTreeUpdate = false;


        $scope.currentSelectedMonth = vatSessionService.month;
        $scope.currentSelectedYear = vatSessionService.year;

        var thisData = {
            userPermission: {}
        };

        userService.getUserByName(loginContext.userName).success(function (userData) {
            vatSessionService.logUser = userData;
        });

        $scope.doWorkflowSort = function (sortstr) {
            $scope.randomCounter++;

            $scope.sortString = sortstr + "_" + $scope.randomCounter;

        };

        //设置项目状态Title
        function setLayoutStatusTitle(statusIds) {

            var currentMonth = vatSessionService.month;
            var statusId;

            //(p.projectStatusList !== null && p.projectStatusList[1] !== undefined) ? setLayoutStatusTitle(p.projectStatusList[1]) : $scope.translateProjectStatus(p.haveCreateProject)
            if (statusIds === null || (statusIds !== null && statusIds[currentMonth] === undefined))
                statusId = 0;
            else {
                statusId = statusIds[currentMonth];
            }
            var status = "../../../app-resources/images/overview/";
            if (region === 'zh-CN') {
                status += 'zh-CN';
            } else {
                status += 'en-US';
            }

            // $log.debug("setLayoutStatusTitle");
            // $scope.statusTitle = $translate.instant('ProjectStatusTitle');
            switch (statusId) {
                case constant.ProjectStatusEnum.UnStarted:
                    status += "/01.png"; //$translate.instant('ProjectStatusUnStarted');
                    break;
                case constant.ProjectStatusEnum.Imported:
                    status += "/02.png"; // $translate.instant('ProjectStatusImported');
                    break;
                case constant.ProjectStatusEnum.AccountMapSubmitted:
                    status += "/03.png";// $translate.instant('ProjectStatusAcccountMapSubmitted');
                    break;
                case constant.ProjectStatusEnum.Generated:
                    status += "/04.png";// $translate.instant('ProjectStatusGenerated');
                    break;
                case constant.ProjectStatusEnum.ReportSubmitted:
                    status += "/05.png"; //$translate.instant('ProjectStatusReportSubmitted');
                    break;
                case constant.ProjectStatusEnum.ReportApproved:
                    status += "/07.png"; //$translate.instant('ProjectStatusReportApproved');
                    break;
                case constant.ProjectStatusEnum.ReportRejected:
                    status += "/06.png"; //$translate.instant('ProjectStatusReportRejected');
                    break;
                case constant.ProjectStatusEnum.Completed:
                    status += "/08.png";// $translate.instant('ProejctStatusCompleted');
                    break;
                default:
                    status += "/01.png";
            }

            return status;
        }

        function setLayoutStatusTitleForCIT(statusIds) {

            var currentMonth = vatSessionService.month;
            var statusId;

            //(p.projectStatusList !== null && p.projectStatusList[1] !== undefined) ? setLayoutStatusTitle(p.projectStatusList[1]) : $scope.translateProjectStatus(p.haveCreateProject)
            if (statusIds === null || (statusIds !== null && statusIds.length === 0))
                statusId = 0;
            else {
                statusId = statusIds[Object.keys(statusIds)[Object.keys(statusIds).length - 1]]
                // statusId = statusIds[currentMonth];
            }
            var status = "../../../app-resources/images/overview/";
            if (region === 'zh-CN') {
                status += 'zh-CN';
            } else {
                status += 'en-US';
            }

            // $log.debug("setLayoutStatusTitle");
            // $scope.statusTitle = $translate.instant('ProjectStatusTitle');
            switch (statusId) {
                case constant.ProjectStatusEnum.UnStarted:
                    status += "/01.png"; //$translate.instant('ProjectStatusUnStarted');
                    break;
                case constant.ProjectStatusEnum.Imported:
                    status += "/02.png"; // $translate.instant('ProjectStatusImported');
                    break;
                case constant.ProjectStatusEnum.AccountMapSubmitted:
                    status += "/03.png";// $translate.instant('ProjectStatusAcccountMapSubmitted');
                    break;
                case constant.ProjectStatusEnum.Generated:
                    status += "/04.png";// $translate.instant('ProjectStatusGenerated');
                    break;
                case constant.ProjectStatusEnum.ReportSubmitted:
                    status += "/05.png"; //$translate.instant('ProjectStatusReportSubmitted');
                    break;
                case constant.ProjectStatusEnum.ReportApproved:
                    status += "/07.png"; //$translate.instant('ProjectStatusReportApproved');
                    break;
                case constant.ProjectStatusEnum.ReportRejected:
                    status += "/06.png"; //$translate.instant('ProjectStatusReportRejected');
                    break;
                case constant.ProjectStatusEnum.Completed:
                    status += "/08.png";// $translate.instant('ProejctStatusCompleted');
                    break;
                default:
                    status += "/01.png";
            }

            return status;
        }

        function initListGrid() {
            var listColumns = [
                {caption: $translate.instant('SequenceNo'), dataField: "index", width: 100,},
                //{ caption: $translate.instant('SapDate'), dataField: "sapDate", dataType: "date", format: "yyyy-MM-dd", },
                //{ caption: $translate.instant('ProjectNameCol'), dataField: "name", },
                {caption: $translate.instant('ProjectCompanyCol'), dataField: "organizationName",},
                {caption: $translate.instant('PIndustry'), dataField: "industryName",},
                //{
                //    caption: $translate.instant('SapProductType'), dataField: "sapProductType",
                //    calculateCellValue: function (rowData) {
                //        return rowData.sapProductType ? convertProductTypeToStr(rowData.sapProductType) : null;
                //    },
                //},
                {caption: $translate.instant('ProjectYearCol'), dataField: "year", width: 100,},
                {caption: $translate.instant('ProjectServiceCol'), dataField: "serviceTypeName",},
                {caption: $translate.instant('ProjectStatus'), dataField: "projectStatusDisplay",},
                // {
                //     caption: $translate.instant('TotalBuildAmount'), dataField: "totalAmount",
                //     format: { type: 'fixedPoint', precision: 2 },
                // },
            ];
            $scope.deferStatus = true;
            $scope.gridListOptions = {
                columns: listColumns,
                bindingOptions: {
                    "dataSource": "queryResults"
                },
                loadPanel: {
                    enabled: true
                },
                //scrolling: {
                //    mode: "virtual"
                //},  
                hoverStateEnabled: true,
                paging: {pageSize: 20},
                noDataText: $translate.instant('AccountVoucher_DataGrid_NoDataText'),
                selection: {mode: "single"},
                onRowClick: function (e) {
                    $scope.goToService(e.data);
                }
            }
        };

        // TODO: REAL Translation for Industry and Region
        var initIndustryName = function (industryID, industryName) {
            var industryKey = '';
            switch (industryID) {
                case '0':
                    industryKey = 'GeneralIndustry';
                    break;
                case '1':
                    industryKey = 'IndustryIndustry';
                    break;
                case '10':
                    industryKey = 'AssetManagement';
                    break;
                case '13':
                    industryKey = 'MobileManufacturingIndustry';
                    break;
                case '14':
                    industryKey = 'FinancialServiceIndustry';
                    break;
                case '20':
                    industryKey = 'ManufacturingIndustry';
                    break;
                case '23':
                    industryKey = 'EstateIndustry';
                    break;
                default:
                    break;
            }

            if (!_.isEmpty(industryKey)) {
                industryName = $translate.instant(industryKey);
            }

            return industryName;
        };

        var initRegionName = function (regionID, regionName) {
            var regionKey = '';
            switch (regionID) {
                case '310000':
                case '310100':
                    regionKey = 'Shanghai';
                    break;
                case '110000':
                case '110100':
                    regionKey = 'Beijing';
                    break;
                case '440300':
                    regionKey = 'Shenzhen';
                    break;
                default:
                    break;
            }

            if (!_.isEmpty(regionKey)) {
                regionName = $translate.instant(regionKey);
            }

            return regionName;
        };

        $scope.loginAtms = function () {
            document.cookie = "LtpaToken=AAECAzVCRkQ2QTAwNUMyNEY2RkZTdXBlckFkbWlumd6hrZ2+cxiAEdE7sMEjLrIBGGg=;";
            window.open("http://localhost:18080/index", "_blank");
        }

        $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, 'DataProcessDataName_UpdateTB', 1, 0, true, 1));
            result.push(new task(2, constant.DataProccessStatus.Unstarted, 'DataProcessDataName_GenerateReport', 1, 0, false, 2));
            result.push(new task(3, constant.DataProccessStatus.ToUpdate, 'DataProcessDataName_UpdateReportConfig', 2, 2, true, 3));
            result.push(new task(4, constant.DataProccessStatus.ToUpdate, 'DataProcessDataName_FinanceReport', 2, 2, true, 4));
            result.push(new task(5, constant.DataProccessStatus.Unstarted, 'DataProcessDataName_CITQuarterly', 2, 2, false, 5));
            result.push(new task(6, constant.DataProccessStatus.Completed, 'DataProcessDataName_CITFirstQuarterly', 3, 5, true, 6));
            result.push(new task(7, constant.DataProccessStatus.Unstarted, 'DataProcessDataName_CITSecondQuarterly', 3, 5, true, 6));
            result.push(new task(8, constant.DataProccessStatus.NoData, 'DataProcessDataName_CITThirdQuarterly', 3, 5, true, 6));
            result.push(new task(9, constant.DataProccessStatus.NoData, 'DataProcessDataName_CITForthQuarterly', 3, 5, true, 6));
            result.push(new task(10, constant.DataProccessStatus.Unstarted, 'DataProcessDataName_YearWorkPaper', 2, 2, true, 7));
            result.push(new task(11, constant.DataProccessStatus.Unstarted, 'DataProcessDataName_AnnualSettlement', 2, 2, true, 8));
            result.push(new task(12, constant.DataProccessStatus.Completed, 'DataProcessDataName_ModelAnalysis', 1, 0, true, 9));
            return result;
        }


        $scope.initProjectList = function (orgID, serviceID, projectYear) {
            $scope.currentView = 'cardView';
            if (!orgID) {
                orgID = '';
            }
            if (!serviceID) {
                serviceID = '';
            }
            if (!projectYear) {
                projectYear = null;
            }

            projectService.getAllProjectList(orgID, serviceID, projectYear).success(function (projectListData) {
                if (projectListData && projectListData.length > 0) {
                    var index = 1;
                    $timeout(function () {
                        projectListData.forEach(function (p) {
                            //if (thisDataService.isHaveOrganizationPermission(p.organizationID)) {
                            if (PWC.isHavePermissionForOrg(p.organizationID, vatSessionService.userPermission))
                            // && $scope.haveVatPermission)
                            {
                                $scope.allResults.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: getServiceIcon(p.serviceTypeID),
                                    color: getColor(p.serviceTypeID),
                                    organizationName: p.organizationName,
                                    serviceTypeName: getServiceTypeName(p.serviceTypeID),
                                    industryName: initIndustryName(p.industryID, p.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: initRegionName(p.regionID, p.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: getPeriodDate(p.serviceTypeID)
                                    , modelAbnormal: false
                                    , riskWarning: false
                                    , reportAbnormal: false,
                                    citDataProcessMockData: $scope.initCitDataProcessMockData()
                                });

                            }
                        });

                        vatSessionService.projects = _.clone($scope.allResults);
                        $scope.queryResults = _.clone($scope.allResults);
                        $scope.gridListOptions.bindingOptions = {"dataSource": "queryResults"};
                        //$scope.query();
                        goQueryState();
                    }, 300);
                } else {
                    vatSessionService.projects = [];
                    $scope.queryResults = [];
                    $scope.gridListOptions.bindingOptions = [];
                }
            });
        };

        $scope.smartSearch = function (isReset) {
            if (isReset) {
                $scope.searchKeyword = "";
            }
            vatSessionService.queryDto.searchKeyword = $scope.searchKeyword;
            if ($scope.serviceTypeId !== '12') {
                $scope.query();
            }
        };

        $scope.translateProjectStatus = function (isCreate) {
            if (isCreate) {
                return $translate.instant('OnGoing');
            } else {
                return $translate.instant('NotBegin');
            }
        }

        $scope.getYearDisplay = function (p) {
            if (p.serviceTypeID === enums.serviceType.VAT || p.serviceTypeID === enums.serviceType.AssetsManage) {
                return p.year + "." + p.startPeriod + "-" + p.year + "." + p.endPeriod;
            } else {
                return p.year;
            }
        }

        var getColor = function (serType) {
            var color = "#e0301e";
            switch (serType) {
                case enums.serviceType.VAT:
                    color = "#e0301e";
                    break;
                case enums.serviceType.FDD:
                    color = "#d04a02";
                    break;
                case enums.serviceType.CIT:
                    color = "#a32020";
                    break;
                case enums.serviceType.TaxAudit:
                    color = "#602320";
                    break;
                case enums.serviceType.RPT:
                    color = "#d93954";
                    break;
            }
            return color;
        };

        var getServiceIcon = function (serType) {
            var type = "fa fa-diamond";
            switch (serType) {
                case enums.serviceType.VAT:
                    type = "fa fa-diamond";
                    break;
                case enums.serviceType.FDD:
                    type = "fa fa-credit-card";
                    break;
                case enums.serviceType.CIT:
                    type = "fa fa-building";
                    break;
                case enums.serviceType.TaxAudit:
                    type = "fa fa-money";
                    break;
                case enums.serviceType.RPT:
                    type = "fa fa-globe";
                    break;
            }
            return type;
        };

        var getServiceTypeName = function (serType) {
            var rtn;
            switch (serType) {
                case enums.serviceType.VAT:
                    rtn = $translate.instant("VATType");
                    break;
                case enums.serviceType.CIT:
                    rtn = $translate.instant("CITType");
                    break;
                default:
                    rtn = $translate.instant("VATType");
                    break;
            }
            return rtn;
        };

        var getPeriodDate = function (serType) {
            var periodDate;
            if (serType === enums.serviceType.CIT) {
                periodDate = $scope.currentSelectedYear + "";
            } else {
                periodDate = $scope.currentSelectedYear + "." + $scope.currentSelectedMonth;
            }
            return periodDate;
        };

        $scope.query = function () {
            if (!$scope.allResults) return;
            var temp = $scope.allResults;

            if ($scope.checkedOrgs && _.keys($scope.checkedOrgs).length > 0) {
                temp = _.filter(temp, function (i) {
                    return _.contains(_.values($scope.checkedOrgs), i.organizationName);
                });
            }
            //if ($scope.checkedYears && $scope.checkedYears.length > 0) {
            //    temp = _.filter(temp, function (i) { return _.contains(_.pluck($scope.checkedYears, 'name'), i.year) })
            //}
            if ($scope.serviceTypeId) {
                temp = _.filter(temp, function (i) {
                    return $scope.serviceTypeId == i.serviceTypeID;
                });
            }
            if (vatSessionService.year) {
                if ($scope.serviceTypeId === enums.serviceType.VAT) {
                    temp = _.filter(temp, function (i) {
                        if (i.startPeriod <= vatSessionService.month && i.endPeriod >= vatSessionService.month && i.year == vatSessionService.year) {
                            return i;
                        }
                    });
                } else if ($scope.serviceTypeId === enums.serviceType.CIT) {
                    temp = _.filter(temp, function (i) {
                        return vatSessionService.year == i.year;
                    });
                }
            }
            if ($scope.checkedRegions && $scope.checkedRegions.length > 0) {
                temp = _.filter(temp, function (i) {
                    return _.contains(_.pluck($scope.checkedRegions, 'name'), i.region);
                });
            }
            if ($scope.checkedStatus && $scope.checkedStatus.length > 0) {
                temp = _.filter(temp, function (i) {
                    return _.contains(_.pluck($scope.checkedStatus, 'name'), i.status);
                });
            }
            if ($scope.searchKeyword !== undefined && $scope.searchKeyword.length > 0) {
                temp = _.filter(temp, function (i) {
                    return (i.name.toUpperCase().indexOf($scope.searchKeyword.toUpperCase()) > -1 || i.organizationName.toUpperCase().indexOf($scope.searchKeyword.toUpperCase()) > -1);
                    // return $scope.selectedService.id == i.serviceTypeID
                })
            }

            var demoData = $scope.demoDataWithStateSaved(temp);
            var counter = 0;
            var setWarningToTrue = false;

            temp.forEach(function (project) {

                setWarningToTrue = false;
                project.finalStatus = (project.serviceTypeID === enums.serviceType.VAT) ? setLayoutStatusTitle(project.projectStatusList) : setLayoutStatusTitleForCIT(project.projectStatusList);
                project.periodDate = (project.serviceTypeID === enums.serviceType.VAT) ? ($scope.currentSelectedYear + "." + $scope.currentSelectedMonth) : ($scope.currentSelectedYear + "");

                var oneDemoData = _.find(demoData, function (one) {
                    return one.id === project.id
                });

                if (project.serviceTypeID === enums.serviceType.VAT) {
                    if (project.projectStatusList !== null && project.projectStatusList[vatSessionService.month] !== undefined && project.projectStatusList[vatSessionService.month] !== 10 && oneDemoData !== undefined) {
                        project.taxAmount = oneDemoData.taxAmount;
                        project.prepadidTaxAmount = oneDemoData.prepadidTaxAmount;
                        project.taxRate = oneDemoData.taxRate;
                        project.hasWarning = oneDemoData.hasWarning;

                    }

                    // START: For --->> Edmond Meng, CIT Demo
                    if (project.serviceTypeID === enums.serviceType.VAT && project.id === "8d8b13e7-07e1-4d84-8984-7b86e8ec6137" && project.code === "Demo111" && project.periodDate === '2017.1') {
                        project.taxAmount = "38669.27";
                        project.prepadidTaxAmount = "53866925.13";
                        project.taxRate = 15;
                        project.hasWarning = true;
                    }
                    // END: For --->> Edmond Meng, CIT Demo
                } else {
                    if (project.projectStatusList !== null && (Object.keys(project.projectStatusList).length > 0 && project.projectStatusList[Object.keys(project.projectStatusList)[Object.keys(project.projectStatusList).length - 1]] !== 10) && oneDemoData !== undefined) {
                        project.taxAmount = oneDemoData.taxAmount;
                        project.prepadidTaxAmount = oneDemoData.prepadidTaxAmount;
                        project.taxRate = oneDemoData.taxRate;
                        project.hasWarning = oneDemoData.hasWarning;

                    }
                    // START: For --->> Edmond Meng, CIT Demo
                    if (project.serviceTypeID !== enums.serviceType.VAT && project.id === "8d8b13e7-07e1-4d84-8984-7b86e8ec6137" && project.code === "Demo111") {
                        var status = "../../../app-resources/images/overview/";
                        if (region === 'zh-CN') {
                            status += 'zh-CN';
                        } else {
                            status += 'en-US';
                        }
                        status += '/04.png';
                        project.finalStatus = status;
                        project.taxAmount = "38669.27";
                        project.prepadidTaxAmount = "53866925.13";
                        project.taxRate = 15;
                        project.hasWarning = true;
                    }
                    // END: For --->> Edmond Meng, CIT Demo
                }

                counter++;
            });


            $scope.queryResults = temp;
            $scope.gridListOptions.data = $scope.queryResults;
            $scope.projectMsg = $translate.instant('ProjectResultMsg').formatObj({"ProjectNum": $scope.queryResults.length});

            var notBeginTemp = _.filter(temp, function (i) {
                if (i.serviceTypeID === enums.serviceType.VAT)
                    return ((i.projectStatusList === null || (i.projectStatusList !== null && i.projectStatusList[vatSessionService.month] === undefined) || (i.projectStatusList !== null && i.projectStatusList[vatSessionService.month] === 10)));

                else
                    return ((i.projectStatusList === null || (i.projectStatusList !== null && Object.keys(i.projectStatusList).length === 0) || i.projectStatusList[Object.keys(i.projectStatusList)[Object.keys(i.projectStatusList).length - 1]] === 10));
            });

            if (notBeginTemp) {
                $scope.notBeginNum = notBeginTemp.length;
            }
            var completedTemp = _.filter(temp, function (i) {
                if (i.serviceTypeID === enums.serviceType.VAT) {
                    if (i.projectStatusList && i.projectStatusList[vatSessionService.month] != null) {
                        return i.projectStatusList[vatSessionService.month] === 100;
                    }
                } else {
                    if (i.projectStatusList && i.projectStatusList.length > 0) {
                        return i.projectStatusList[Object.keys(i.projectStatusList)[Object.keys(i.projectStatusList).length - 1]] === 100;
                    }
                }
            });
            if (completedTemp) {
                $scope.completedNum = completedTemp.length;
            }
            $scope.ongoingNum = $scope.queryResults.length - $scope.notBeginNum - $scope.completedNum;
        };

        $scope.demoDataWithStateSaved = function (temp) {

            var demoData = [];
            var data;

            var demoDataComposedByLocalStorage = $scope.serviceTypeId + "_" + vatSessionService.year + "_" + vatSessionService.month;

            data = localStorageService.get(demoDataComposedByLocalStorage);

            if (data === null || data.length === 0) {
                var counter = 0;
                var everyXnumberToSetTrue = 3;
                var dData;

                // Set State:
                temp.forEach(function (item) {
                    dData = new Object();
                    //generate random data
                    dData.id = item.id;
                    dData.taxAmount = randomXToY(10000, 99999999, 2);
                    dData.prepadidTaxAmount = randomXToY(10000, 99999999, 2);
                    dData.taxRate = randomXToY(1, 35, 0);
                    dData.hasWarning = false;

                    if (counter >= everyXnumberToSetTrue && (counter % everyXnumberToSetTrue === 0))
                        dData.hasWarning = true;

                    demoData.push(dData);
                    counter++;

                });


                localStorageService.set(demoDataComposedByLocalStorage, demoData);


            } else {
                // Get from State:
                demoData = localStorageService.get(demoDataComposedByLocalStorage);
            }

            return demoData;
        };

        $scope.fileSort = function (sortstr) {
            if ($scope.queryResults.length > 0) {
                if (sortstr == 'year') {
                    if ($scope.orderYear) {
                        $scope.orderYear = false;
                        var list = _.sortBy($scope.queryResults, 'year');
                        $scope.queryResults = list;
                    } else {
                        $scope.orderYear = true;
                        var list = _.sortBy($scope.queryResults, 'year');
                        $scope.queryResults = list.reverse();
                    }
                }
                if (sortstr == 'name') {
                    if ($scope.orderName) {
                        $scope.orderName = false;
                        var list = _.sortBy($scope.queryResults, 'name');
                        $scope.queryResults = list;
                    } else {
                        $scope.orderName = true;
                        var list = _.sortBy($scope.queryResults, 'name');
                        $scope.queryResults = list.reverse();
                    }
                }
                if (sortstr == 'status') {
                    if ($scope.orderStatus) {
                        $scope.orderStatus = false;
                        var list = _.sortBy($scope.queryResults, 'haveCreateProject');
                        $scope.queryResults = list;
                    } else {
                        $scope.orderStatus = true;
                        var list = _.sortBy($scope.queryResults, 'haveCreateProject');
                        $scope.queryResults = list.reverse();
                    }
                }
                if (sortstr == 'type') {
                    if ($scope.orderType) {
                        $scope.orderType = false;
                        var list = _.sortBy($scope.queryResults, 'serviceTypeID');
                        $scope.queryResults = list;
                    } else {
                        $scope.orderType = true;
                        var list = _.sortBy($scope.queryResults, 'serviceTypeID');
                        $scope.queryResults = list.reverse();
                    }
                }
            }
        }

        $scope.goToService = function (project) {
            if (!project.clicked) {
                project.clicked = true;
                $log.debug('goToService()...');
                serviceLogService.addEnterProjectLog(loginContext.userName, 'Enter project (id: ' + project.id + ', serviceType: ' + project.serviceTypeID + ')').then(function () {
                    if (project.serviceTypeID === enums.serviceType.AssetsManage) {
                        $state.go('assetsManage.importData.productItem');
                        assetsManageSessionService.product.fSetCode = project.fSetCode;
                        assetsManageSessionService.product.productIDs = project.productIDs;
                        assetsManageSessionService.project.organizationName = project.fSetName;
                        assetsManageSessionService.project.id = project.id;
                        assetsManageSessionService.project.serviceTypeID = project.serviceTypeID;
                        //window.location.href = '/#/assetsManage/importData/productItem';
                    } else if (project.serviceTypeID === enums.serviceType.VAT) {
                        if (project.haveCreateProject) {
                            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;
                                            goRightPath(project);
                                        }
                                    });
                            } else {
                                vatSessionService.project = citSessionService.project = project;
                                goRightPath(project);
                            }
                        } else {
                            projectService.addProject(project).success(function (rsp) {
                                if (rsp && rsp.result) {
                                    project.haveCreateProject = true;
                                    project.dbName = rsp.dbname;
                                    project.id = rsp.projectID;

                                    if (_.isNull(project.projectStatusList)) { //如果当前期间还没有导入任何数据的话,就添加一条未开始状态的记录
                                        projectService.setProjectStatus(project.id, vatSessionService.month, constant.ProjectStatusEnum.UnStarted)
                                            .success(function (or) {
                                                if (or.result) {
                                                    projectService.getProjectAllStatus(project.id).success(function (org) {
                                                        //添加完成后,在vatSessionService.project中添加新加入的数据
                                                        project.projectStatusList = org;
                                                        projectService.getProjectStatus(project.id, vatSessionService.month)
                                                            .success(function (or1) {
                                                                if (or1.result) {
                                                                    project.importSubStatus = or1.data.importSubStatus;
                                                                    vatSessionService.project = project;
                                                                    goRightPath(project);
                                                                }
                                                            });
                                                    })
                                                }
                                            });
                                    } else {
                                        vatSessionService.project = project;
                                        goRightPath(project);
                                    }
                                } else {
                                    SweetAlert.error($translate.instant('AddProjectFail'));
                                }
                            });
                        }
                    } else { // project.serviceTypeID === enums.serviceType.CIT
                        if (project.haveCreateProject) {
                            if (_.isUndefined(project.projectStatusList[enums.wholeYearPeriod.import])) { //如果当前期间还没有导入任何数据的话,就添加一条未开始状态的记录
                                projectService.setProjectStatus(project.id, enums.wholeYearPeriod.import, constant.ProjectStatusEnum.UnStarted)
                                    .success(function (or) {
                                        if (or.result) {
                                            //添加完成后,在vatSessionService.project中添加新加入的数据
                                            project.projectStatusList[enums.wholeYearPeriod.import] = constant.ProjectStatusEnum.UnStarted;
                                            vatSessionService.project = citSessionService.project = project;
                                            citSessionService.year = $scope.currentSelectedYear;
                                            goRightPath(project);
                                        }
                                    });
                            } else {
                                vatSessionService.project = citSessionService.project = project;
                                citSessionService.year = $scope.currentSelectedYear;
                                goRightPath(project);
                            }
                        } else {
                            projectService.addProject(project).success(function (rsp) {
                                if (rsp && rsp.result) {
                                    project.haveCreateProject = true;
                                    project.dbName = rsp.dbname;
                                    project.id = rsp.projectID;

                                    if (_.isNull(project.projectStatusList)) { //如果当前期间还没有导入任何数据的话,就添加一条未开始状态的记录
                                        projectService.setProjectStatus(project.id, enums.wholeYearPeriod.import, constant.ProjectStatusEnum.UnStarted)
                                            .success(function (or) {
                                                if (or.result) {
                                                    projectService.getProjectAllStatus(project.id).success(function (org) {
                                                        //添加完成后,在vatSessionService.project中添加新加入的数据
                                                        project.projectStatusList = org;
                                                        projectService.getProjectStatus(project.id, enums.wholeYearPeriod.import)
                                                            .success(function (or1) {
                                                                if (or1.result) {
                                                                    project.importSubStatus = or1.data.importSubStatus;
                                                                    vatSessionService.project = citSessionService.project = project;
                                                                    citSessionService.year = $scope.currentSelectedYear;
                                                                    goRightPath(project);
                                                                }
                                                            });
                                                    })
                                                }
                                            });
                                    } else {
                                        vatSessionService.project = citSessionService.project = project;
                                        citSessionService.year = $scope.currentSelectedYear;
                                        goRightPath(project);
                                    }
                                } else {
                                    SweetAlert.error($translate.instant('AddProjectFail'));
                                }
                            });
                        }
                    }

                    $timeout(function () {
                        project.clicked = false;
                    }, 1000);
                });
            }
        };


        $scope.toggleExpand = function (item) {
            item.expand = !item.expand;
        };

        var goRightPath = function (project) {
            // TODO: CIT 权限
            if (project.serviceTypeID === enums.serviceType.CIT) {
                $state.go('cit.importData.assetList');
            } else {
                var menuList = [
                    constant.vatPermission.dataImport.balanceSheet.queryCode,
                    constant.vatPermission.dataImport.journalEntry.queryCode,
                    constant.vatPermission.dataImport.erpImport.queryCode,
//                    constant.vatPermission.dataImport.outputInvoice.queryCode,
//                    constant.vatPermission.dataImport.inputInvoice.queryCode,
//                    constant.vatPermission.dataImport.customInvoice.queryCode,
//                    constant.vatPermission.dataImport.voucherMapping.queryCode,
//                    constant.vatPermission.dataImport.invoiceMapping.queryCode,
//                    constant.vatPermission.dataImport.auditAdjust.queryCode,

                    constant.vatPermission.dataPreview.trialBalance.queryCode,
                    constant.vatPermission.dataPreview.profitLoss.queryCode,
                    constant.vatPermission.dataPreview.offBalanceSheet.queryCode,
                    constant.vatPermission.dataPreview.journal.queryCode,
                    constant.vatPermission.dataPreview.cashFlow.queryCode,
                    constant.vatPermission.dataPreview.invoiceRecord.queryCode,
                    constant.vatPermission.dataPreview.certifiedInvoicesList.queryCode,
                    constant.vatPermission.dataPreview.redLetterInformationTable.queryCode,
                    constant.vatPermission.dataPreview.coupaPurchasingReport.queryCode,
                    constant.vatPermission.dataPreview.invoiceData.queryCode,

                    constant.vatPermission.dataManage.caculateDataCode,
                    constant.vatPermission.dataManage.revenueDetailCode,
                    constant.vatPermission.dataManage.billDetailCode,

                    constant.vatPermission.reportView.bsplCode,
                    constant.vatPermission.reportView.taxReturnCode,

                    // constant.vatPermission.dataAnalysis.modelAnalysisCode,
                    // constant.vatPermission.dataAnalysis.dashboard.dashboardCode,
                    //constant.vatPermission.dataAnalysis.vatTaxDifferenceCode,
                ];

                $scope.$root.checkUserOrganizationPermissionList(menuList).success(function (data) {

                    //TODO 加上跳转
                    if (data) {


                        if (data[constant.vatPermission.dataImport.balanceSheet.queryCode]) {
                            $state.go('vat.importData.balanceSheet');
                        } else if (data[constant.vatPermission.dataImport.journalEntry.queryCode]) {
                            $state.go('vat.importData.journalEntry');
                        } else if (data[constant.vatPermission.dataImport.erpImport.queryCode]) {
                            $state.go('vat.importData.erpImport');
                        } else if (data[constant.vatPermission.dataPreview.trialBalance.queryCode]) {
                            $state.go('vat.previewData.trialBalance');
                        } else if (data[constant.vatPermission.dataPreview.profitLoss.queryCode]) {
                            $state.go('vat.previewData.profitLoss');
                        } else if (data[constant.vatPermission.dataPreview.offBalanceSheet.queryCode]) {
                            $state.go('vat.previewData.offBalanceSheet');
                        } else if (data[constant.vatPermission.dataPreview.journal.queryCode]) {
                            $state.go('vat.previewData.journal');
                        } else if (data[constant.vatPermission.dataPreview.cashFlow.queryCode]) {
                            $state.go('vat.previewData.cashFlow');
                        } else if (data[constant.vatPermission.dataPreview.invoiceRecord.queryCode]) {
                            $state.go('vat.previewData.invoiceRecord');
                        } else if (data[constant.vatPermission.dataPreview.certifiedInvoicesList.queryCode]) {
                            $state.go('vat.previewData.certifiedInvoicesList');
                        } else if (data[constant.vatPermission.dataPreview.redLetterInformationTable.queryCode]) {
                            $state.go('vat.previewData.redLetterInfoTab');
                        } else if (data[constant.vatPermission.dataPreview.coupaPurchasingReport.queryCode]) {
                            $state.go('vat.previewData.coupaPurchasingReport');
                        } else if (data[constant.vatPermission.dataPreview.invoiceData.queryCode]) {
                            $state.go('vat.previewData.invoiceData');
                        } else if (data[constant.vatPermission.dataManage.caculateDataCode]) {
                            $state.go('vat.reductionData.caculateData');
                        } else if (data[constant.vatPermission.dataManage.revenueDetailCode]) {
                            $state.go('vat.reductionData.revenueDetail');
                        } else if (data[constant.vatPermission.dataManage.billDetailCode]) {
                            $state.go('vat.reductionData.billDetail');
                        } else if (data[constant.vatPermission.reportView.bsplCode]) {
                            $state.go('vat.generateReport.reportView');
                        } else if (data[constant.vatPermission.reportView.taxReturnCode]) {
                            $state.go('vat.generateReport.reportUploadView');
                        }


//                    if (data[constant.vatPermission.dataImport.balanceSheet.queryCode]) {
//                        $state.go('vat.importData.balanceSheet');
//                    } else if (data[constant.vatPermission.dataImport.journalEntry.queryCode]) {
//                        $state.go('vat.importData.journalEntry');
//                    } else if (data[constant.vatPermission.dataImport.erpImport.queryCode]) {
//                        $state.go('vat.importData.erpData');
//                    } else if (data[constant.vatPermission.dataImport.auditAdjust.queryCode]) {
//                        $state.go('vat.importData.auditAdjust');
//                    } else if (data[constant.vatPermission.dataImport.outputInvoice.queryCode]) {
//                        $state.go('vat.importData.outputInvoice');
//                    } else if (data[constant.vatPermission.dataImport.inputInvoice.queryCode]) {
//                        $state.go('vat.importData.inputInvoice');
//                    } else if (data[constant.vatPermission.dataImport.customInvoice.queryCode]) {
//                        $state.go('vat.importData.customInvoice');
//                    } else if (data[constant.vatPermission.dataImport.voucherMapping.queryCode]) {
//                        $state.go('vat.importData.voucherMapping');
//                    } else if (data[constant.vatPermission.dataImport.invoiceMapping.queryCode]) {./
//                        $state.go('vat.importData.invoiceMapping');
//                    } else


                        // else if (data[constant.vatPermission.dataPreview.accountVoucher.queryCode]) {
//                        $state.go('vat.previewData.accountVoucher');
//                    } else

//                    else if (data[constant.vatPermission.dataPreview.customInvoice.queryCode]) {
//                        $state.go('vat.previewData.customInvoice');
//                    }
//                     else if (data[constant.vatPermission.dataManage.accountMappingCode]) {
//                         $state.go('vat.reductionData.accountMapping');
//                     } else if (data[constant.vatPermission.dataManage.goodsMappingCode]) {
//                         $state.go('vat.reductionData.goodsMapping');
//                     }

                        //TODO 删除的部分
                        // if (data[constant.vatPermission.dataPreview.balanceSheet.queryCode]) {
                        //     $state.go('vat.previewData.balanceSheet');
                        // }

                        // else if (data[constant.vatPermission.dataPreview.inputInvoice.queryCode]) {
                        //     $state.go('vat.previewData.inputInvoice');
                        // } else if (data[constant.vatPermission.dataPreview.outputInvoice.queryCode]) {
                        //     $state.go('vat.previewData.outputInvoice');
                        // }
                        //     else if (data[constant.vatPermission.dataManage.caculateDataCode]) {
                        //         $state.go('vat.reductionData.caculateData');
                        //     } else if (data[constant.vatPermission.dataManage.revenueDetailCode]) {
                        //         $state.go('vat.reductionData.revenueDetail');
                        //     } else if (data[constant.vatPermission.dataManage.billDetailCode]) {
                        //         $state.go('vat.reductionData.billDetail');
                        //     }  /*else if (data[constant.vatPermission.dataManage.unbilledInvoiceCode]) {
                        //     $state.go('vat.reductionData.unbilledInvoice');
                        // }*/ else if (data[constant.vatPermission.reportView.bsplCode] || data[constant.vatPermission.reportView.taxReturnCode]) {
                        //         $state.go('vat.generateReport');
                        //     } else if (data[constant.vatPermission.dataAnalysis.modelAnalysisCode]) {
                        //         $state.go('vat.analyzeLayout.analyzeReport');
                        //     } else if (data[constant.vatPermission.dataAnalysis.dashboard.dashboardCode]) {
                        //         $state.go('analyzeOrganizeDashboard');
                        //     }


                        //else if (data[constant.vatPermission.dataAnalysis.vatTaxDifferenceCode]) {
                        //    $state.go('vat.analyzeLayout.vatTaxDifference');
                        //}
                    }
                });
            }
        }

        $scope.toggleItemSub = function (item, parent) {

            // orgDisplay.showBusy();
            if (item.isChecked) {
                if (!item.dimensionId) {
                    $scope.checkedOrgs[item.id] = item.name;
                } else {
                    item.subOrgs.forEach(function (org) {
                        $scope.checkedOrgs[org.id] = org.name;
                        org.isChecked = true;
                    });
                }
            } else {

                if (!item.dimensionId) {
                    delete $scope.checkedOrgs[item.id];
                } else {
                    item.subOrgs.forEach(function (org) {
                        org.isChecked = false;
                        delete $scope.checkedOrgs[org.id];
                    });
                }
            }

            $scope.checkedIds = _.keys($scope.checkedOrgs);
            vatSessionService.queryDto.checkedOrgs = $scope.checkedOrgs;
            if ($scope.serviceTypeId !== enums.serviceType.AssetsManage) {
                $scope.query();
            }
            // orgDisplay.hideBusy();
        };

        $scope.toggleItemSubSpan = function (item) {
            if (item.isChecked) {
                item.isChecked = false;
            } else {
                item.isChecked = true;
            }
            $scope.toggleItemSub(item, null);
        };

        $scope.toggleView = function (clickedView) {
            if (clickedView == $scope.currentView) return;
            $scope.currentView = clickedView;
        };

        var thisDataService = {
            isHaveOrganizationPermission: function (orgID) {

                var permission = thisData.userPermission;
                var isShow = false;

                if (permission) {

                    if (permission.isSuperAdmin || permission.isADUser) {
                        isShow = true;
                    } else {

                        // 查找机构
                        var findOrg = _.find(permission.organizationPermissionList, function (num) {

                            return num.id === orgID;
                        });

                        if (findOrg && findOrg.permissionList && findOrg.permissionList.length > 0) {

                            // 查看具体权限
                            isShow = true;
                        }

                    }
                }

                return isShow;
            },
        };

        var initDatePickers = function () {
            if ($scope.serviceTypeId === enums.serviceType.CIT) {
                $scope.systemTitle = $translate.instant('CIT');
                $scope.viewMode = 2;
                $scope.dateFormat = $translate.instant('dateFormat4Year');
            }
            if ($scope.serviceTypeId === enums.serviceType.VAT) {
                $scope.systemTitle = $translate.instant('MenuVAT');
                $scope.viewMode = 1;
                $scope.dateFormat = $translate.instant('dateFormat4YearMonth');
            }
            if ($scope.serviceTypeId === enums.serviceType.AssetsManage) {
                $scope.systemTitle = $translate.instant('AssetTitle');
                $scope.viewMode = 1;
                $scope.dateFormat = $translate.instant('dateFormat4YearMonth');
            }

            var ele1 = $("#overviewDatepicker");
            ele1.datepicker({
                startDate: $scope.startDate,
                endDate: $scope.endDate,
                language: region,
                viewMode: $scope.viewMode,
                minViewMode: $scope.viewMode,
                autoclose: true, //选中之后自动隐藏日期选择框
                clearBtn: true, //清除按钮
                todayBtn: false, //今日按钮
                format: $scope.dateFormat //日期格式,详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
            }).on('changeDate', function (e) {
                $scope.changeDate(e);
            });
            ele1.datepicker("setDate", $scope.selectedDate);


        };

        $scope.changeStartDate = function (e) {
            if (e && e.date) {
                var tempYear = e.date.getFullYear();
                var tempMonth = e.date.getMonth() + 1;
                $scope.currentSelectedStartMonth = tempMonth;
                $scope.currentSelectedStartYear = tempYear;
            }
        };

        $scope.changeDate = function (e) {
            if (e && e.date) {
                var isDateUpdated = false;
                var tempYear = e.date.getFullYear();
                var tempMonth = e.date.getMonth() + 1;

                if (tempYear !== vatSessionService.year || tempMonth !== vatSessionService.month) {
                    isDateUpdated = true;
                }

                vatSessionService.year = tempYear;
                vatSessionService.month = tempMonth;
                $scope.currentSelectedMonth = tempMonth;
                $scope.currentSelectedYear = tempYear;

                if (isDateUpdated) {
                    //$scope.$apply(function () {
                    //    $scope.conditionChange = !$scope.conditionChange;
                    //});

                    $timeout(function () {
                        $scope.conditionChange = !$scope.conditionChange;
                    });
                }
                if ($scope.serviceTypeId !== enums.serviceType.AssetsManage) {
                    $scope.query();
                }
            }
        };

        var orgDisplay = {

            orgList: [],
            grayColorD9: '#d9d9d9',
            currentIdcol: '',
            currentNamecol: 'orgName',
            activeColor: 'black',
            activeBackgroundColor: '#fbf8f5',
            whiteColor: 'white',
            main: function () {

                $scope.dimensionOrgShow = function (idcol, namecol) {

                    orgDisplay.showBusy();

                    vatSessionService.queryDto.fieldId = idcol;
                    vatSessionService.queryDto.filedName = namecol;

                    orgDisplay.currentIdcol = idcol;
                    orgDisplay.currentNamecol = namecol;

                    $('.operate-icon').css('background-color', orgDisplay.whiteColor);
                    $('.operate-icon i').css('color', orgDisplay.grayColorD9);


                    $scope.checkedOrgs = {};
                    //$scope.query();

                    var orgData = [];
                    if (idcol) {
                        orgData = orgDisplay.otherShow(idcol, namecol);
                    } else {
                        orgData = orgDisplay.orgShow();
                    }

                    $('.' + namecol).css('color', orgDisplay.activeColor);

                    $('.' + namecol).parent().css('background-color', orgDisplay.activeBackgroundColor);

                    $timeout(function () {
                        orgDisplay.hideBusy();

                        if ($scope.isFirst) {
                            $scope.setTreeChecked(orgData);
                            $scope.isFirst = false;
                        }

                        $scope.orgData = orgData;
                    }, 50);
                };

                orgDisplay.getOrgData();
            },

            getOrgData: function () {

                var data = vatSessionService.orgTree;

                if (!data) {
                    data = [];
                }

                var result = [];

                //如果是资产管理,则只获取资产管理类型的组织机构
                if ($scope.serviceTypeId === enums.serviceType.AssetsManage) {
                    result = _.filter(data, function (item) {
                        return item.industryID == '10';
                    });
                } else {
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        if (thisDataService.isHaveOrganizationPermission(item.id)) {
                            result.push(item);
                        }
                    }
                }

                orgDisplay.orgList = result;

                //$scope.dimensionOrgShow('', 'orgName');
                $scope.dimensionOrgShow(vatSessionService.queryDto.fieldId, vatSessionService.queryDto.filedName);


                // orgDisplay.orgList = testOrgList;
            },

            orgShow: function () {
                var showList = angular.copy(orgDisplay.orgList);

                // 构造父子节点

                for (var i = 0; i < showList.length; i++) {
                    var item = showList[i];
                    if (item.parentID === null) {
                        continue;
                    }

                    var parentNode = _.find(showList, function (num) {
                        return num.id === item.parentID
                    });

                    if (parentNode) {
                        continue;
                    }

                    item.parentID = orgDisplay.getParentID(item, orgDisplay.orgList, showList);
                }

                var idList = _.pluck(showList, 'id');


                var topNodeList = _.filter(showList, function (org) {
                    return idList.indexOf(org.parentID) === -1;
                });

                var orgList = [];
                topNodeList.forEach(function (org) {
                    var item = {
                        id: org.id,
                        name: org.name
                    };

                    var tempList = orgDisplay.getSubOrgDropDownList(org, showList);

                    item.subOrgs = tempList;
                    // 构造子节点
                    orgList.push(item);

                    // orgList = _.union(orgList, tempList);
                });

                return orgList;

            },

            // 获取父节点
            getParentID: function (current, allList, orgDtoList) {
                if (current.parentID === null) {
                    return null;
                }

                var findParent = _.find(allList, function (num) {
                    return num.id === current.parentID;
                });

                if (!findParent) {
                    return null;
                }

                var parent = _.find(orgDtoList, function (num) {
                    return num.id === findParent.id;
                });

                if (parent != null) {
                    return parent.id;
                } else {
                    return orgDisplay.getParentID(findParent, allList, orgDtoList);
                }
            },
            getSubOrgDropDownList: function (current, showList) {
                var sublist = _.filter(showList, function (row) {
                    return row.parentID === current.id;
                });

                var list = [];
                if (!sublist || sublist.length === 0) {
                    return list;
                }

                sublist.forEach(function (row) {
                    var item = {
                        id: row.id,
                        name: row.name,
                        parentID: current.id,
                        expanded: true,
                    };

                    var tempList = orgDisplay.getSubOrgDropDownList(row, showList);
                    item.subOrgs = tempList;

                    list.push(item);

                });

                return list;
            },

            otherShow: function (idcol, namecol) {
                var showList = angular.copy(orgDisplay.orgList);
                var otherList = orgDisplay.getMap(showList, idcol, namecol);

                var list = [];
                otherList.forEach(function (other) {

                    var item = other;

                    item.dimensionId = idcol;

                    item.subOrgs = _.filter(showList, function (t) {

                        return t[idcol] === other.id;
                    });

                    list.push(item);
                });


                return list;
            },
            getMap: function (data, idCol, nameCol) {
                if (data && data.length > 0) {
                    var idList = _.uniq(_.pluck(data, idCol));
                    var list = [];

                    idList.forEach(function (row) {
                        if (row) {
                            var findOne = _.find(data, function (o) {
                                return o[idCol] === row;
                            });

                            if (findOne && findOne[nameCol]) {
                                list.push({
                                    id: row,
                                    name: findOne[nameCol],
                                    selected: true,
                                });
                            }
                        }
                    });

                    return list;
                } else {
                    return [];
                }
            },

            showBusy: function () {
                $('#busy-indicator-container').show();
            },

            hideBusy: function () {
                $('#busy-indicator-container').hide();
            }

        };

        $scope.setTreeChecked = function (dataList) {
            if (dataList && dataList.length > 0 && _.keys(vatSessionService.queryDto.checkedOrgs).length > 0) {
                dataList.forEach(function (v) {
                    if (vatSessionService.queryDto.checkedOrgs[v.id]) {
                        v.isChecked = true;
                    }
                    if (v.subOrgs && v.subOrgs.length > 0) {
                        $scope.setTreeChecked(v.subOrgs);
                    }
                });
            }
        }

        var goQueryState = function () {
            $scope.searchKeyword = vatSessionService.queryDto.searchKeyword;
            $scope.checkedOrgs = vatSessionService.queryDto.checkedOrgs;
            if ($scope.serviceTypeId !== enums.serviceType.AssetsManage) {
                $scope.query();
            }
        };

        //function to get random number upto m
        function randomXToY(minVal, maxVal, floatVal) {
            var randVal = minVal + (Math.random() * (maxVal - minVal));
            return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
        }

        /**********************************资产配置*************************************/
        //初始化产品列表
        function initProductListGrid() {
            var listColumns = [
                {caption: '年份', dataField: 'fYear'},
                {caption: '产品标识', dataField: "fSetID"},
                {caption: '产品编号', dataField: "fSetCode"},
                {caption: '产品描述(名称)', dataField: "fSetName"},
                {caption: '财务主管', dataField: "fManager"},
                {caption: '启用年份', dataField: "fStartYear"},
                {caption: '启用月份', dataField: "fStartMonth"},
                {caption: '所属机构', dataField: "accountDepartment"}
            ];
            $scope.gridListOptions = {
                showBorders: true,
                columns: listColumns,
                bindingOptions: {
                    "dataSource": "productListQueryResult"
                },
                loadPanel: {
                    enabled: true
                },
                hoverStateEnabled: true,
                paging: {pageSize: 20},
                noDataText: $translate.instant('AccountVoucher_DataGrid_NoDataText'),
                selection: {mode: "single"},
                onRowClick: function (e) {
                    $scope.goToService(e.data);
                },
                onContentReady: function (e) {
                    $scope.productListGridInstance = e.component;
                }
            }
        };

        $scope.initProductList = function () {
            productService.getProductList().success(function (data) {
                $scope.productListQueryResult = data;
                $scope.totolCount = data.length;
                var index = 1;
                data.forEach(function (v) {
                    v.index = index++;
                    v.serviceTypeID = enums.serviceType.AssetsManage;
                });

            });
        };

        //重新设置产品列表grid
        $scope.updateProductList = function () {
            $scope.updateStatus = true;
        };

        $scope.addNewProduct = function () {
            $scope.modalService.newProductModal.open();
        };

        $scope.product = {
            fYear: "",
            fSetId: "",
            fSetName: "",
            fManager: ""
        };

        $scope.modalService = {
            newProductModal: {
                open: function () {
                    $scope.product = {
                        fYear: "",
                        fSetId: "",
                        fSetName: "",
                        fManager: ""
                    };

                    var treeView;
                    var syncTreeViewSelection = function (treeView) {
                        if (!treeView) return;

                        if (!$scope.treeBoxValue) {
                            treeView.unselectAll();
                            return;
                        }

                        $scope.treeBoxValue.forEach(function (key) {
                            treeView.selectItem(key);
                        });
                    };

                    $scope.treeBoxValue = [""];
                    $scope.treeDataSource = [];
                    $scope.treeBoxNameValue = [""];
                    productService.getProductList().success(function (data) {
                        data.forEach(function (v) {
                            if (!v.productIDs) {
                                var item = new Object;
                                item.name = v.fSetName;
                                item.content = {id: v.fSetCode, guid: v.id};
                                $scope.treeDataSource.push(item);
                            }
                        });
                    });

                    $scope.treeBoxOptions = {
                        bindingOptions: {
                            value: 'treeBoxNameValue'
                        },
                        valueExpr: "ID",
                        displayExpr: "name",
                        placeholder: "选择...",
                        showClearButton: false,
                        dataSource: $scope.treeDataSource,
                        onValueChanged: function () {
                            syncTreeViewSelection(treeView);
                        },
                        treeView: {
                            dataSource: $scope.treeDataSource,
                            dataStructure: "plain",
                            keyExpr: "ID",
                            parentIdExpr: "categoryId",
                            displayExpr: "name",
                            selectByClick: true,
                            selectNodesRecursive: false,
                            showCheckBoxesMode: "normal",
                            bindingOptions: {
                                selectionMode: "selectionMode"
                            },
                            onContentReady: function (e) {
                                treeView = e.component;
                                syncTreeViewSelection(treeView);
                            },
                            onItemSelectionChanged: function (args) {
                                var keyValue = args.component.getSelectedNodesKeys();
                                if (keyValue.length === 0) {
                                    keyValue = [""];
                                }
                                var value = [""];
                                var nodes = args.component.getNodes();
                                var newValue = [""];
                                var nameValue = [""];
                                keyValue.forEach(function (v) {
                                    var findResult = _.find(nodes, function (node) {
                                        return node.key === v;
                                    });
                                    if (findResult) {
                                        newValue.push(findResult.itemData.content.guid);
                                        value.push(findResult.itemData.content.id);
                                        nameValue.push(findResult.itemData.name);
                                    }
                                });
                                $scope.treeBoxValue = keyValue;
                                $scope.newNewtreeBoxValue = value;
                                $scope.newTreeBoxValue = newValue;
                                var tempArray = nameValue.length === 1 ? nameValue : nameValue.shift();
                                $scope.treeBoxNameValue = nameValue;
                            }
                        }
                    };

                    $timeout(function () {
                        var ele2 = $("#productStartDate");
                        ele2.datepicker({
                            startDate: $scope.startDate,
                            endDate: $scope.endDate,
                            language: region,
                            viewMode: $scope.viewMode,
                            minViewMode: $scope.viewMode,
                            autoclose: true, //选中之后自动隐藏日期选择框
                            clearBtn: true, //清除按钮
                            todayBtn: false, //今日按钮
                            format: $scope.dateFormat //日期格式,详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
                        }).on('changeDate', function (e) {
                            $scope.changeStartDate(e);
                        });
                        ele2.datepicker("setDate", $scope.selectedStartDate);
                    }, 100);

                    $scope.newProductModalInstance = ackUibModal($scope, 'addNewProduct.html', 'addNewProduct', '.app-overview ', 'static')
                    $scope.newProductModalInstance.open();
                },
                save: function (result) {
                    $scope.saveProduct();
                    $scope.newProductModalInstance.close();
                },
                cancel: function () {
                    $scope.newProductModalInstance.cancel();
                }
            }
        };

        $scope.changeWithZeroNumber = function (sourceNumber) {
            if (sourceNumber.length > 1) {
                if (sourceNumber < 10) {
                    return sourceNumber.replace(/0/g, '');
                } else {
                    return sourceNumber;
                }
            } else {
                return sourceNumber;
            }
        };

        $scope.saveProduct = function () {
            //$scope.product.fSetCode = $scope.treeBoxValue.toString();
            $scope.product.fStartYear = $scope.currentSelectedStartYear;
            $scope.product.fStartMonth = $scope.changeWithZeroNumber($scope.currentSelectedStartMonth);
            $scope.product.productIDs = $scope.newTreeBoxValue.toString();

            //调用service插入数据库
            productService.addNewProduct($scope.product).success(function () {
                $scope.initProductList();
            })
        };
        var successCount = 0;
        var doUploadProductFileName = function (file) {
            if (file) {
                var arr = file.name.split('.');
                if (arr[arr.length - 1] !== 'xls' && arr[arr.length - 1] !== 'xlsx') {
                    SweetAlert.warning($translate.instant('ImportFileInvalidType'));
                    return;
                }
                //$scope.initJournalEntryList = [];
                //$scope.gridOptionsJournalEntry.data = [];
                successCount = 0;
                if (!file.$error) {
                    var tempFileName = PWC.newGuid() + '.dat';
                    Upload.upload({
                        url: uploadUrl,
                        data: {
                            filename: file.name,
                            tempFileName: tempFileName,
                            file: file
                        },
                        resumeChunkSize: resumable ? $scope.chunkSize : null,
                        headers: {
                            'Access-Control-Allow-Origin': '*',
                            Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken()
                        },
                        __RequestVerificationToken: token,
                        withCredentials: true
                    }).then(uploadJournalEntrySuccess);
                }
            }
        };

        //上传成功后执行函数
        var uploadJournalEntrySuccess = function (resp) {
            console.log(resp);
            successCount++;
            if (successCount === 1) {
                $scope.tempFileName = resp.data;
                //初始化到excel文件的第一个sheet
                getUploadFileContent(0);
            }
        };

        var getUploadFileContent = function () {
            if (_.isString($scope.tempFileName)) {
                productService.getFileContent($scope.tempFileName, 0, 0).success(function (data) {

                    //将导入文件的sheet赋值到数组
                    $scope.sheetData = data;
                    //加入index序号
                    var index = 1;
                    data.dataList.forEach(function (v) {
                        v.index = index++;
                    });

                    //先将完整数据深拷贝存放到变量中
                    $scope.sheetData.excelSheetAllData = angular.copy(data.dataList);
                    var number = 1;
                    $scope.sheetData.excelSheetAllData.forEach(function (v) {
                        v.index = number++;
                    });
                    //将导入文件的sheet赋值到数组
                    //只赋值data的前500条到sheetData的dataList中,防止数据量太大渲染的时候卡死浏览器
                    $scope.sheetData.dataList = data.dataList.slice(0, 500);

                    if (data & data.result === false) {
                        SweetAlert.warning(data.resultMsg);
                        return;
                    }

                    //upload data to DB
                    saveProductDataToDatabase();
                });
            }
        };

        var saveProductDataToDatabase = function () {
            //将需要导入的数据组装到list中
            var importProductList = [];
            var startRowNum = 3;
            for (var i = startRowNum - 1; i < $scope.sheetData.dataList.length; i++) {
                var productInfo = {
                    'Index': $scope.sheetData.dataList[i].index,
                    'FYear': $scope.sheetData.dataList[i][0],
                    'FSETID': $scope.sheetData.dataList[i][1],
                    'FSETCODE': $scope.sheetData.dataList[i][2],
                    'FSETNAME': $scope.sheetData.dataList[i][3],
                    'FMANAGER': $scope.sheetData.dataList[i][4],
                    'FSTARTYEAR': $scope.sheetData.dataList[i][5],
                    'FSTARTMONTH': $scope.changeWithZeroNumber($scope.sheetData.dataList[i][6]),
                    'FMONTH': $scope.changeWithZeroNumber($scope.sheetData.dataList[i][7]),
                    'ACCOUNTDEPARTMENT': $scope.sheetData.dataList[i][8]
                };
                importProductList.push(productInfo);
            }

            productService.importProductData(importProductList).success(function () {
                //logDto.UpdateState = $translate.instant('ImportSuccess');
                //vatOperationLogService.addOperationLog(logDto);
                //vatCommonService.importSetProjectStatus(projectDbName, curPeriod
                //                                       , constant.DictionaryDictKey.WFImportJournalEntry
                //                                       , enums.FinishStatusEnum.Finished);
                //vatCommonService.setImportSubStatus(enums.VatImportSubStatus.isEntryImport, true);
                //$log.debug("import entry importJournalEntryData: " + vatSessionService.project.importSubStatus.isEntryImport);
                SweetAlert.success($translate.instant('ImportSuccess'));
                $scope.initProductList();
            }).error(function () {
                SweetAlert.error($translate.instant('PleaseContactAdministrator'));
                //logDto.UpdateState = $translate.instant('ImportFail');
                //vatOperationLogService.addOperationLog(logDto);
            });
        };

        /**********************************资产配置*************************************/
        (function initialize() {
            if ($scope.serviceTypeId !== enums.serviceType.AssetsManage) {
                initListGrid();
            }
            initDatePickers();
            $scope.updateStatus = false;

            if ($.isEmptyObject(vatSessionService.orgTree)) {
                orgService.getOrgListLevel().success(function (data) {
                    if (data && $.isEmptyObject(vatSessionService.orgTree)) {
                        vatSessionService.orgTree = data;
                        $scope.orgTreeUpdate = true;
                    }
                });
            }

            userService.getUserPermission(loginContext.userName).success(function (userPermission) {
                thisData.userPermission = userPermission;
                userPermission.permissionList.forEach(function (p) {
                    if (p.code.startWith('02')) {
                        $scope.haveVatPermission = true;
                        return;
                    }
                    if (p.code.startWith('03')) {
                        $scope.haveCitPermission = true;
                        return;
                    }
                });
                vatSessionService.userPermission = userPermission;
                orgDisplay.main();
                if ($scope.serviceTypeId === enums.serviceType.AssetsManage) {
                    $scope.projectMsg = $translate.instant('ProjectResultMsg').formatObj({"ProjectNum": 66});
                    initProductListGrid();
                    $scope.initProductList();
                    $scope.toggleView('listView');
                } else {
                    $scope.initProjectList();
                }
            });

            $scope.$watch('productFileName', function (newValue, oldValue) {
                if (newValue && newValue !== oldValue) {
                    doUploadProductFileName(newValue);
                }
            });

            $scope.$watch('orgTreeUpdate', function (newValue, oldValue) {
                if (newValue === true) {
                    orgDisplay.getOrgData();
                }
            });
        })();
    }
]);

frameworkModule.factory('assetsManageSessionService', ['$log', function ($log) {
    'use strict';
    $log.debug('assetsManageSessionService.ctor()...');

    var date = new Date();
    var month = date.getMonth();
    var projectyear = 2017;
    if (month <= 0) {
        month = 1;
    }
    var logUser = {
        ID: "66933E7B-DA75-4B2E-B7D6-AB65DCA20D50",
        UserName: "Admin",
    };

    var reset = function () {
        var date = new Date();
        var m = date.getMonth();
        if (m <= 0) {
            m = 1;
        }
        this.month = m;
    };

    return {
        month: 6,
        year: projectyear,
        project: {
            year: projectyear,
            projectStatusList: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
            importSubStatus: 1,
            dbName: 'AssetsManage',
            id: '99999',
            name: '阳光证券有限公司增值税申报项目',
            organizationName: '阳光证券有限公司增值税申报项目'
        },
        projects: [],
        dataChanged: false,
        logUser: logUser,
        reset: reset,
        product: {
            fSetCode: '11111111111111111111',
            productIDs: 'xxxxxxxxxxxxxxxxxxxx'
        }
    }


}]);


frameworkModule.factory("demoDataService", function ($window, $rootScope) {
    'use strict';
    return {
        setData: function (val) {
            $window.localStorage && $window.localStorage.setItem('overview-demo-data', val);
            return this;
        },
        getData: function () {
            return $window.localStorage && $window.localStorage.getItem('overview-demo-data');
        }
    };
});