crmApp.service('AdvanceRulesService', function ($filter) {
    var displaySetting = {
        FieldsSorting: [{
            'SortID': -1,
            'FieldMappingID': 0,
            'SortDirection': '',
            'Sequence': 1
        }],
        FieldMappings: [],
        DisplayColumns: [
            {
                'ViewColumnID': -1,
                'ViewID': 0,
                'FieldMappingID': 0,
                'DisplayField': '',
                'Sequence': 1,
            }
        ]
    };
    var _defaultDisplaySetting = {
        FieldsSorting: [{
            'SortID': -1,
            'FieldMappingID': 0,
            'SortDirection': '',
            'Sequence': 1
        }],
        FieldMappings: [],
        DisplayColumns: [
            {
                'ViewColumnID': -1,
                'ViewID': 0,
                'FieldMappingID': 0,
                'DisplayField': '',
                'Sequence': 1,
            }
        ]
    };

    var _oriDisplaySetting = {
        FieldsSorting: [{
            'SortID': -1,
            'FieldMappingID': 0,
            'SortDirection': '',
            'Sequence': 1
        }],
        FieldMappings: [],
        DisplayColumns: [
            {
                'ViewColumnID': -1,
                'ViewID': 0,
                'FieldMappingID': 0,
                'DisplayField': '',
                'Sequence': 1,
            }
        ]
    };
    var _allowRemove = true;
    var _allowEdit = true;
    var _clearEnabledOnly = false;
    var advlist = [
              {
                  'ViewRuleID': -1,
                  'Sequence': 1,
                  'RuleType': '1',
                  'RuleOperator': '1',
                  'GroupingOperator': '',
                  'RowSelected': false,
                  'IsFromDB': false,
                  'AllowRemove': true,
                  'DisableAll': false,
                  'AllowSelectOperator': true,
                  RuleGroup: [
                      {
                          'DisplayField': null,
                          'FieldType': '12',
                          'FieldMapping': '',
                          'TableName': '',
                          'FieldOperator': null,
                          'FieldOperatorCode': '0',
                          'FieldMappingRef': '0',
                          'FieldMappingRefCode': '0',
                          'IsInnerJoin': '0',
                          'selected': [],
                          'IsFromDB': false,
                          'IsMultiple': false,
                          'OperatorEnabled': false,
                          'FieldEnabled': false,
                          'FieldValues': [
                              {
                                  'ViewRuleGroupFieldsID': 0,
                                  'FieldValue': '',
                                  'IsFromDB': false
                              }
                          ]
                      }
                  ]
              }
    ];
    var isEnableDynamicDisplayColumn = false;
    var permissionUsers = [];
    var permissionRoles = [];
    var permissionSetting = [];
    var permissionType;

    this.updateItem = function (item) {
        advlist = item;
    }

    this.getList = function () {
        var retList = [];
        //// format date 
        //var dateTimeFormat = 'dd MMM yyyy hh:mm a';
        //retList = $.extend(true, {}, advlist);
        ////angular.forEach(advlist, function (item, i) {
        ////    retList.push(Object.clone(item));//$extend(true, {}, advlist);
        ////});
        //angular.forEach(retList, function (item, i) {
        //    var ruleGroup = item.RuleGroup;
        //    angular.forEach(ruleGroup, function (rgItem, j) {
        //        if (rgItem.FieldType == 14) {
        //            rgItem.FieldValues[0].FieldValue = $filter('date')(rgItem.FieldValues[0].FieldValue, dateTimeFormat);
        //        }
        //    });
        //});

        return advlist;
    }

    this.getDisplaySetting = function () {
        return displaySetting;
    }

    this.getDefaultDisplaySetting = function () {
        return _defaultDisplaySetting;
    }
    this.resetDisplaySetting = function () {
        displaySetting = angular.copy( _oriDisplaySetting);
    }
    this.getDynamicDisplayInd = function () {
        return isEnableDynamicDisplayColumn;
    }

    this.setDynamicDisplayInd = function (value) {
        isEnableDynamicDisplayColumn = value;
    }

    this.updateDisplaySetting = function (item) {
        displaySetting = item;
    }

    this.getOriDisplaySetting = function () {
        return _oriDisplaySetting;
    }

    this.setOriDisplaySetting = function () {
        _oriDisplaySetting.DisplayColumns = angular.copy( displaySetting.DisplayColumns);
        _oriDisplaySetting.FieldMappings = angular.copy(displaySetting.FieldMappings);
        _oriDisplaySetting.FieldsSorting = angular.copy(displaySetting.FieldsSorting);
    }

    this.getAllowRemove = function () {
        var result = _allowRemove;
        return _allowRemove;
    }

    this.setAllowEdit = function (value) {
        _allowEdit = value;
    }

    this.getAllowEdit = function () {
        return _allowEdit;
    }

    this.setAllowRemove = function (value) {
        _allowRemove = value;
    }

    this.getClearEnabledOnly = function () {
        return _clearEnabledOnly;
    }

    this.setClearEnabledOnly = function (value) {
        _clearEnabledOnly = value;
    }

    this.getDefaultList = function () {
        return [
              {
                  'ViewRuleID': -1,
                  'Sequence': 1,
                  'RuleType': '1',
                  'RuleOperator': '1',
                  'GroupingOperator': '',
                  'RowSelected': false,
                  'IsFromDB': false,
                  'AllowRemove': true,
                  'DisableAll': false,
                  'AllowSelectOperator': true,
                  RuleGroup: [
                      {
                          'ViewRuleGroupID': 0,
                          'ViewRuleID': 0,
                          'DisplayField': null,
                          'FieldType': '12',
                          'FieldMapping': '',
                          'TableName': '',
                          'FieldOperator': null,
                          'FieldOperatorCode': '0',
                          'FieldMappingRef': '0',
                          'FieldMappingRefCode': '0',
                          'IsInnerJoin': '0',
                          'selected': [],
                          'IsFromDB': false,
                          'IsMultiple': false,
                          'OperatorEnabled': false,
                          'FieldEnabled': false,
                          'FieldValues': [
                              {
                                  'ViewRuleGroupFieldsID': 0,
                                  'FieldValue': '',
                                  'IsFromDB': false
                              }
                          ]
                      }
                  ]
              }
        ];
    }

    this.assignFieldsSorting = function (sortList, displayColList) {
        var obj = [];
        if (sortList != null && sortList && sortList.length > 0) {
            obj = sortList;
        }
        if (obj.length == 0 || displayColList.length == 0) {
            obj.push({
                'SortID': -1,
                'FieldMappingID': 0,
                'SortDirection': '',
                'Sequence': obj.length + 1
            });
            obj.push({
                'SortID': -2,
                'FieldMappingID': 0,
                'SortDirection': '',
                'Sequence': obj.length + 1
            });

        }
        if ((obj.length != 0 && obj.length <= 1) && displayColList.length != 0 && displayColList.length <= 1) {
            obj.push({
                'SortID': -1,
                'FieldMappingID': 0,
                'SortDirection': '',
                'Sequence': obj.length + 1
            });
        }
        else if (obj.length != 0 && obj.length <= 1 && obj.length < 2 && displayColList.length > 2) {
            obj.push({
                'SortID': -1,
                'FieldMappingID': 0,
                'SortDirection': '',
                'Sequence': obj.length + 1
            });
        }
        else if (obj.length != 0 && obj.length <= 1 && obj.length < 2 && displayColList.length > 2) {
            obj.push({
                'SortID': -1,
                'FieldMappingID': 0,
                'SortDirection': '',
                'Sequence': obj.length + 1
            });
            obj.push({
                'SortID': -1,
                'FieldMappingID': 0,
                'SortDirection': '',
                'Sequence': obj.length + 1
            });
        }
        return obj;
    }

    this.clearList = function (clearEnabledOnly) {
        if (clearEnabledOnly == true) {
            advlist = $filter('filter')(advlist, { AllowRemove: false }, true);
        }
        else {
            advlist = this.getDefaultList();
        }
    }

    this.checkIsContainDisabledRules = function () {
        var count = 0;
        var obj;
        obj = $filter('filter')(advlist, { AllowRemove: false }, true);
        if (obj != null && obj.length > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    this.validateAdvanceRules = function () {
        return validateRules();
    }

    function validateRules() {
        var isValid = true;
        var errMessage = "Please fill in all mandatory fields";
        //.filter((element) => element.flags.some((subElement) => subElement.completed === false));
        //var rules = $filter('filter')(advlist.RuleGroup, { DisplayField: 0 });
        //var rules = advlist.RuleGroup.filter((element) => element.RuleGroup.some((subElement) => subElement.FieldOperator == 0));
        //var rules = $filter('filter')(advlist.RuleGroup);
        //if (rules != undefined && rules.length > 0) {
        //    isValid = false;
        //}

        var rulesOperator = $filter('filter')(advlist.RuleGroup, { FieldOperator: 0 });
        if (rulesOperator != undefined && rulesOperator.length > 0) {
            isValid = false;
        }

        if (!isValid) {
            console.log('error');
            swal({
                title: errMessage,
                text: "",
                type: "warning",
                timer: 2500
            });
        }
        return isValid;

    }
    this.setPermissionUser = function (item) {
        permissionUsers = item;
    } 

    this.getPermissionUser = function () {
        return permissionUsers;
    }

    this.setPermissionRole = function (item) {
        permissionRoles = item;
    }

    this.getPermissionRole = function () {
        return permissionRoles;
    }


    this.setPermissionType = function (item) {
        permissionType = item;
    }

    this.getPermissionType = function () {
        return permissionType;
    }

    this.getPermissionSetting = function () {
        return permissionSetting;
    }
});