crmApp.controller('OutboundManualAssignedController', function ($scope, $mdDialog, $window, AntiForgeryService, $compile, $q, $http, $location, $filter, DTOptionsBuilder, DTColumnBuilder, OutboundSI) {
    var vm = this;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;

    //CheckBox
    vm.selectPagefunc = selectPagefunc;
    vm.selectPage = false;
    vm.selectAll = false;
    vm.selectedCount;
    vm.AssignSelected = AssignSelected;
    var totalCountByPage = 0;
    var currentItems = {};
    $scope.SelectedOutboundID = {
        OutboundIDs: []
    };

    $scope.selectedOutboundList = {
        OutboundList: []
    };
    vm.SelectedOutboundList = {};
    // Checkbox

    // Load Outbound Manual Assign 
    var ajaxOCLManualAssignCallback = function (data, callback, settings) {
        data.JenisKempenID = vm.JenisKempenID;
        data.TPName = vm.TPName;
        OutboundSI.getOutboundManualAssignData(data).then(function (r) {
            if (r.status == 200) {
                if (r.data.recordsTotal > 0)
                    vm.OpenButton = true
                currentItems = r.data.data;
                callback(r.data);
            }
        });
    }

    vm.init = function () {
        vm.OCLShowFilter = false;

        OutboundSI.getDropdown(false).then(function (r) {
            for (var key in r.data) {
                vm[key] = r.data[key];
            }
        });
    };

    //Search Outbound Assign By Manager
    vm.dtInstanceManualOCLAssigned = {};
    vm.searchOutboundAssigned = function () {
        vm.blnValid = true;

        if (vm.blnValid) {
            vm.dtInstanceManualOCLAssigned.reloadData();
        };

    }

    vm.clearOutboundAssigned = function () {

        if (vm.JenisKempenID != null) vm.JenisKempenID = '';
        vm.TPName = '';
    }

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

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

    //Search User for Manual Assign Purpose
    vm.SearchUser = function (query, click) {
        vm.UsersOption = [];
        vm.loading = true;
        var data = {
            keyword: query,
        }

        if (query.length > 2) {
            // TODO : To search users from DB or AD
            OutboundSI.getSearchUser(data).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UsersOption = m;


                    }
                } vm.loading = false;
            });
        }
    }

    vm.SelectUser = function (selectedItem) {
        vm.AssignTo = selectedItem;
    }

    //Manual Assign Outbound to People
    vm.AssignToButton = function (isDirty, Form) {
        vm.showValidationMsgPopup = false;
        var result = null;
        if (Form.$valid) {

            if (isDirty) {
                var OutboundUpdate = {
                    Outbound: $scope.selectedOutboundList.OutboundList,
                    OutboundUser: vm.AssignTo,
                    Remark: vm.Remarks
                }

                result = OutboundSI.updatedOCLMangerAssign(OutboundUpdate);

                result.then(function (r) {
                    if (!r.status === 200) {
                        swal("Failed", r.data, "error");
                        return;
                    }

                    swal({
                        title: "Outbound Assignment",
                        text: 'Successfully Assigned. \n\n Total record that success assigned : ' + r.data.CountHavenAssignBeforeManualAssign + '\n Total record that has been assigned to other : ' + r.data.CountAlreadyAssignBeforeManualAssign,
                        type: "success",
                        timer: 9500,
                        showConfirmButton: true
                    }, function () {
                        if (r.data.recordsTotal > 0)
                            vm.OpenButton = true
                         vm.redirectTo('/Outbound/Assignment');
                    });
                });
            }

        }
        else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");

            var deferred = $q.defer(); // required for click and disabled
            deferred.reject('');
            result = deferred.promise;
            vm.showValidationMsgPopup = true;
            vm.showValidationMsg = true;
        }

        return result;
    }

    // Bind Table for Outbound Manual Assign New Page
    var titleHtml = '<input type="checkbox" ng-model="outbound.selectPage" ng-click="outbound.selectPagefunc(outbound.selectPage, outbound.selected)">';

    vm.dtColumnsManualOCLAssigned = [

        DTColumnBuilder.newColumn("OutboundID").withTitle(titleHtml)
                .notSortable().withOption("searchable", false)
                .renderWith(function (data) {
                    var idx;
                    var blnChecked = false;
                    idx = $scope.SelectedOutboundID.OutboundIDs.indexOf(data);

                    //Check if Select All button is checked
                    if (vm.selectAll) {
                        blnChecked = true;
                    }
                    else {
                        //Check if item inside the local storage list
                        idx != -1 ? blnChecked = true : blnChecked = false;
                    }

                    return ' <input id="' + data + '" ' +
                        'type="checkbox" ' +
                        (blnChecked ? 'checked="checked"' : "") +
                        ' ng-click="outbound.AssignSelected($event, ' + data + ')" />'
                }),

        //DTColumnBuilder.newColumn('OutboundID').withTitle('ID'),
         DTColumnBuilder.newColumn('TPName').withTitle('Nama'),
         DTColumnBuilder.newColumn('JenisKempenName').withTitle('Jenis Kempen'),
         DTColumnBuilder.newColumn('NoRujukanCukai').withTitle('No. Rujukan Cukai'),
         //DTColumnBuilder.newColumn('OutboundStatus').withTitle('Status'),
         DTColumnBuilder.newColumn('REMSDate').withTitle('Tarikh ReMS').renderWith(function (data, type) {
             if (data == null) {
                 return '-';
             }
             else {
                 return $filter('date')(data, $scope.DateFormat);
             }

         }).withOption('width', '15%'),

    ];

    vm.dtOptionsManualOCLAssigned = DTOptionsBuilder.newOptions()
        .withOption('ajax', ajaxOCLManualAssignCallback)
        .withDataProp('data')
        .withOption('processing', true)
        .withOption('searching', true)
        .withOption('serverSide', true)
        //.withOption('lengthChange', false)
        .withOption('autoWidth', false)
        .withPaginationType('full_numbers')
        //.withDisplayLength(5)
          .withOption('headerCallback', function (header) {
              if (!vm.headerCompiled) {
                  // Use this headerCompiled field to only compile header once
                  vm.headerCompiled = true;
                  $compile(angular.element(header).contents())($scope);
              }
          })
        .withOption('createdRow', function (row, data, dataIndex) {
            $compile(angular.element(row).contents())($scope);
        });

    //Bind Table - end

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

    //Allow pop up come out after select checkbox 
    vm.Assign = function (e) {
        $scope.selectedOutboundList.IsSelectAll = vm.selectAll;

        if ($scope.selectedOutboundList.OutboundList.length > 0) {
            vm.openDialog(e, '#OutboundManualAssignActionDialog');
        }
        else {
            swal("Gagal", "Please select records to proceed for assignment!", "error");
            clearObjList();
        }


    }

    vm.redirectTo = function (url) {

        $window.beforeUnloadCanceled = true;
        $window.location.href = url;
    }

    function selectPagefunc(selectPage, selectedItems) {
        //vm.selectedCount = totalCountByPage;
        for (var i = 0, l = currentItems.length; i < l; i++) {
            add(selectPage, currentItems[i].OutboundID);
        }

        //Set Display selected count
        //vm.selectedCount = $scope.SelectedCertPoList.CertPoList.length;
    }

    function add(status, OutboundID) {
        var queryResult = document.getElementById(OutboundID);

        if (vm.selectPage) { //tick
            queryResult.checked = true;

            if ($scope.SelectedOutboundID.OutboundIDs.indexOf(OutboundID) !== -1) { }
            else {
                pushToList(OutboundID);
            }
        }
        else { //untick
            queryResult.checked = false
            removeFromList(OutboundID);
        }

        //Validate Add To List button
        //vm.selectAll ? vm.disabledAddToList = false : $scope.SelectedOutboundID.OutboundIDs.length > 0 ? vm.disabledAddToList = false : vm.disabledAddToList = true;

        ////Set Display selected count
        //vm.selectedCount = $scope.SelectedOutboundID.OutboundIDs.length;
    }

    function pushToList(OutboundID) {
        $scope.SelectedOutboundID.OutboundIDs.push(OutboundID);
        $scope.selectedOutboundList.OutboundList.push({ OutboundID: OutboundID })
    }

    function removeFromList(OutboundID) {
        var terminate = false;
        for (var i = 0, l = $scope.selectedOutboundList.OutboundList.length; i < l; i++) {
            if (!terminate) {
                if ($scope.selectedOutboundList.OutboundList[i] == OutboundID) {
                    $scope.selectedOutboundList.OutboundList.splice(i, 1);
                    terminate = true;
                }
            }
        }
        var idx = $scope.selectedOutboundList.OutboundList.indexOf(OutboundID);
        $scope.selectedOutboundList.OutboundList.splice(idx, 1);
    }

    function AssignSelected($event, OutboundID) {
        if ($event.currentTarget.checked) { //tick
            pushToList(OutboundID);
        }
        else { //untick
            removeFromList(OutboundID);
            vm.selectPage = false;
        }
    }

    /* Clear Local Storage List*/
    function clearObjList() {
        //Delete all items
        var i = $scope.selectedOutboundList.OutboundList.length;
        while (i--) {
            $scope.selectedOutboundList.OutboundList.splice(i, 1);
        }

        //Delete all items
        var j = $scope.SelectedOutboundID.OutboundIDs.length;
        while (j--) {
            $scope.SelectedOutboundID.OutboundIDs.splice(i, 1);
        }
    }

})