crmApp.controller("SysMaintenanceController", SysMaintenanceController);

//Variable passed in
//$scope.DisableDataFromDB
//$scope.PartialSelection
function SysMaintenanceController($scope, $window, $compile, $q, $http, $location, $filter, $timeout, $mdDialog, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder,
    AdvanceRulesService,
    GeneralService, AdminSI) {
    var vm = this;
    vm.multiSelect = {};
    vm.multiSelect.selected = [];
    vm.displaySetting;
    vm.permissionSetting;
    vm.isHCLEmailBlast = $window.isHCLEmailBlast;
    vm.init = function (page, showEditableColumns, showUserPermission) {
        vm.pageType = page;
        if (vm.isHCLEmailBlast)
            vm.pageType = 6;
        vm.showEditableColumns = showEditableColumns ? showEditableColumns : false;
        vm.showUserPermission = showUserPermission ? showUserPermission : false;

        vm.moneyValidation = GeneralService.Validation.MoneyWithNeg;
        vm.yearValidation = GeneralService.Validation.Year;
        vm.yearValidationMsg = GeneralService.Validation.YearMsg;
        vm.decimalValidation = GeneralService.Validation.Decimal;
        vm.decimalValidationMsg = GeneralService.Validation.DecimalMsg;

        getAdvanceRulesDropdown(page, 0);


        vm.dateOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1
        };
        vm.OperatorOptions = [];
        vm.FieldType = [12];

        // $scope.AdvanceRules = $scope.AdvanceRulesParent;
        vm.DisableDataFromDB = ($scope.DisableDataFromDB != undefined) ? $scope.DisableDataFromDB : false;
        //$scope.DisableAllRules = vm.DisableDataFromDB;
        $scope.AdvanceRules = AdvanceRulesService.getList();
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
        AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
        console.log('INIT Advance Rules', $scope.AdvanceRules);
        //}
        // else if (page == '2') {
        // }

        // Set rules based on parameter changed
        //$scope.$watch('clearAdvanceRules', function (newVal, oldVal) {
        //    // $scope.AdvanceRules = newVal;
        //    AdvanceRulesService.clearList();
        //    //AdvanceRulesService.addItem($scope.AdvanceRules);
        //    $scope.AdvanceRules = AdvanceRulesService.getList();
        //}, true);
        if ($scope.isSaveNewSeg === undefined) {
            $scope.$emit('AdvanceRules', 'ADVInitializeComplete');
        }
    }

    $scope.$on('AdvanceRules', function (event, data) {
        if (data == 'CLEAR') {
            vm.clearAllRules();
        }
        else if (data == 'LATESTDATA') {
            AdvanceRulesService.updateItem($scope.AdvanceRules);
        } else if (data == 'VALIDATE') {
            validateRules();
            event.preventDefault()
        }
        else if (data == 'GETDROPDOWN') {
            getAdvanceRulesDropdown(vm.pageType, $scope.jenisKempenID);
        } else if (data == 'POPULATEBASICRULES') {
            //AdminSI.getAdvanceRulesDropdown(vm.pageType, $scope.jenisKempenID).then(function (r) {
            //    for (var key in r.data) {
            //        vm[key] = r.data[key];
            //    }
            vm.AddNewRulesFromBasicOrDB();
            //});
        }
        else if (data == 'REFRESHADVRULES') {
            getAdvanceRulesDropdown(vm.pageType, $scope.jenisKempenID).then(function (data) {
                $scope.AdvanceRules = AdvanceRulesService.getList();
            });
        }
    });

    vm.multiSelectOnSelected = function (parentRuleIndex, childRuleIndex, ruleGroupID) {
        //do selectedItem.PropertyName like selectedItem.Name or selectedItem.Key 
        //whatever property your list has.
        console.log('multiselected : ', vm.multiSelect.selected);
        //updateFieldValues(parentRuleIndex, childRuleIndex, , ruleGroupFieldsID, false);
        updateFieldValues(parentRuleIndex, childRuleIndex, ruleGroupID);
    }
    vm.AssignToOnSelected = function (parentRuleIndex, childRuleIndex, ruleGroupID) {
        //do selectedItem.PropertyName like selectedItem.Name or selectedItem.Key 
        //whatever property your list has.
        console.log('multiselected : ', vm.multiSelect.selected);
        //Remain last selected value
        if ($scope.AdvanceRules[parentRuleIndex]
            .RuleGroup[childRuleIndex].selected.length > 1)
            $scope.AdvanceRules[parentRuleIndex]
                   .RuleGroup[childRuleIndex].selected = [$scope.AdvanceRules[parentRuleIndex].
                                                           RuleGroup[childRuleIndex].selected[$scope.AdvanceRules[parentRuleIndex].
                                                           RuleGroup[childRuleIndex].selected.length - 1]];
        //updateFieldValues(parentRuleIndex, childRuleIndex, , ruleGroupFieldsID, false);
        updateFieldValues(parentRuleIndex, childRuleIndex, ruleGroupID);
    }
    vm.multiSelectOnRemoved = function (parentRuleIndex, childRuleIndex) {
        //do selectedItem.PropertyName like selectedItem.Name or selectedItem.Key 
        //whatever property your list has.
        console.log('multiremoved : ', vm.multiSelect.selected);
        updateFieldValues(parentRuleIndex, childRuleIndex);
    }

    vm.clearAllRules = function () {
        AdvanceRulesService.clearList(AdvanceRulesService.getClearEnabledOnly());
        $scope.AdvanceRules = AdvanceRulesService.getList();
    }

    vm.clearDate = function (model) {
        model = '';
    }

    vm.operatorOnChanged = function (parentRuleIndex, childRuleIndex) {
        var selectedRules = $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex];
        var isMultipleInd = checkOperatorIsMultiple(selectedRules);
        //angular.forEach($scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues, function (value, key) {
        //    $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues[key].IsMultiple = isMultipleInd;

        //    $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues[key].FieldValue = $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues[key].FieldValue;
        //});
        if ($scope.fieldOperatorOptionsNewSeg)
            vm.FieldOperatorOptions = $scope.fieldOperatorOptionsNewSeg;
        var fieldOps = $filter('filter')(vm.FieldOperatorOptions, { DataTypeID: selectedRules.FieldOperator }, true);

        if (fieldOps != undefined && fieldOps.length > 0) {
            console.log("Selected operator", fieldOps);
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperatorCode = fieldOps[0].OperatorCode;
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldEnabled = true;
            if ($scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldType == 52) {
                if ($scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperator == 32 || $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperator == 42 || $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperator == 43
                     || $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperator == 44 || $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperator == 45 || $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperator == 46) {
                    $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues[0].FieldValue = '[System Generated Date]';
                }
                else
                {
                    $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues[0].FieldValue = '';
                }

            }
        } else {
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldEnabled = false;
        }
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        console.log('operatorOnChanged', $scope.AdvanceRules);
    };

    vm.fieldOnChange = function (parentRuleIndex, childRuleIndex, id) {

        if (id == null || id == undefined) {
            vm.OperatorOptions[childRuleIndex] = [];
            vm.FieldType[childRuleIndex] = 12;
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldEnabled = false;
            return false;
        }
        if ($scope.fieldMappingOptionsNewSeg)
            vm.FieldMappingOptions = $scope.fieldMappingOptionsNewSeg;

        if ($scope.jenisKempenOptionsNewSeg)
            vm['JenisKempenIDOptions'] = $scope.jenisKempenOptionsNewSeg;

        // Find selected Field mapping object
        var selectedObjList = $filter('filter')(vm.FieldMappingOptions, { FieldMappingID: id }, true);
        var selectedObj = selectedObjList[0];
        var fieldOps = $filter('filter')(vm.FieldOperatorOptions, { LookupParamSysID: selectedObj.FieldType });
        if (selectedObj.FieldType == '15' || selectedObj.FieldType == '50' || selectedObj.FieldType == '51') {
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues = [];
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldEnabled = false;
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected = [];
            vm.multiSelect.selected = [];
        }
        else
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues = [{ 'FieldValue': '', 'IsMultiple': false }];

        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldType = selectedObj.FieldType;
        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldMapping = selectedObj.FieldMapping;
        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].IsInnerJoin = selectedObj.IsInnerJoin;

        // Assign field operators
        if (fieldOps.length != 0) {
            // Populate drop down value
            if ((selectedObj.FieldType == '15' || selectedObj.FieldType == '50' || selectedObj.FieldType == '51') && selectedObj.FieldMappingRef != undefined) //&& selectedObj.FieldMappingRef.toLowerCase() == 'ref_lookupparam'
            {
                var optionsKey = selectedObj.FieldMappingRefCode + 'Options';
                $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOptions = vm[optionsKey];
            }
            // Default select the only options left
            if (fieldOps.length == 1) {
                $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldOperator = fieldOps[0].DataTypeID;
                vm.operatorOnChanged(parentRuleIndex, childRuleIndex);
            }

            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].OperatorOptions = fieldOps;

            if (vm.OperatorOptions.length == parentRuleIndex) {
                console.log('Operator options spliced');
                vm.OperatorOptions.splice(parentRuleIndex, 0, fieldOps);
                vm.FieldType.splice(parentRuleIndex, 0, selectedObj.FieldType);
            }
            else {
                vm.OperatorOptions[parentRuleIndex] = fieldOps;
                vm.FieldType[parentRuleIndex] = selectedObj.FieldType;
            }
        }
        else {
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].OperatorOptions = [];
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOption = [];
            vm.OperatorOptions = [{}];
        }

        AdvanceRulesService.updateItem($scope.AdvanceRules);
        console.log('field on change', $scope.AdvanceRules);
    };

    vm.submitAdvanceRules = function () {
        var objRules = $scope.AdvanceRules;
        //console.log(objRules);
        return AdminSI.UpdateAdvanceRules(objRules).then(function (r) {
            if (r.status == 200) {

            }

        });
    };

    vm.AddNewRules = function (i, d) {
        $scope.AdvanceRules = AdvanceRulesService.getList();
        $scope.AdvanceRules.splice(i, 0, {
            'ViewRuleID': -1 * (i + 1),
            'Sequence': i + 1,
            'RuleType': '1',
            'RuleOperator': d,
            'GroupingOperator': '',
            'RowSelected': false,
            'AllowRemove': true,
            'AllowSelectOperator': true,
            'IsFromDB': false,
            RuleGroup: [
                {
                    'ViewRuleGroupID': -1 * (i + 1),
                    'DisplayField': null,
                    'FieldType': '12',
                    'OperatorOptions': [],
                    'ValueOptions': [],
                    'FieldMapping': '',
                    'TableName': '',
                    'FieldOperator': '0',
                    'FieldOperatorCode': '0',
                    'FieldMappingRef': '0',
                    'FieldMappingRefCode': '0',
                    'IsInnerJoin': '0',
                    'selected': [],
                    'IsFromDB': false,
                    'IsMultiple': false,
                    'OperatorEnabled': false,
                    'FieldEnabled': false,
                    'FieldValues': [
                        {
                            'FieldValue': '',
                            'IsMultiple': false,
                            'IsFromDB': false
                        }
                    ]
                }
            ]
        });

        setSequence($scope.AdvanceRules, i + 1);
        var disabledRules = $filter('filter')($scope.AdvanceRules, { AllowRemove: false });
        if (disabledRules != null && disabledRules.length > 0) disabledRules[disabledRules.length - 1].AllowSelectOperator = true;
        console.log($scope.AdvanceRules);
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        //console.log($scope.AdvanceRules);
    };

    vm.InitializeAdvanceRulesFromDB = function () {

    };

    vm.AddNewRulesFromBasicOrDB = function () {
        // Get data from parents
        var tableType = $scope.tableType;
        var jenisKempenID = $scope.jenisKempenID;
        var i = $scope.rulesIndex;
        var d = $scope.rulesOperator;
        var fieldType = $scope.rulefieldType;
        var fieldOperator = $scope.rulefieldOperator;
        var fieldValue = $scope.rulesFieldValue;
        var fieldMapping = $scope.rulesFieldMapping;
        var rulesType = $scope.rulesType;
        var groupingOperator = $scope.groupingOperator;
        var ruleID = $scope.ruleID;
        var ruleGroupID = $scope.ruleGroupID;
        var isFromDB = $scope.isFromDB;
        var allowRemove = true;
        var allowEdit = true;
        var ruleGroupFieldsID = $scope.ruleGroupFieldsID;
        var ruleGroupsIndex = $scope.ruleGroupsIndex; //SL added
        //var fieldOps = $filter('filter')($scope.AdvanceRules, function (item) {
        //    angular.forEach(item, function (ruleGroup, key) {
        //    });
        //});
        var isRefresh = false;
        //variable scope DisableDataFromDB will override allowRemove and allowEdit
        if ($scope.DisableDataFromDB != undefined && $scope.DisableDataFromDB === true && isFromDB) {
            vm.DisableDataFromDB = $scope.DisableDataFromDB;
            allowRemove = false;
            allowEdit = false;
        }
        else {
            allowRemove = AdvanceRulesService.getAllowRemove();
            allowEdit = AdvanceRulesService.getAllowEdit();
        }
        $scope.AdvanceRules = AdvanceRulesService.getList();
        if ($scope.fieldOperatorOptionsNewSeg)
            vm.FieldOperatorOptions = $scope.fieldOperatorOptionsNewSeg;
        var fieldOps = $filter('filter')(vm.FieldOperatorOptions, { LookupParamSysID: fieldType, OperatorCode: fieldOperator });
        var selectedField;
        if ($scope.fieldMappingOptionsNewSeg) {
            vm.FieldMappingOptions = $scope.fieldMappingOptionsNewSeg;
            selectedField = $filter('filter')(vm.FieldMappingOptions, { FieldMapping: fieldMapping, FieldType: fieldType, JenisKempenID: jenisKempenID }, true);

            processAdvanceRules(selectedField, fieldOps, tableType, jenisKempenID, i,
                           d, fieldType, fieldOperator, fieldValue, fieldMapping,
                           rulesType, groupingOperator, ruleID, ruleGroupID, isFromDB,
                           ruleGroupID, ruleGroupFieldsID, allowRemove, allowEdit);
        }
        else if ($scope.IsRefreshFieldMapping) {
            console.log('Refresh Field Mapping on add new rules from basic or DB');
            //getAdvanceRulesDropdown(vm.pageType, $scope.jenisKempenID).then(function (data) {
            //    selectedField = $filter('filter')(vm.FieldMappingOptions, { FieldMapping: fieldMapping, FieldType: fieldType, JenisKempenID: jenisKempenID }, true);
            //    processAdvanceRules(selectedField);
            //});

            AdminSI.getAdvanceRulesDropdown(vm.pageType, jenisKempenID).then(function (r) {

                $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                for (var key in r.data) {
                    vm[key] = r.data[key];
                }
                vm.PartialFieldMappingOptions = $filter('filter')(vm.FieldMappingOptions, { DisplayField: 0 });
                $scope.displaySetting.FieldMappings = vm.FieldMappingOptions;
                AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                AdvanceRulesService.setOriDisplaySetting();
                console.log('displaysetting', $scope.displaySetting);

                if ($scope.isSaveNewSeg !== undefined) {
                    $scope.$emit('AdvanceRules', 'ADVInitializeComplete');
                }

                if (vm.pageType == 5)
                    selectedField = $filter('filter')(vm.FieldMappingOptions, {
                        FieldMapping: fieldMapping, FieldType: fieldType, JenisKempenID: jenisKempenID
                    }, true);
                else
                    selectedField = $filter('filter')(vm.FieldMappingOptions, {
                        FieldMapping: fieldMapping, FieldType: fieldType
                    }, true);
                processAdvanceRules(selectedField, fieldOps, tableType, jenisKempenID, i,
                               d, fieldType, fieldOperator, fieldValue, fieldMapping,
                               rulesType, groupingOperator, ruleID, ruleGroupID, isFromDB,
                               ruleGroupID, ruleGroupFieldsID, allowRemove, allowEdit);
            });
        }
        else {
            if (vm.pageType == 5)
                selectedField = $filter('filter')(vm.FieldMappingOptions, {
                    FieldMapping: fieldMapping, FieldType: fieldType, JenisKempenID: jenisKempenID
                }, true);
            else
                selectedField = $filter('filter')(vm.FieldMappingOptions, {
                    FieldMapping: fieldMapping, FieldType: fieldType
                }, true);

            processAdvanceRules(selectedField, fieldOps, tableType, jenisKempenID, i,
                               d, fieldType, fieldOperator, fieldValue, fieldMapping,
                               rulesType, groupingOperator, ruleID, ruleGroupID, isFromDB,
                               ruleGroupID, ruleGroupFieldsID, allowRemove, allowEdit, ruleGroupsIndex); //SL ADD ruleGroupsIndex TO CATER FOR FIRST RULE IS MANY VIEWRULEGROUP. D 
        }

        //var selectedFieldMappingID;
        //if (selectedField == undefined) {
        //    selectedFieldMappingID
        //} else { selectedFieldMappingID = selectedField[0].FieldMappingID; }

        //// remove initial row for the first inserted new rules
        //if (i == 0) $scope.AdvanceRules = [];

        ////dont allow outbound jeniskempen to be removed
        ////if (tableType == 5) {
        ////    if (fieldMapping == "JenisKempenID") {
        ////        allowRemove = false;
        ////        allowEdit = true;
        ////    }
        ////}
        ////variable scope DisableDataFromDB will override allowRemove and allowEdit
        //if ($scope.DisableDataFromDB != undefined && $scope.DisableDataFromDB === true && isFromDB) {
        //    allowRemove = false;
        //    allowEdit = false;
        //}
        //else {
        //    if ($scope.AllowRemove != undefined) {
        //        allowRemove = $scope.AllowRemove
        //    }
        //    else {
        //        allowRemove = true;
        //    }
        //    if ($scope.AllowEdit != undefined) {
        //        allowEdit = $scope.AllowEdit
        //    }
        //    else {
        //        allowEdit = true;
        //    }
        //}

        //$scope.AdvanceRules.splice(i, 0, {
        //    'ViewRuleID': ruleID,
        //    'Sequence': i + 1,
        //    'RuleType': rulesType,
        //    'RuleOperator': d,
        //    'GroupingOperator': groupingOperator,
        //    'RowSelected': false,
        //    'AllowRemove': allowRemove,
        //    'IsFromDB': isFromDB,
        //    RuleGroup: [
        //        {
        //            'ViewRuleGroupID': ruleGroupID,
        //            'ViewRuleID': ruleID,
        //            'DisplayField': selectedFieldMappingID,
        //            'FieldType': fieldType,
        //            'OperatorOptions': [],
        //            'ValueOptions': [],
        //            'FieldMapping': '',
        //            'TableName': '',
        //            'FieldOperator': fieldOps[0].DataTypeID,
        //            'FieldOperatorCode': fieldOperator,
        //            'FieldMappingRef': '0',
        //            'FieldMappingRefCode': '0',
        //            'IsInnerJoin': '0',
        //            'selected': [],
        //            'IsFromDB': isFromDB,
        //            'IsMultiple': false,
        //            'FieldEnabled': allowEdit,
        //            'FieldValues': [
        //                //{
        //                //    'FieldValue': fieldValue
        //                //}
        //            ]
        //        }
        //    ]
        //});

        //setSequence($scope.AdvanceRules, i + 1);
        //console.log($scope.AdvanceRules);

        //// Get dropdown options for Operators
        //vm.fieldOnChange(i, 0, selectedFieldMappingID);

        //// Set field value after set Operator options based on field type
        //if (fieldType == 15) { //Dropdown
        //    $scope.AdvanceRules[i].RuleGroup[0].selected = [];
        //    angular.forEach(fieldValue, function (obj) {
        //        $scope.AdvanceRules[i].RuleGroup[0].selected.push(obj.FieldValue);
        //    });
        //    console.log('multiSelect', $scope.AdvanceRules[i].RuleGroup[0].selected);
        //    updateFieldValues(i, 0);
        //} else {// String
        //    //$scope.AdvanceRules[i].RuleGroup[0].FieldValues.push({ 'FieldValue': fieldValue[0].FieldValue, 'IsMultiple' : false});
        //    if (fieldType == 14) {
        //        $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].FieldValue = new Date(fieldValue[0].FieldValue);
        //    }
        //    else {
        //        $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].FieldValue = fieldValue[0].FieldValue;
        //    }
        //    $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].IsFromDB = fieldValue[0].IsFromDB;
        //    $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].ViewRuleGroupFieldsID = fieldValue[0].ViewRuleGroupFieldsID;
        //    $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].ViewRuleGroupID = ruleGroupID;
        //}
        //AdvanceRulesService.updateItem($scope.AdvanceRules);
        //console.log($scope.AdvanceRules);
    };

    function processAdvanceRules(selectedField, fieldOps, tableType, jenisKempenID, i,
                                d, fieldType, fieldOperator, fieldValue, fieldMapping,
                                rulesType, groupingOperator, ruleID, ruleGroupID, isFromDB,
                                ruleGroupID, ruleGroupFieldsID, allowRemove, allowEdit, ruleGroupsIndex) {

        var selectedFieldMappingID;
        if (selectedField == undefined) {
            selectedFieldMappingID
        } else { selectedFieldMappingID = selectedField[0].FieldMappingID; }

        //SL added ruleGroupsIndex
        // remove initial row for the first inserted new rules
        if (i == 0 && !ruleGroupsIndex) $scope.AdvanceRules = [];

        //dont allow outbound jeniskempen to be removed
        //if (tableType == 5) {
        //    if (fieldMapping == "JenisKempenID") {
        //        allowRemove = false;
        //        allowEdit = true;
        //    }
        //}


        //variable scope DisableDataFromDB will override allowRemove and allowEdit
        //if ($scope.DisableDataFromDB != undefined && $scope.DisableDataFromDB === true && isFromDB) {
        //    vm.DisableDataFromDB = $scope.DisableDataFromDB;
        //    allowRemove = false;
        //    allowEdit = false;
        //}
        //else {

        //        allowRemove = AdvanceRulesService.getAllowRemove();

        //    //if (!allowRemove) AdvanceRulesService.setAllowRemove(true);
        //    allowEdit = AdvanceRulesService.getAllowEdit();
        //    //if (!allowEdit) AdvanceRulesService.setAllowEdit(true);
        //    //if ($scope.AllowRemove != undefined) {              
        //    //    $scope.AllowRemove = undefined;
        //    //}
        //    //else {
        //    //    allowRemove = true;
        //    //}
        //    //if ($scope.AllowEdit != undefined) {
        //    //    allowEdit = $scope.AllowEdit
        //    //}
        //    //else {
        //    //    allowEdit = true;
        //    //}
        //}
        var childIndex = 0;
        // Bind to existing rule if exits else push as new rules (grouping scenario)
        var existingRule = $filter('filter')($scope.AdvanceRules, { ViewRuleID: ruleID }, true);
        if (existingRule != undefined && existingRule != null && existingRule.length > 0) {
            existingRule[0].RuleGroup.push({
                'ViewRuleGroupID': ruleGroupID,
                'ViewRuleID': ruleID,
                'DisplayField': selectedFieldMappingID,
                'FieldType': fieldType,
                'OperatorOptions': [],
                'ValueOptions': [],
                'FieldMapping': '',
                'TableName': '',
                'FieldOperator': fieldOps[0].DataTypeID,
                'FieldOperatorCode': fieldOperator,
                'FieldMappingRef': '0',
                'FieldMappingRefCode': '0',
                'IsInnerJoin': '0',
                'selected': [],
                'IsFromDB': isFromDB,
                'IsMultiple': false,
                'FieldEnabled': allowEdit,
                'FieldValues': [
                    //{
                    //    'FieldValue': fieldValue
                    //}
                ]
            });
            childIndex = existingRule[0].RuleGroup.length - 1;
        }
        else {
            $scope.AdvanceRules.splice(i, 0, {
                'ViewRuleID': ruleID,
                'Sequence': i + 1,
                'RuleType': rulesType,
                'RuleOperator': d,
                'GroupingOperator': groupingOperator,
                'RowSelected': false,
                'AllowRemove': allowRemove,
                'AllowSelectOperator': allowRemove,
                'IsFromDB': isFromDB,
                RuleGroup: [
            {
                'ViewRuleGroupID': ruleGroupID,
                'ViewRuleID': ruleID,
                'DisplayField': selectedFieldMappingID,
                'FieldType': fieldType,
                'OperatorOptions': [],
                'ValueOptions': [],
                'FieldMapping': '',
                'TableName': '',
                'FieldOperator': fieldOps[0].DataTypeID,
                'FieldOperatorCode': fieldOperator,
                'FieldMappingRef': '0',
                'FieldMappingRefCode': '0',
                'IsInnerJoin': '0',
                'selected': [],
                'IsFromDB': isFromDB,
                'IsMultiple': false,
                'FieldEnabled': allowEdit,
                'FieldValues': [
                    //{
                    //    'FieldValue': fieldValue
                    //}
                ]
            }
                ]
            });
        }

        setSequence($scope.AdvanceRules, i + 1);
        console.log($scope.AdvanceRules);

        // Get dropdown options for Operators
        vm.fieldOnChange(i, childIndex, selectedFieldMappingID);

        // Set field value after set Operator options based on field type
        if (fieldType == 15 || fieldType == 50 || fieldType == 51) { //Dropdown
            $scope.AdvanceRules[i].RuleGroup[childIndex].selected = [];//SL 0 substitute with childIndex??
            angular.forEach(fieldValue, function (obj) {
                $scope.AdvanceRules[i].RuleGroup[childIndex].selected.push([obj.ViewRuleGroupFieldsID, obj.FieldValue]);
            });
            console.log('multiSelect', $scope.AdvanceRules[i].RuleGroup[childIndex].selected);
            updateFieldValues(i, childIndex, ruleGroupID, ruleGroupFieldsID, isFromDB);//SL USE CHILDINDEX INSTEAD OF 0
        } else {// String
            //$scope.AdvanceRules[i].RuleGroup[0].FieldValues.push({ 'FieldValue': fieldValue[0].FieldValue, 'IsMultiple' : false});
            if (fieldType == 14 || fieldType == 52) {
                //$scope.AdvanceRules[i].RuleGroup[childIndex].FieldValues[0].FieldValue = new Date(fieldValue[0].FieldValue);
                if ($scope.AdvanceRules[i].RuleGroup[childIndex].FieldOperator != 32 && $scope.AdvanceRules[i].RuleGroup[childIndex].FieldOperator != 42 && $scope.AdvanceRules[i].RuleGroup[childIndex].FieldOperator != 43
                    && $scope.AdvanceRules[i].RuleGroup[childIndex].FieldOperator != 44 && $scope.AdvanceRules[i].RuleGroup[childIndex].FieldOperator != 45 && $scope.AdvanceRules[i].RuleGroup[childIndex].FieldOperator != 46) {
                    $scope.AdvanceRules[i].RuleGroup[childIndex].FieldValues[0].FieldValue = new Date(fieldValue[0].FieldValue).toLocaleString();
                }
                else {
                    $scope.AdvanceRules[i].RuleGroup[childIndex].FieldValues[0].FieldValue = fieldValue[0].FieldValue;
                }
            }
            else {
                $scope.AdvanceRules[i].RuleGroup[childIndex].FieldValues[0].FieldValue = fieldValue[0].FieldValue;
            }
            $scope.AdvanceRules[i].RuleGroup[childIndex].FieldValues[0].IsFromDB = fieldValue[0].IsFromDB;
            $scope.AdvanceRules[i].RuleGroup[childIndex].FieldValues[0].ViewRuleGroupFieldsID = fieldValue[0].ViewRuleGroupFieldsID;
            $scope.AdvanceRules[i].RuleGroup[childIndex].FieldValues[0].ViewRuleGroupID = ruleGroupID;
        }
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        console.log($scope.AdvanceRules);
    }

    vm.operatorChanged = function (i, d) {

        if (d != '0') {
            vm.AddNewRules(i, d);
        }
    }

    vm.addNewRule = function (i) {
        //$timeout(function () {
        // Add new rule below the clicked icon row
        vm.AddNewRules(i + 1, '1')
        //}, 500);
    }

    vm.removeRules = function () {

        var newDataList = [];
        $scope.selectedAll = false;
        var selectedObj = $filter('filter')($scope.AdvanceRules, { RowSelected: true }, true);
        var remainObj = $filter('filter')($scope.AdvanceRules, { RowSelected: false }, true);

        if (selectedObj == undefined || selectedObj.length == 0) {
            swal({
                title: "Please select at least one rule.",
                text: "",
                type: "warning",
                timer: 2500
            });
            return false;
        }
        //vm.OperatorOptions.splice(i, 1);
        //angular.forEach($scope.AdvanceRules, function (selected) {
        //    $scope.AdvanceRules = [];
        //    if (!selected.selected) {
        //        //selected.Sequence = newDataList.length + 1,
        //        $scope.AdvanceRules.push(selected);
        //    }
        //});
        $scope.AdvanceRules = remainObj;

        if ($scope.AdvanceRules.length == 0) {
            $scope.AdvanceRules = AdvanceRulesService.getDefaultList();
        }
        else {
            console.log($scope.AdvanceRules);
            console.log('Set Sequence ' + selectedObj[0].Sequence);
            setSequence($scope.AdvanceRules, selectedObj[0].Sequence - 1);
        }
        console.log($scope.AdvanceRules);
        AdvanceRulesService.updateItem($scope.AdvanceRules);

    };

    function getAdvanceRulesDropdown(page, jenisKempen) {
        return $q(function () {
            var deferred = $q.defer();
            if (jenisKempen == null || jenisKempen == '') jenisKempen = 0;
            AdminSI.getAdvanceRulesDropdown(page, jenisKempen).then(function (r) {

                $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                deferred.resolve(r.data);
                for (var key in r.data) {
                    vm[key] = r.data[key];
                }
                console.log('Dropdown : ', +r.data);
                vm.PartialFieldMappingOptions = $filter('filter')(vm.FieldMappingOptions, { DisplayField: 0 });
                $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                $scope.displaySetting.FieldMappings = vm.FieldMappingOptions;
                AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                AdvanceRulesService.setOriDisplaySetting();
                console.log('displaysetting', $scope.displaySetting);
                if ($scope.isSaveNewSeg !== undefined) {
                    $scope.$emit('AdvanceRules', 'ADVInitializeComplete');
                }
                return deferred.promise;
            });
        });
    }

    function updateFieldValues(parentRuleIndex, childRuleIndex, ruleGroupID, ruleGroupFieldsID, isFromDB) {
        var selectedRules = $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex];
        if (selectedRules != undefined) {
            var selectedFieldValues = selectedRules.FieldValues;
            // Clear array before any actions taken
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues = [];
            var isMultipleInd = checkOperatorIsMultiple(selectedRules);
            var intFieldCount = 0;
            // Loop through item to add value
            for (var i = 0; i < $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected.length; i++) {//SL edited in changeset 4567
                var FieldValue = $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected[i];

                if (angular.isArray(FieldValue)) {
                    var dbRuleGroupFieldsID = FieldValue[0];
                    FieldValue = FieldValue[1];
                    $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected[i] = FieldValue;
                }
                ruleGroupFieldsID = (dbRuleGroupFieldsID != undefined && dbRuleGroupFieldsID != null) ? dbRuleGroupFieldsID : (++intFieldCount) * -1;
                isFromDB = (isFromDB != undefined && isFromDB != null) ? isFromDB : 0;
                ruleGroupID = (ruleGroupID != undefined && ruleGroupID != null) ? ruleGroupID : $scope.ruleGroupID;

                if ($scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldType == 51) {
                    AdminSI.searchUnitByIDForAdvancedRules(FieldValue).then(function (result) {
                        // $scope.AdvanceRules = AdvanceRulesService.getList();
                        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected = [FieldValue];
                        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOptions = [result.data];
                        AdvanceRulesService.updateItem($scope.AdvanceRules);
                    });
                }
                else if ($scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldType == 50) {
                    AdminSI.searchUserByIDForAdvancedRules(FieldValue).then(function (result) {
                        // $scope.AdvanceRules = AdvanceRulesService.getList();
                        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected = [FieldValue];
                        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOptions = [result.data];
                        AdvanceRulesService.updateItem($scope.AdvanceRules);
                    });
                }

                $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues
                .push({ 'ViewRuleGroupFieldsID': ruleGroupFieldsID, 'ViewRuleGroupID': ruleGroupID, 'FieldValue': FieldValue, 'IsFromDB': isFromDB });
            };

            AdvanceRulesService.updateItem($scope.AdvanceRules);
            console.log("updateFieldValues", $scope.AdvanceRules);
        }
    }

    function validateRules() {
        var isValid = true;
        var errMessage = "Please fill in all mandatory fields";

        var rules = $filter('filter')($scope.AdvanceRules, {
            DisplayField: 0
        });
        if (rules != undefined && rules.length > 0) {
            isValid = false;
        }

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

        angular.forEach($scope.AdvanceRules, function (rules, key) {
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues
                .push({ 'FieldValue': value, 'IsMultiple': isMultipleInd });
        });

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

    }

    function checkOperatorIsMultiple(selectedRules) {
        var isMultipleInd = false;
        if (selectedRules.FieldType == 15 || selectedRules.FieldType == 50 || selectedRules.FieldType == 51) { // dropdown scenario
            if (selectedRules.FieldOperator != 0) {
                var fieldOps = $filter('filter')(vm.FieldOperatorOptions, {
                    DataTypeID: selectedRules.FieldOperator
                });
                console.log("Check Is Multiple", fieldOps);
                if (fieldOps != undefined && fieldOps.length > 0) {
                    isMultipleInd = fieldOps[0].IsMultiple;
                    console.log(isMultipleInd);
                }
            }
        }
        return isMultipleInd;
    }

    function setSequence(obj, i) {

        if (obj.length >= i) {
            // Increment sequence
            for (var idx = i; idx < obj.length; idx++) {
                var objRule = obj[idx];
                if (objRule != undefined) {
                    objRule.Sequence = idx + 1;
                }
            }
        }
    }

    vm.groupRules = function (d) {

        var arrRules = $filter('filter')($scope.AdvanceRules, {
            RowSelected: true
        }, true);
        var arrRulesNotSelected = $filter('filter')($scope.AdvanceRules, {
            RowSelected: false
        }, true);
        // Validation
        if (arrRules.length <= 1) {
            swal({
                title: "Please select at least two rules for grouping.",
                text: "",
                type: "warning",
                timer: 2500
            });
            return false;
        }

        var itemCount = 0;
        var idx = 0;
        var rulesNotSelectedCount = arrRulesNotSelected != null ? arrRulesNotSelected.length : 0;
        var newViewRuleID = vm.checkDuplicateID(arrRulesNotSelected, rulesNotSelectedCount);
        arrRules.forEach(function (obj) {
            itemCount++;
            var fieldValue = obj.RuleGroup[0].FieldValues[0];

            if (obj.RuleGroup[0].FieldType == 51) {
                AdminSI.searchUnitByIDForAdvancedRules(fieldValue.FieldValue).then(function (result) {
                    // $scope.AdvanceRules = AdvanceRulesService.getList();
                    obj.RuleGroup[0].ValueOptions = [result.data];
                    AdvanceRulesService.updateItem($scope.AdvanceRules);
                });
            }
            else if (obj.RuleGroup[0].FieldType == 50) {
                AdminSI.searchUserByIDForAdvancedRules(fieldValue.FieldValue).then(function (result) {
                    // $scope.AdvanceRules = AdvanceRulesService.getList();
                    obj.RuleGroup[0].selected = [fieldValue.FieldValue];
                    obj.RuleGroup[0].ValueOptions = [result.data];
                    AdvanceRulesService.updateItem($scope.AdvanceRules);
                });
            }


            var newID = -1 * newViewRuleID;
            var currentItemIdx = $scope.AdvanceRules.indexOf(obj);
            if (itemCount == 1) {
                idx = currentItemIdx;


                obj.ViewRuleID = newID;
                obj.IsFromDB = false;
                var ruleCount = 0;
                obj.RuleGroup.forEach(function (objRuleGroup) {
                    var fieldCount = 0;
                    ruleCount++;
                    objRuleGroup.ViewRuleGroupID = -1 * ruleCount;
                    objRuleGroup.ViewRuleID = newID;
                    objRuleGroup.IsFromDB = false;
                    objRuleGroup.FieldValues.forEach(function (fieldItem) {
                        fieldCount++;
                        fieldItem.ViewRuleGroupFieldsID = -1 * (fieldCount);
                        fieldItem.ViewRuleGroupID = objRuleGroup.ViewRuleGroupID;
                        fieldItem.IsFromDB = false;
                    });
                });
                objGrouping = {
                    'ViewRuleID': newID,
                    'Sequence': 1,
                    'RuleType': '2',
                    'RuleOperator': d,
                    'GroupingOperator': d,
                    'AllowRemove': true,
                    'AllowSelectOperator': true,
                    'RowSelected': false,
                    'IsFromDB': false,
                    RuleGroup: obj.RuleGroup
                };
            }
            else {

                obj.ViewRuleID = newID;
                obj.IsFromDB = false;
                var ruleCount = 0;
                obj.RuleGroup.forEach(function (objRuleGroup) {
                    var fieldCount = 0;
                    ruleCount++;
                    objRuleGroup.ViewRuleGroupID = -1 * itemCount;
                    objRuleGroup.ViewRuleID = newID;
                    objRuleGroup.IsFromDB = false;
                    objRuleGroup.FieldValues.forEach(function (fieldItem) {
                        fieldCount++;
                        fieldItem.ViewRuleGroupFieldsID = -1 * (fieldCount);
                        fieldItem.ViewRuleGroupID = objRuleGroup.ViewRuleGroupID;
                        fieldItem.IsFromDB = false;
                    });
                    objGrouping.RuleGroup.push(objRuleGroup);
                });
            }
            // Remove current item after added into group
            $scope.AdvanceRules.splice(currentItemIdx, 1);
        });

        // Add grouped items into array
        $scope.AdvanceRules.splice(idx, 0, objGrouping);

        setSequence($scope.AdvanceRules, idx - 1);
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        console.log($scope.AdvanceRules);

    };

    vm.checkDuplicateID = function (obj, id) {
        var item = $filter('filter')(obj, { ViewRuleID: id });
        var result = id;
        if (item != null && item.length > 0) { result = vm.checkDuplicateID(obj, id + 1); }

        return result;
    }

    vm.unGroupRules = function (idx, d) {
        var arrRules = $scope.AdvanceRules[idx];
        console.log(d);
        var itemCount = 0;
        var arrLength = arrRules.RuleGroup.length;
        $scope.AdvanceRules.splice(idx, 1);
        arrRules.RuleGroup.forEach(function (objRuleGroup) {
            var newID = -1 * (itemCount + 1);
            objGrouping = {
                'ViewRuleID': newID,
                'Sequence': idx + 1,
                'RuleType': '1',
                'RuleOperator': d,
                'GroupingOperator': '',
                'AllowRemove': true,
                'AllowSelectOperator': true,
                'RowSelected': false,
                'IsFromDB': false,
                RuleGroup: []
            };
            objRuleGroup.ViewRuleGroupID = newID;
            objRuleGroup.ViewRuleID = newID;
            objRuleGroup.IsFromDB = false;
            var fieldvalueCount = 0;
            var fieldValue = objRuleGroup.FieldValues[0];
            if (objRuleGroup.FieldType == 51) {
                AdminSI.searchUnitByIDForAdvancedRules(fieldValue.FieldValue).then(function (result) {
                    objRuleGroup.ValueOptions = [result.data];
                    AdvanceRulesService.updateItem($scope.AdvanceRules);
                });
            }
            else if (objRuleGroup.FieldType == 50) {
                AdminSI.searchUserByIDForAdvancedRules(fieldValue.FieldValue).then(function (result) {
                    objRuleGroup.selected = [fieldValue.FieldValue];
                    objRuleGroup.ValueOptions = [result.data];
                    AdvanceRulesService.updateItem($scope.AdvanceRules);
                });
            }

            objRuleGroup.FieldValues.forEach(function (objRuleGroupFields) {
                fieldvalueCount++;

                objRuleGroupFields.ViewRuleGroupFieldsID = -1 * fieldvalueCount;
                objRuleGroupFields.ViewRuleGroupID = newID;
                objRuleGroupFields.IsFromDB = false;
            });

            objGrouping.RuleGroup.push(objRuleGroup);
            $scope.AdvanceRules.splice(idx + itemCount, 0, objGrouping);
            itemCount++;
        });
        if (arrLength == 1) {
            $scope.AdvanceRules[$scope.AdvanceRules.length - 1].RuleOperator = '';
        }

        setSequence($scope.AdvanceRules, idx + 1);

        AdvanceRulesService.updateItem($scope.AdvanceRules);
        console.log($scope.AdvanceRules);
    };

    vm.openDialogV2 = function (e, id) {
        $mdDialog.show({
            contentElement: id,
            parent: angular.element(document.body),
            targetEvent: e,
            clickOutsideToClose: false
        });
    }


    vm.SearchByName = function (query, parentRuleIndex, childRuleIndex, fieldType) {
        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOptions = [];
        vm.loading = true;
        if (query && query.length > 2) {
            if (fieldType == 51) {
                AdminSI.searchUnitForAdvancedRules(query).then(function (r) {// Search Unit
                    if (r.data != null) {
                        var m = r.data;
                        if (m.length != 0) {
                            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOptions = m;
                        }
                    } vm.loading = false;

                });
            }
            else if (fieldType == 50) {// Search User
                AdminSI.searchUserForAdvancedRules(query).then(function (r) {
                    if (r.data != null) {
                        var m = r.data;
                        if (m.length != 0) {
                            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOptions = m;
                        }
                    } vm.loading = false;

                });
            }
        }

    }

}


crmApp.controller("AdvancedDisplayColumnController", AdvancedDisplayColumnController);

function AdvancedDisplayColumnController($scope, $window, $compile, $mdDialog, $filter,
    DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, GeneralService, AdvanceRulesService) {

    var vm = this;
    vm.init = function () {
        $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
        console.log('child display setting', $scope.displaySetting);
    }

    vm.addNewDisplayField = function (list) {
        if (list != null) {
            console.log($scope.displaySetting);
            var displayColumn = [];
            displayColumn = {
                Sequence: list.length + 1,
                FieldMappingID: 0
            };
            list.push(displayColumn);
        }
    }

    vm.removeDisplayFieldRow = function (list, index) {
        if (list != null) {
            list.splice(index, 1);
            vm.sortList(list);
            console.log('Display setting removed : ', $scope.displaySetting);
        }
    }

    vm.sortList = function (list) {
        angular.forEach(list, function (item, d) {
            item.Sequence = d + 1;
        });
    }

    //Field mapping list
    vm.sortableListOptions = {
        stop: function (e, ui) {
            vm.sortList($scope.displaySetting.Dis);
        }
    };

    $scope.$on('AdvanceRules_DisplayColumn', function (event, data) {
        if (data == 'INIT') {
            vm.init();
        }
    });

    vm.XOR = function (a, b) {
        // return ( a || b ) || !( a && b );
        return (a ? 1 : 0) ^ (b ? 1 : 0);
    }
    vm.bitOR = function (a, b) {
        console.log(a | b);
        return a | b;
    }

    vm.sortList = function (list) {
        angular.forEach(list, function (item, d) {
            item.Sequence = d + 1;
        });
    }

    vm.confirmDisplaySetting = function (list, sortList) {
        AdvanceRulesService.setDynamicDisplayInd(true);
        var isInvalid = false;
        angular.forEach(list, function (item, d) {
            if (!item.FieldMappingID) { item.Invalid = true; isInvalid = true; }//SL edited if(item.FieldMappingID==0)
        });
        if (isInvalid) {
            swal("Gagal!", "Sila isi semua ruangan.");
            return;
        }
        else {
            var obj = AdvanceRulesService.getDisplaySetting();
            vm.sortList(list);
            obj.DisplayColumns = list;
            obj.FieldsSorting = sortList;
            AdvanceRulesService.updateDisplaySetting(obj);
            console.log('Confirm Display Setting', obj);
        }
        $mdDialog.hide();
    }

    vm.resetDisplaySetting = function () {
        AdvanceRulesService.resetDisplaySetting();
    }

    vm.validateSelection = function (field, fieldMappingList, list) {
        var filteredList = [];

        if (list != null && list.length > 1) {
            var filteredList = $filter('filter')(list, function (item) {
                return field.FieldMappingID != 0 && item.FieldMappingID == field.FieldMappingID;
            });
        }
        console.log('filteredList', filteredList);
        if (filteredList.length > 1) {
            swal("Gagal!", "Kod medan hanya boleh dipilih sekali sahaja.", "error");
            field.isInvalid = true;
            field.FieldCode = "";
        }
        else {
            field.isInvalid = false;
            var fieldMapping = $filter('filter')(fieldMappingList, function (item) {
                return item.FieldMappingID == field.FieldMappingID;
            });
            if (fieldMapping.length > 0) {
                field.FieldMappingCode = fieldMapping[0].FieldMapping;
                field.DisplayField = fieldMapping[0].DisplayField;
            }
        }
    }

    vm.close = function () {
        vm.resetDisplaySetting();
        $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
        $mdDialog.hide();
    }
}


crmApp.controller("AdvancedViewPermissionController", AdvancedViewPermissionController);

function AdvancedViewPermissionController($scope, $window, $compile, $mdDialog, $filter,
    DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, GeneralService, AdvanceRulesService, AdminSI, UserSI) {
    var vm = this;
    var constOnlyMeCode = '1';
    var constSpecificUserCode = '3';
    vm.showSpecificUserPanel = false;
    vm.UserRoleType = 'P';

    vm.init = function () {
        AdminSI.getViewPermissionDropdown().then(function (r) {
            if (r.status === 200) {
                $scope.permissionSetting = r.data;
            }

        });

        vm.SelectedTimbalanUser = "";
        vm.SelectedJabatanUser = "";
        vm.SelectedCawanganUser = "";
        vm.SelectedUnitsUser = "";
        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;

        GetUserGroupHierarcyOptions();

        //console.log('permission user list', $scope.permissionUsers);  

    }



    vm.bindlist = function () {
        $scope.permissionUsers = AdvanceRulesService.getPermissionUser();
        $scope.permissionRoles = AdvanceRulesService.getPermissionRole();
        $scope.permissionSetting.PermissionTypeID = AdvanceRulesService.getPermissionType();
        vm.permissionUsersOri = $.extend(true, [], $scope.permissionUsers);
        vm.permissionRolesOri = $.extend(true, [], $scope.permissionRoles);
        vm.PermissionTypeIDOri = $scope.permissionSetting.PermissionTypeID;//$.extend(true, [], $scope.permissionSetting.PermissionTypeID);
        vm.permissionTypeChange($scope.permissionSetting.PermissionTypeID);
        vm.CheckRecord();
    }

    vm.addNewPermission = function () {

        if (validateAddMember()) {

            var user = $filter('filter')($scope.permissionUsers, { UserProfileID: vm.AssignToUser.UserProfileID }, true);
            if (user.length > 0) {
                swal("Gagal", "Pengguna ini telah ditambah", "error");
            }
            else {
                var member = [];
                member = {
                    IsNew: true,
                    LoginID: vm.AssignToUser.ID,
                    DisplayName: vm.AssignToUser.DisplayName,
                    UserProfileID: vm.AssignToUser.UserProfileID,
                }
                $scope.permissionUsers.unshift(member);
                AdvanceRulesService.setPermissionUser($scope.permissionUsers);
                vm.CheckRecord();
            }
            vm.reset();
        }

    }

    vm.addNewRole = function () {

        if (validateAddRole()) {

            var role = $filter('filter')($scope.permissionRoles, { FunctionalRoleID: vm.AssignRole.FunctionalRoleID }, true);
            if (role.length > 0) {
                swal("Gagal", "Role ini telah ditambah", "error");
            }
            else {
                var newrole = [];
                newrole = {
                    IsNew: true,
                    FunctionalRoleID: vm.AssignRole.FunctionalRoleID,
                    RoleName: vm.AssignRole.RoleName
                }
                $scope.permissionRoles.unshift(newrole);
                AdvanceRulesService.setPermissionRole($scope.permissionRoles);
                vm.CheckRecord();
            }
            vm.reset();
        }

    }

    vm.removePermissionRow = function (list, index) {
        if (list != null) {
            $scope.permissionUsers.splice(index, 1);
            AdvanceRulesService.setPermissionUser($scope.permissionUsers);
            vm.CheckRecord();
        }
    }

    vm.removeRoleRow = function (list, index) {
        if (list != null) {
            $scope.permissionRoles.splice(index, 1);
            AdvanceRulesService.setPermissionRole($scope.permissionRoles);
            vm.CheckRecord();
        }
    }
    vm.CheckRecord = function () {
        vm.showRoleNoRecord = $scope.permissionRoles == null || $scope.permissionRoles.length == 0;
        vm.showUserNoRecord = $scope.permissionUsers == null || $scope.permissionUsers.length == 0;

    }

    vm.reset = function () {
        vm.AssignToUser = null;
        vm.AssignRole = null;
    }

    vm.ResetUserHierarchy = function () {
        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;
        vm.NoUserMessage = false;

        vm.SelectedTimbalanUser = "";
        vm.SelectedJabatanUser = "";
        vm.SelectedCawanganUser = "";
        vm.SelectedUnitsUser = "";
        vm.AssignToUser = "";

        vm.filteredWorkflowAssignToJabatanUserOption = [];
        vm.filteredWorkflowAssignToCawanganUserOption = [];
        vm.filteredWorkflowAssignToUnitUserOption = [];
        vm.UserResultOption = [];

        vm.JabatanUserOption = [];
        vm.CawanganUserOption = [];
        //vm.UnitOption = [];
    }
    function validateAddMember() {
        //initialize
        if ($scope.permissionUsers == null || $scope.permissionUsers == undefined)
            $scope.permissionUsers = [];


        if (!vm.AssignToUser || vm.AssignToUser == null) {
            vm.showUserRequiredMsg = true;
            return false;
        }
        else
            return true;
    }

    function validateAddRole() {
        //initialize
        if ($scope.permissionRoles == null || $scope.permissionRoles == undefined)
            $scope.permissionRoles = [];


        if (!vm.AssignRole || vm.AssignRole == null) {
            vm.showRoleRequiredMsg = true;
            return false;
        }
        else
            return true;
    }
    $scope.$on('AdvanceRules_Permission', function (event, data) {
        if (data == 'INIT') {
            vm.bindlist();
        }
    });

    vm.Cancel = function () {
        $scope.permissionUsers = vm.permissionUsersOri;
        $scope.permissionRoles = vm.permissionRolesOri;
        $scope.permissionSetting.PermissionTypeID = vm.PermissionTypeIDOri;
        AdvanceRulesService.setPermissionUser($scope.permissionUsers);
        AdvanceRulesService.setPermissionRole($scope.permissionRoles);
        AdvanceRulesService.setPermissionType($scope.permissionSetting.PermissionTypeID);
        vm.permissionTypeChange($scope.permissionSetting.PermissionTypeID);
        vm.CheckRecord();
        vm.reset();
        $mdDialog.hide();
    }

    vm.Close = function () {
        $mdDialog.hide();
    }

    vm.permissionTypeChange = function (id) {

        if (!id) { //if id is null, assign default value - Only Me
            var defaultType = $filter('filter')($scope.permissionSetting.PermissionTypeOptions, {
                "Code": constOnlyMeCode
            }, true);
            id = defaultType.length > 0 ? defaultType[0].Value : id;
            $scope.permissionSetting.PermissionTypeID = id;
            vm.showSpecificUserPanel = defaultType.length > 0 && defaultType[0].Code == constSpecificUserCode;
        }
        else {
            var filtered = $filter('filter')($scope.permissionSetting.PermissionTypeOptions, {
                "Value": id
            }, true);
            if (filtered.length > 0 && filtered[0].Code == constSpecificUserCode) {
                vm.showSpecificUserPanel = true;
            }
            else {
                $scope.permissionUsers = [];
                $scope.permissionRoles = [];
                AdvanceRulesService.setPermissionUser($scope.permissionUsers);
                AdvanceRulesService.setPermissionRole($scope.permissionRoles);
                vm.showSpecificUserPanel = false;
            }
        }
        AdvanceRulesService.setPermissionType(id);
    }


    function GetUserGroupHierarcyOptions() {
        UserSI.getUserGroupHierarcyOptions().then(function (r) {
            if (r.status === 200) {
                if (r.data) {

                    vm.WorkflowAssignToSeksyenUserOption = r.data["WorkflowAssignToSeksyenOption"];
                    vm.WorkflowAssignToJabatanUserOption = r.data["WorkflowAssignToJabatanOption"];
                    vm.WorkflowAssignToCawanganUserOption = r.data["WorkflowAssignToCawanganOption"];
                    vm.WorkflowAssignToUnitUserOption = r.data["WorkflowAssignToUnitOption"];
                }
            }
        });
    }


    function SearchUserByUnitID(selectedUnitID) {
        if (selectedUnitID) {
            vm.NoUserMessage = false;
            vm.UserResultOption = [];
            vm.AssignToUser = "";
            UserSI.searchUserByUnitID(selectedUnitID).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        vm.UserResultOption = r.data;

                        if (vm.UserResultOption.length == 0) {
                            vm.NoUserMessage = true;
                        }
                    }
                }
            });
        }
    }

    vm.seksyenUserChange = function (selectedTimbalanUser) {
        vm.filteredWorkflowAssignToJabatanUserOption = [];
        if (selectedTimbalanUser != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                ParentUnitID: parseInt(selectedTimbalanUser)
            }, true);
            vm.filteredWorkflowAssignToJabatanUserOption = [];
            if (m != undefined && m.length != 0) {
                vm.filteredWorkflowAssignToJabatanUserOption = m;
            }

            SearchUserByUnitID(selectedTimbalanUser);
        }
        else {
            vm.AssignToUser = "";
        }
    };

    vm.jabatanUserChange = function (SelectedJabatanUser) {
        //enable upper hierarchy
        vm.SeksyenUserEnabled = true;

        vm.filteredWorkflowAssignToCawanganUserOption = [];

        if (SelectedJabatanUser != null) {
            //disable upper hierarchy
            vm.SeksyenEnabled = false;
            var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, {
                ParentUnitID: parseInt(SelectedJabatanUser)
            }, true);

            if (m != undefined && m.length != 0) {

                vm.filteredWorkflowAssignToCawanganUserOption = m;
            }
            SearchUserByUnitID(SelectedJabatanUser);

        } else {
            vm.AssignToUser = "";
        }
    };

    vm.cawanganUserChange = function (SelectedCawanganUser) {
        //enable upper hierarchy
        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;

        vm.filteredWorkflowAssignToUnitUserOption = [];

        if (SelectedCawanganUser != null) {
            //disable upper hierarchy
            vm.SeksyenUserEnabled = false;
            vm.JabatanUserEnabled = false;

            var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, {
                ParentUnitID: parseInt(SelectedCawanganUser)
            }, true);

            if (m != undefined && m.length != 0) {
                vm.filteredWorkflowAssignToUnitUserOption = m;
            }
            SearchUserByUnitID(SelectedCawanganUser);
        } else {
            vm.AssignToUser = "";
        }
    };

    vm.unitUserChange = function (SelectedUnitsUser) {
        SearchUserByUnitID(SelectedUnitsUser);
    };

    vm.SearchJabatanUser = function (query) {
        vm.JabatanUserOption = [];
        if (query.length > 1) {
            vm.JabatanUserOption = vm.WorkflowAssignToJabatanUserOption;
        }
    }

    vm.SearchCawanganUser = function (query) {
        vm.CawanganUserOption = [];
        if (query.length > 1) {
            vm.CawanganUserOption = vm.WorkflowAssignToCawanganUserOption;
        }
    }

    vm.ResetUserHierarchy = function () {
        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;
        vm.NoUserMessage = false;

        vm.SelectedTimbalanUser = "";
        vm.SelectedJabatanUser = "";
        vm.SelectedCawanganUser = "";
        vm.SelectedUnitsUser = "";
        vm.AssignToUser = "";

        vm.filteredWorkflowAssignToJabatanUserOption = [];
        vm.filteredWorkflowAssignToCawanganUserOption = [];
        vm.filteredWorkflowAssignToUnitUserOption = [];
        vm.UserResultOption = [];

        vm.JabatanUserOption = [];
        vm.CawanganUserOption = [];
        vm.UnitOption = [];
    }


    vm.SearchUserByName = function (query) {
        vm.UserResultOption = [];
        vm.loading = true;

        if (query.length > 2) {
            UserSI.searchUserByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UserResultOption = m;
                    }
                } vm.loading = false;
            });
        }

    }


    vm.ShowFilterUserOption = function () {
        if (!vm.showUserdetail) {
            vm.showUserdetail = true;
        }
        else {
            vm.ResetUserHierarchy();
            vm.showUserdetail = false;
        }
    }

    vm.SearchRoleByName = function (query) {
        vm.RoleResultOption = [];
        vm.roleloading = true;

        if (query.length > 2) {
            UserSI.searchRoleByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.RoleResultOption = m;
                    }
                } vm.roleloading = false;
            });
        }

    }
}