crmApp.controller("CaseReassignmentController", CaseReassignmentController);

function CaseReassignmentController($scope, $window, $q, $mdDialog,
                                 DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, $compile,
                                 AntiForgeryService, $timeout, localStorageService, $http, CaseSI, UserSI) {

    vm = this;
    vm.ShowFilter = false;
    var constAssignToTypeUnit = 20;
    var constAssignToTypeUser = 21;

    vm.showdetail = false;
    vm.dtInstanceAssign = {};
    vm.blnValid = true;
    $scope.SelectedID = {
        IDs: []
    };

    $scope.selectedList = {
        List: []
    };

    vm.init = function () {
        vm.SelectAll = false;
        GetDefaultManager();

        CaseSI.getCaseReassignDropdown().then(function (r) {
            if (r.status == 200) {
                for (var key in r.data) {
                    vm[key] = r.data[key];
                }

                vm.WorkflowAssignToSeksyenOptionDocUnit = r.data["WorkflowAssignToSeksyenOption"];
                vm.WorkflowAssignToJabatanOptionDocUnit = r.data["WorkflowAssignToJabatanOption"];
                vm.WorkflowAssignToCawanganOptionDocUnit = r.data["WorkflowAssignToCawanganOption"];
                vm.WorkflowAssignToUnitOptionDocUnit = r.data["WorkflowAssignToUnitOption"];

                var m = $filter('filter')(vm.WorkflowAssignToTypeOption, { IsDefault: true }, true);
                if (m && (m.length > 0)) {
                    vm.Other = m[0].Value;
                }
            }
        });
    };

    // Load Outbound Manual Assign 
    var ajaxCallback = function (data, callback, settings) {
        data.RefNo = vm.RefNo;
        data.AssignToTypeID = vm.AssignToTypeID;
        data.AssignBy = vm.AssignBy;
        data.Kategori1ID = vm.Kategori1ID;
        data.AssignTo = vm.casesAssignTo;
        CaseSI.getCaseReassignListing(data).then(function (r) {
            if (r.status == 200) {
                if (r.data.recordsTotal > 0)
                    vm.ShowAssignButton = true
                currentItems = r.data.WorkflowList;
                console.log(r.data);
                callback(r.data);
            }
        });
    }

    vm.ShowPopup = function (e) {

        if (!$scope.selectedList.List || $scope.selectedList.List.length == 0) {
            swal("Amaran!", "Sila pilih satu rekod untuk pengagihan.", "warning");
            return;
        } else if (vm.SelectAll) {
            swal({
                title: "Adakah anda pasti untuk agih kesemua " + currentItems.length + " rekod?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: true,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {
                    openDialogPopup(e);
                }
            });
        }
        else {
            openDialogPopup(e);
            //vm.SelectedTimbalan = "";
            //vm.SelectedJabatan = "";
            //vm.SelectedCawangan = "";
            //vm.SelectedUnits = "";

            //vm.SeksyenEnabled = true;
            //vm.JabatanEnabled = true;
            //vm.NoUserMessage = false;

            ////if (vm.DefaultManager && vm.DefaultManager != null)
            ////    vm.AssignTo = vm.DefaultManager;

            ////// trigger db call only if unit type is selected and kategori value has changed
            ////if (vm.UserType == constAssignToTypeUnit && isKategoriChanged)
            ////    vm.searchforUnit();

            //vm.openDialog(e, '#WorkflowActionDialog');
        }
    }

    function openDialogPopup(e) {

        vm.SelectedTimbalan = "";
        vm.SelectedJabatan = "";
        vm.SelectedCawangan = "";
        vm.SelectedUnits = "";

        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;
        vm.NoUserMessage = false;

        //if (vm.DefaultManager && vm.DefaultManager != null)
        //    vm.AssignTo = vm.DefaultManager;

        //// trigger db call only if unit type is selected and kategori value has changed
        //if (vm.UserType == constAssignToTypeUnit && isKategoriChanged)
        //    vm.searchforUnit();

        vm.openDialog(e, '#WorkflowActionDialog');
    }

    vm.searchforUser = function () {
        //21-->Get default people value for Submit To
        var data = {
            keyword: "",
            AssignToType: constAssignToTypeUser
        }

        CaseSI.getWorkFlowSearchUserOrUnit(data).then(function (u) {
            if (u.data.length > 0) {
                var m = u.data;
                if (m.length != 0) {
                    vm.Users = m;
                    vm.TempUser = vm.Users[0];
                    vm.AssignTo = vm.Users[0];
                    vm.UserType = constAssignToTypeUser;
                    vm.AssignToDisable = true;
                    vm.AssignOther = false;
                    vm.showdetail = false;

                }
            }
            else {
                vm.AssignTo = null;
                vm.UserType = constAssignToTypeUser;
                vm.AssignToDisable = false;
                vm.AssignOther = false;
                vm.showdetail = false;
            }
        });
    }

    vm.searchforOther = function () {
        vm.AssignTo = null;
        vm.UserType = 0;
        vm.AssignToDisable = false;
        vm.AssignOther = true;
    }

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

    var titleHtml = '<input type="checkbox" ng-model="cases.SelectAll" ng-click="cases.SelectAllRecords($event)">';
    function renderCaselink(data, type, row, meta) {

        var link = '<a href="/Case/Profile/detail/' + row.ProfileID + '" target="_blank">' + row.RefNo + '</a>';
        if (row.RefNo == undefined || row.RefNo == '0' || !row.RefNo)
            link = '-';
        return link
    }

    vm.dtColumnsAssign = [
        DTColumnBuilder.newColumn("WorkflowID").withTitle(titleHtml)
                .notSortable().withOption("searchable", false)
                //.renderWith(function (data) {
                .renderWith(function (data, type, row) {
                    var idx;
                    var blnChecked = vm.SelectAll;
                    var wfID = data;
                    var item = $filter('filter')($scope.selectedList.List, { WorkFlowID: wfID }, true);

                    //Check if Select All button is checked
                    if (vm.selectAll) {
                        blnChecked = true;
                    }
                    else {
                        //Check if item inside the local storage list
                        (item && item.length > 0) ? blnChecked = true : blnChecked = false;
                    }
                    return ' <input id="' + wfID + '" ' +
                        'type="checkbox" ' +
                        (blnChecked ? 'checked="checked"' : "") +
                        ' ng-click="cases.RecordSelected($event, ' + wfID + ')" />'
                }),
         DTColumnBuilder.newColumn('RefNo').withTitle('No. Kes').renderWith(renderCaselink),
         DTColumnBuilder.newColumn('AssignToTypeDesc').withTitle('Jenis Pengagihan'),
         DTColumnBuilder.newColumn('DayTaken').withTitle('Bil. Hari'),
         DTColumnBuilder.newColumn('Kategori').withTitle('Kategori'),
         DTColumnBuilder.newColumn('ActChannelName').withTitle('Aktiviti'),
         DTColumnBuilder.newColumn('AliranDesc').withTitle('Aliran'),
         DTColumnBuilder.newColumn('AssignTo').withTitle('Diagihkan Kepada'),
         DTColumnBuilder.newColumn('CreatedBy').withTitle('Dihasilkan Oleh'),
         DTColumnBuilder.newColumn('CreatedDatetime').withTitle('Tarikh Dihasilkan').renderWith(function (data, type) {
             return $filter('date')(data, $scope.DateTimeFormat);
         })
    ];

    vm.dtOptionsAssign = DTOptionsBuilder.newOptions()
        .withOption('ajax', ajaxCallback)
        .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);
        });

    vm.SelectAllRecords = function (e) {
        //vm.selectedCount = totalCountByPage;
        $scope.SelectedID.IDs = [];
        $scope.selectedList.List = [];
        if (vm.SelectAll) { //tick
            for (var i = 0, l = currentItems.length; i < l; i++) {
                vm.ProcessAllRecords(vm.SelectAll, currentItems[i].WorkFlowID);
            }
        }
        var table = $(e.target).closest('table');
        $('td input:checkbox', table).prop('checked', vm.SelectAll);
        console.log("selected list", $scope.selectedList.List);
        console.log("selected ID", $scope.SelectedID.IDs);
        //Set Display selected count
        //vm.selectedCount = $scope.SelectedCertPoList.CertPoList.length;
    }

    vm.ProcessAllRecords = function (isAllChecked, id) {

        pushToList(id);

        //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;
    }

    vm.RecordSelected = function ($event, id) {
        if ($event.currentTarget.checked) { //tick
            pushToList(id);
            if ($scope.selectedList.List.length == currentItems.length) { vm.SelectAll = true; }
        }
        else { //untick
            removeFromList(id);
            vm.SelectAll = false;
        }
        console.log("selected list", $scope.selectedList.List);
        console.log("selected ID", $scope.SelectedID.IDs);
    }

    function pushToList(id) {
        $scope.SelectedID.IDs.push(id);
        $scope.selectedList.List.push({ WorkFlowID: id})
    }

    function removeFromList(id) {
        var terminate = false;
        $scope.selectedList.List = $scope.selectedList.List.filter(function (obj) {
            return obj.WorkFlowID != id;
        });
        $scope.SelectedID.IDs = $scope.selectedList.List.filter(function (obj) {
            return obj != id;
        });

        //for (var i = 0, l = $scope.selectedList.List.length; i < l; i++) {
        //    if (!terminate) {
        //        if ($scope.selectedList.List[i].WorkFlowID == id) {
        //            //$scope.selectedList.List.splice(i, 1);
        //            var item = { WorkFlowID: id };
        //            var idx = $scope.selectedList.List.indexOf(item);
        //            if (idx != -1) {
        //                $scope.selectedList.List.splice(idx, 1);
        //                $scope.SelectedID.IDs.splice(idx, 1);
        //            }
        //            terminate = true;
        //        }
        //    }
        //}
        //var idx = $scope.selectedList.List.indexOf(id);
        //$scope.selectedList.List.splice(idx, 1);
        //$scope.SelectedID.IDs.splice(idx, 1);
    }

    vm.searchCaseAssignment = function () {
        vm.blnValid = true;
        if (vm.blnValid)
        {
            vm.dtInstanceAssign.reloadData();
        }
    }

    vm.clearCaseAssignment = function () {
        vm.RefNo = "";
        vm.Kategori1ID = 0;
        vm.AssignBy = "";
        vm.AssignToTypeID = 0;
        vm.casesAssignTo = "";
        vm.blnValid = false;
    }

    function SearchUserByUnitID(selectedUnitID) {

        if (selectedUnitID) {
            vm.NoUserMessage = false;
            vm.UserResultOption = [];
            vm.AssignTo = "";
            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.seksyenChange = function (selectedTimbalan) {

        vm.casesWorkflowAssignToJabatanOption = [];

        if (selectedTimbalan != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ParentUnitID: parseInt(selectedTimbalan) }, true);

            if (m != undefined && m.length != 0) {
                vm.casesWorkflowAssignToJabatanOption = m;
            }
            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(selectedTimbalan);
            }
        }

    };

    vm.jabatanChange = function (SelectedJabatan) {
        //enable upper hierarchy
        vm.SeksyenEnabled = true;

        vm.casesWorkflowAssignToCawanganOption = [];

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

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

                vm.casesWorkflowAssignToCawanganOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedJabatan);
            }
        }

    };

    vm.cawanganChange = function (SelectedCawangan) {

        //enable upper hierarchy
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;

        vm.casesWorkflowAssignToUnitOption = [];

        if (SelectedCawangan != null) {
            //disable upper hierarchy
            vm.SeksyenEnabled = false;
            vm.JabatanEnabled = false;

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

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

                vm.casesWorkflowAssignToUnitOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedCawangan);
            }

        }

    };

    vm.unitChange = function (SelectedUnits) {

        if (vm.Other == constAssignToTypeUser) {
            SearchUserByUnitID(SelectedUnits);
        }
    };

    vm.ResetHierarchy = function () {
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;
        vm.NoUserMessage = false;

        vm.SelectedTimbalan = "";
        vm.SelectedJabatan = "";
        vm.SelectedCawangan = "";
        vm.SelectedUnits = "";
        vm.AssignTo = "";

        vm.casesWorkflowAssignToJabatanOption = [];
        vm.casesWorkflowAssignToCawanganOption = [];
        vm.casesWorkflowAssignToUnitOption = [];
        vm.UserResultOption = [];

        vm.JabatanOption = [];
        vm.CawanganOption = [];
        vm.UnitOption = [];
    }

    vm.SelectHierarchy = function () {
        vm.UserResultOption = [];
        m = [];

        if (vm.SelectedUnits != "" && vm.SelectedUnits != null) {
            m = $filter('filter')(vm.WorkflowAssignToUnitOption, { ID: vm.SelectedUnits }, true);
        }
        else if (vm.SelectedCawangan != "" && vm.SelectedCawangan != null) {
            m = $filter('filter')(vm.WorkflowAssignToCawanganOption, { ID: vm.SelectedCawangan }, true);
        }
        else if (vm.SelectedJabatan != "" && vm.SelectedJabatan != null) {
            m = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ID: vm.SelectedJabatan }, true);
        }

        else if (vm.SelectedTimbalan != "" && vm.SelectedTimbalan != null) {
            m = $filter('filter')(vm.WorkflowAssignToSeksyenOption, { ID: vm.SelectedTimbalan }, true);
        }

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

            vm.UserResultOption = m;
            vm.AssignTo = m[0];
        }

    }

    vm.SearchJabatan = function (query) {
        vm.JabatanOption = [];
        if (query.length > 1) {
            vm.JabatanOption = vm.WorkflowAssignToJabatanOption;
        }

    }

    vm.SearchCawangan = function (query) {

        vm.CawanganOption = [];
        if (query.length > 1) {
            vm.CawanganOption = vm.WorkflowAssignToCawanganOption;
        }

    }

    vm.CloseSearchHierary = function () {
        if (vm.SelectedUnits != "") {
            vm.SelectedUnits = "";
        }

        if (vm.SelectedCawangan != "") {
            vm.SelectedCawangan = "";
        }

        if (vm.SelectedJabatan != "") {
            vm.SelectedJabatan = "";
        }

        if (vm.SelectedTimbalan != "") {
            vm.SelectedTimbalan = "";
        }
    }

    vm.CancelSearchHierary = function (e) {
        $mdDialog.hide();
        vm.openDialog(e, '#WorkflowActionDialog');
    }

    vm.SearchUser = function (query, click) {
        vm.UsersOption = [];
        vm.loading = true;
        var UserType = vm.UserType;
        var data = {
            keyword: query,
            AssignToType: UserType

        }

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


                    }
                } vm.loading = false;
            });

        }

    }

    //Selected Submit To User
    vm.SelectUser = function (selectedItem) {
        vm.AssignTo = selectedItem;
    }

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

        if (vm.Other == constAssignToTypeUser && 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.SearchUnitByName = function (query) {
        vm.UserResultOption = [];
        vm.loading = true;

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

    //Selected Submit To User
    vm.SelectUserHierarchy = function (selectedItem) {
        vm.AssignTo = selectedItem;
    }

    vm.chooseOtherGroupOrUser = function () {
        vm.ResetHierarchy();
    }

    vm.ShowFilterOption = function () {
        if (!vm.showdetail) {
            //vm.optionWording = 'Hide Option';
            vm.showdetail = true;
        }
        else {
            //vm.optionWording = 'More Option';
            vm.showdetail = false;
        }
    }

    function GetDefaultManager() {
        UserSI.getDefaultManager().then(function (r) {
            if (r.status === 200) {
                if (r.data) {
                    vm.DefaultManager = r.data;
                    if (vm.DefaultManager && vm.DefaultManager.ID != null) {
                        vm.UserType = constAssignToTypeUser;
                        vm.AssignTo = vm.DefaultManager;
                    }
                    else {
                        vm.searchforOther();
                    }
                }
            }
        });
    }

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

    function validateAssignment() {
        if (!vm.AssignTo && vm.AssignTo == null) {
            swal("Failed", "Sila pilih agihan kepada.", "error");
            var deferred = $q.defer(); // required for click and disabled
            deferred.resolve('');
            result = deferred.promise;
            return false;
        }
        else if (vm.AssignTo.ManagerFunctionRoleID == null && vm.AssignTo.AssignToType == 20) {
            swal("Failed", "Tiada pengguna ditambah sebagai Manager. Sila pastikan pengguna ditambah sebagai Manager untuk unit yang dipilih.", "error");
            var deferred = $q.defer(); // required for click and disabled
            deferred.reject('');
            result = deferred.promise;
            vm.showValidationMsgPopup = true;
            vm.showValidationMsg = true;
            return false;
        }
        else if (vm.SelectAll) {
            if ($scope.selectedList.List.length > 1) {
                swal({
                    title: "Adakah anda pasti untuk mengagihkan semua rekod (Jumlah rekod:" + currentItems.length + ")?",
                    text: "",
                    type: "warning",
                    showCancelButton: false,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: true,
                    closeOnCancel: true
                }, function (isConfirm) {
                    return isConfirm;
                });
            }
        }
        return true;
    }

    vm.ReassignWorkflow = function () {
        if (validateAssignment()) {
            var workflowAction = {
                UserType: vm.UserType == 0 ? vm.AssignTo.AssignToType : vm.UserType,
                AssignTo: vm.AssignTo,
                DecisionID: 6
            }

            var WorkflowUpdate = {
                Workflow: workflowAction,
                WorkFlowList: $scope.selectedList.List,
                TableType: 1,
                SelectAll: vm.SelectAll
            }
            CaseSI.reassignBulkWorkflow(WorkflowUpdate).then(function (r) {
                if (r.status === 200) {
                    swal({
                        title: "Proses agihan kes berjaya dikemaskini.",
                        type: "success",
                        showConfirmButton: true
                    }, function () {
                        $scope.SelectedID.IDs = [];
                        $scope.selectedList.List = [];
                        vm.dtInstanceAssign.reloadData();
                        vm.CloseAssignCase();
                        return returnResultPromise();
                    });
                }
            });
        }
        else {
            return returnResultPromise();
        }
    }
    function returnResultPromise() {
        var result = null;
        var deferred = $q.defer();
        deferred.resolve('');
        result = deferred.promise;
        return result;
    }

}