commonModule.
controller('customAttributeModalController', ['$scope', '$log', '$translate', 'uiGridConstants', '$location', '$timeout', '$interval', 'areaRegionService', '$filter', 'SweetAlert', 'statisticAttributeService', 'dimensionService','enums',
    function ($scope, $log, $translate, uiGridConstants, $location, $timeout, $interval, areaRegionService, $filter, SweetAlert, statisticAttributeService, dimensionService,enums) {

        var selectedModel = '#addDimensionModal' + $scope.dimensionId;

        var showWarning = function (resultMsg) {

            var errMsg = $translate.instant(resultMsg);
            SweetAlert.warning(errMsg);
        };

        var showSuccessMsg = function (resultMsg) {

            var errMsg = $translate.instant(resultMsg);
            SweetAlert.success(errMsg);
        };

        var getDimensionList = function () {
            dimensionService.getDimensionList().success(function (data) {
                $scope.customDimensionList = _.where(data, function (item) {
                    return item.isSystemDimension === true;
                });

                $log.debug($scope.customDimensionList);

                //$scope.selectedFirst = $scope.orgFields[6];
                //$scope.selectedSecond = $scope.orgFields[3];
            });
        };

        //自定义显示属性列表
        var getStatisticAttributeList = function () {
            var parentDimensionID = $scope.dimensionId;
             
            //属性列表,多少个自定义属性,多少个dropdown list

            if ($scope.tabType !== 3) {
                statisticAttributeService.getByParentDimensionID(parentDimensionID).success(function (data) {
                    if (data) {
                        
                        $scope.statisticAttrList = data;

                        if (!$scope.statisticAttrList || $scope.statisticAttrList.length === 0) {
                            var statisticAttrTemp = {

                            };

                            $scope.statisticAttrList.push(statisticAttrTemp);
                        }

                        //下拉列表内容
                        getDropdownList('');
                    }
                });
            } else {
                //如果是机构Tab的话
                statisticAttributeService.getOrgSubChildrenStatAttributeList(parentDimensionID).success(function (data) {
                    if (data) {
                        $scope.statisticAttrList = data;

                        $scope.firstRowList = [];
                        var list = JSON.parse(JSON.stringify($scope.statisticAttrList));
                        $scope.firstRowList.push(list[0]);
                        $scope.firstRowList.push(list[1]);

                        $scope.statisticAttrList.splice(0, 2);

                        //下拉列表内容
                        getDropdownList(constant.DimensionType.OrgSubChildren);
                    }
                });
            } 
        };

        var getDropdownList = function (dictionaryCode) {
            //下拉列表内容
            statisticAttributeService.get(dictionaryCode).success(function (data) {
                if (data) {
                    $scope.dimensionList = data;

                    //显示已经设置的自定义属性
                    var list = $scope.statisticAttrList;
                     
                    if (dictionaryCode == constant.DimensionType.OrgSubChildren) {
                        $scope.withoutOrgAttrList = _.filter(data, function (item) {
                            return item.isOrgSelfProperty != true;
                        });
                    }

                    $scope.isBUTabType = false;
                    //事业部,第一行的机构,固定
                    if ($scope.tabType == 1) {
                        //第一行,永远显示机构数,并且不可编辑
                        list[0].attrSelectedID = constant.attributeID.orgSubChildrenID;
                        $scope.isBUTabType = true;
                        for (var i = 1; i < list.length; i++) {
                            list[i].attrSelectedID = list[i].attributeID;
                        }

                    }
                    else if ($scope.tabType === 3) {
                        var firstRowlist = $scope.firstRowList;
                        for (var i = 0; i < firstRowlist.length; i++) {
                            firstRowlist[i].attrSelectedID = firstRowlist[i].attributeID;
                        }
                        for (var i = 0; i < list.length; i++) {
                            list[i].attrSelectedID = list[i].attributeID;
                        }
                    } else if ($scope.tabType == 2) {
                        // 这是区域
                        $scope.firstRowList = [];
                        var notFirstRowList = [];
                        for (var i = 0; i < list.length; i++) {
                            list[i].attrSelectedID = list[i].attributeID;
                            if (i <=1){
                                $scope.firstRowList.push(list[i]);
                            } else{
                                notFirstRowList.push(list[i]);
                            }
                        }

                        $scope.statisticAttrList = notFirstRowList;

                    }
                    else {
                        for (var i = 1; i < list.length; i++) {
                            list[0].attrSelectedID = list[i].attributeID;
                        }
                    }
                }
            });
        };

        var editAttributeModel = function () {
            initData();
            //  $('#addDimensionModal').appendTo("body").modal('show');
            $(selectedModel).modal('show');
        }

        $scope.$watch('operateType', function (newValue, oldValue) {
            if (newValue) {

                if (newValue == constant.Operation.Add) {

                } else if (newValue == constant.Operation.Edit) {
                    editAttributeModel();
                }
            }
        });

        $(".addDimensionModal").on("hidden.bs.modal", function () {
            $scope.operateType = null;
        });

        $scope.closeModal = function () {
            $scope.operateType = null;
        };

        //自定义显示属性后,保存
        var saveAttr = function () {
            //fix bug for 10146. 如果没有选择值 请弹出错误提示框!
            var filterResult = _.filter($scope.statisticAttrList, function (row) {
                return !row.attrSelectedID;
            });

            if (filterResult && filterResult.length > 0) {
                showWarning("PleaseSelectAttr");
                return false;
            }

            if ($scope.tabType !== 3 && $scope.tabType !== 2) {
                saveAttrExceptOrgStructure();
            } else {
                saveAttrForOrgStructure();
            }
        };

        

        var saveAttrForOrgStructure = function () {

            var selectedAttr = [];
            var selectedAttrTemp = [];
            var selectedAttrTempFirstRow = [];

            var firstRowList = $scope.firstRowList;
            var list = $scope.statisticAttrList;
            var hasError = false;

            firstRowList.forEach(function (row) {
                if (row.attrSelectedID) {
                    var selectedID = row.attrSelectedID;
                    //维度不能重复选择
                    if (selectedAttrTempFirstRow.indexOf(selectedID) >= 0) {
                        hasError = true;
                        return;
                    }
                    selectedAttrTempFirstRow.push(selectedID);
                    selectedAttr.push({ attributeID: selectedID, dimensionID: $scope.dimensionId });
                }
            });

            list.forEach(function (row) {
                if (row.attrSelectedID) {
                    var selectedID = row.attrSelectedID;
                    //维度不能重复选择
                    if (selectedAttrTemp.indexOf(selectedID) >= 0) {
                        hasError = true;
                        return;
                    }
                    selectedAttrTemp.push(selectedID);
                    selectedAttr.push({ attributeID: selectedID, dimensionID: $scope.dimensionId });
                }
            });
            if (hasError) {
                showWarning("SelectAttrDuplicated");
                return false;
            }
            //至少选择一个维度
            if (selectedAttrTemp.length == 0) {
                showWarning("SelectOneAttr");
                return false;
            }

            statisticAttributeService.updateRange(selectedAttr).success(function (data) {
                if (data) {

                    showSuccessMsg('SaveSuccess');
                    $(selectedModel).modal('hide');

                    $scope.isUpdate = true;
                    $scope.operateType = null;
                    // $scope.refreshAttributeList();
                }
            });

        };

        ///除了机构层级之外的
        var saveAttrExceptOrgStructure = function () {
            var selectedAttr = [];
            var selectedAttrTemp = [];

            var list = $scope.statisticAttrList;
            var hasError = false;
            list.forEach(function (row) {
                if (row.attrSelectedID) {
                    var selectedID = row.attrSelectedID;
                    //维度不能重复选择
                    if (selectedAttrTemp.indexOf(selectedID) >= 0) {
                        hasError = true;
                        return;
                    }
                    selectedAttrTemp.push(selectedID);
                    selectedAttr.push({ attributeID: selectedID, dimensionID: $scope.dimensionId });
                }
            });
            if (hasError) {
                showWarning("SelectAttrDuplicated");
                return false;
            }
            //至少选择一个维度
            if (selectedAttrTemp.length == 0) {
                showWarning("SelectOneAttr");
                return false;
            }
            //$state.params.dimensionID
            statisticAttributeService.updateRange(selectedAttr).success(function (data) {
                if (data) {

                    showSuccessMsg('SaveSuccess');
                    $(selectedModel).modal('hide');

                    $scope.isUpdate = true;
                    $scope.operateType = null;
                    $scope.refreshAttributeList();
                }
            });
        };

        //删除自定义的维度
        var deleteAttr = function (row) {
            for (var i = 0; i < $scope.statisticAttrList.length; i++) {
                if ($scope.statisticAttrList[i].attributeID == row.attributeID) {
                    $scope.statisticAttrList.splice(i, 1);
                    break;
                }
            }

        };

        //添加自定义显示属性
        var AddAttr = function () {
            if ($scope.statisticAttrList.length < $scope.dimensionList.length) {
                var newObject = { dimensionID: '', name: '', IsActive: true };

                $scope.statisticAttrList.push(newObject);
            }
            else {
                showWarning("AddToMaximum");
            }
        };

        var initData = function () {
            getStatisticAttributeList();
            getDimensionList();
        };

        (function initialize() {
            $log.debug('orgCustomAttributeModalController.ctor()...');

            $scope.refreshAttributeList = getStatisticAttributeList;
            $scope.AddAttr = AddAttr;
            $scope.SaveAttr = saveAttr;
            $scope.deleteAttr = deleteAttr;
        })();
    }
]);