crmApp.controller("TaskController", TaskController);
crmApp.controller("SearchTaskController", SearchTaskController);

function TaskController($scope, $window, $mdDialog, $q, $filter, DTOptionsBuilder, DTColumnBuilder, TaskSI, UserSI, AntiForgeryService, $compile, GeneralService) {
    var vm = this;
    vm.TaskId = $window.taskid;
    vm.CaseId = $window.caseid;
    vm.ActId = $window.actid;
    vm.RefNo = $window.refno;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    //vm.RegardingOptions = ['Not Related', 'Activity', 'Case'];
    vm.RegardingOptions = ['Tidak Berkenaan', 'Aktiviti', 'Kes'];
    var constNotRelated = "Tidak Berkenaan";
    var constAct = "Aktiviti";
    var constCase = "Kes";
    vm.dtInstanceRgdCase = {};
    vm.dtInstanceRgdAct = {};
    vm.task = {};
    vm.ChangesHistory = [];
    var oriRefNo = "";
    var oriRegarding = "";
    vm.showValidationMsg = false;
    vm.RefNoErr = false;
    vm.showErrInvalidDate = false;

    //used to identify <textarea> elements to be replaced by CKEditor instance
    editor = CKEDITOR.replace('TextArea_Description');

    vm.redirectTo = function (url) {
        $window.beforeUnloadCanceled = true;
        $window.location.href = url;
    }

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

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

    vm.init = function () {
        vm.IsNew = true;
        vm.UsersOption = [];
        vm.task.TaskStatusID = 261; //set to open
        vm.task.StartDate = $filter('date')(new Date(), $scope.DateFormat);
        vm.resetSearchCriteria();
        vm.showUserdetail = false;
        vm.ResetUserHierarchy();

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

        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;

        // datepicker
        vm.startDateMinDate = null;
        vm.startDateMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;
        vm.startDateOptions = {
            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.dueDateMinDate = null;
        vm.dueDateMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;
        vm.dueDateOptions = {
            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
        };

        GetUserGroupHierarcyOptions();

        //drop down menu
        TaskSI.getDropdown().then(function (r) {
            if (r.status === 200) {
                for (var key in r.data.data) {
                    vm[key] = r.data.data[key];
                }

                vm.Users = r.data.users;
                //bind AssignTo
                var m = $filter('filter')(vm.Users, r.data.currUser, true);
                if (m.length === 1) {
                    vm.task.AssignTo = m[0]; //set Pegawai Bertugas to sendiri
                }

                //export excel record
                var m = $filter('filter')(vm.ParameterSettings, { ParameterID: 22 }, true); 
                if (m && (m.length != 0)) {
                    vm.maxExportRecord = m[0].ParameterValue;
                }

                if (vm.CaseId > 0) {
                    vm.RegardingTxt = constCase;
                    vm.task.CaseID = vm.CaseId;
                    vm.task.RefNo = vm.RefNo;
                    vm.regardingURL = "/case/profile/detail/" + vm.CaseId;
                } else if (vm.ActId > 0) {
                    vm.RegardingTxt = constAct;
                    vm.task.ActivityID = vm.ActId;
                    vm.task.RefNo = vm.RefNo;
                    vm.regardingURL = "/activity/profile/detail/" + vm.ActId;
                } else if (vm.TaskId > 0) {
                    TaskSI.getTask(vm.TaskId).then(function (r) {
                        if (r.status === 200) {
                            vm.IsNew = false;
                            vm.task = r.data;
                            //py: special handle for sometimes ckeditor is empty - but not sure it is working
                            editor.setData(vm.task.Description);
                            setTimeout(function () {
                                editor.setData(vm.task.Description);
                            }, 1000);

                            if (r.data.IsPTP) { // SET both start date and due date - not allow to select earlier than today's date
                                vm.dueDateOptions = {
                                    minDate: (new Date()).setHours(0, 0, 0, 0), // 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.startDateOptions = {
                                    minDate: (new Date()).setHours(0, 0, 0, 0), // 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.task.DueDate = r.data.DueDate == null ? "" : $filter('date')(new Date(r.data.DueDate), $scope.DateFormat);
                            //vm.task.StartDate = r.data.StartDate == null ? "" : $filter('date')(new Date(r.data.StartDate), $scope.DateFormat);
                            vm.task.DueDate = r.data.DueDate == null ? "" : new Date(r.data.DueDate);
                            vm.task.StartDate = r.data.StartDate == null ? "" : new Date(r.data.StartDate);

                            //var id;
                            if (r.data.CaseID == null && r.data.ActivityID == null) {
                                vm.RegardingTxt = constNotRelated;
                                vm.regardingURL = "";
                                vm.task.RefNo = "";
                                oriRefNo = "";
                                oriRegarding = vm.RegardingTxt;
                            }
                            else if (r.data.CaseID > 0) {
                                vm.RegardingTxt = constCase;
                                id = r.data.CaseID;
                                vm.regardingURL = "/case/profile/detail/" + id;
                                vm.task.RefNo = r.data.RefNo;
                                oriRefNo = r.data.RefNo;
                                oriRegarding = vm.RegardingTxt;
                            } else if (r.data.ActivityID > 0) {
                                vm.RegardingTxt = constAct;
                                id = r.data.ActivityID;
                                vm.regardingURL = "/activity/profile/detail/" + id;
                                vm.task.RefNo = r.data.RefNo;
                                oriRefNo = r.data.RefNo;
                                oriRegarding = vm.RegardingTxt;
                            }

                            //bind Pegawai Bertugas
                            var m = $filter('filter')(vm.Users, r.data.AssignToLogin, true);
                            if (m.length === 1) {
                                vm.task.AssignTo = m[0];
                            }

                        }
                    });
                }
                else if (vm.TaskId == 0) {
                    TaskSI.getTask(0).then(function (r) {
                        if (r.status === 200) {
                            vm.task.CanSearchCase = r.data.CanSearchCase;
                            vm.task.CanSearchAct = r.data.CanSearchAct;
                        }
                    });
                }
            }
        });
        displayCaseDataTable();
        displayActivityDataTable();
    }

    //Bind Case - Start
    function displayCaseDataTable() {
        vm.dtColumnsRgdCase = [
            DTColumnBuilder.newColumn('CaseRefNo').withTitle('No. Kes').renderWith(function (data, type, full) {
                return '<a target="_blank" href="/case/profile/detail/' + full.CaseID + '">' + data + '</a>';
            }).withOption('width', '20%'),
            DTColumnBuilder.newColumn('Kategori1Name').withTitle('Kategori').renderWith(renderKategori).withOption('width', '35%'),
            DTColumnBuilder.newColumn('StatusLevel1Name').withTitle('Status').renderWith(renderStatusLevel).withOption('width', '35%'),
            DTColumnBuilder.newColumn('CaseID').notSortable().withTitle('').renderWith(function (data, type, full) {
                var link;
                link = '<button type="button" ng-click="task.selectRegardingID(\'' + data + '\',\'' + full.CaseRefNo + '\')" class="btn btn-primary" ><span class="fa fa-check-square"></span> Pilih</button>';
                return link;
            }).withOption('width', '10%')
        ];
        vm.dtOptionsRgdCase = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallback)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withOption('filter', false)
            .withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);
            })
            .withOption('order', [])
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
    }
    var ajaxCallback = function (data, callback, settings) {
        data.Regarding = vm.RegardingTxt == constCase ? "Case" : "";
        data.RefNo = vm.SearchRefNo;
        data.Kategori1ID = vm.SearchKategori1ID;
        data.Kategori2ID = vm.SearchKategori2ID;
        data.Kategori3ID = vm.SearchKategori3ID;
        data.CaseStatusLevel1ID = vm.SearchCaseStatusLevel1ID;
        data.CaseStatusLevel2ID = vm.SearchCaseStatusLevel2ID;
        data.CaseStatusLevel3ID = vm.SearchCaseStatusLevel3ID;
        TaskSI.getCaseOrActivity(data).then(function (r) {
            if (r.status === 200) {
                callback(r.data);
            }
        });
    };
    //Bind Case - End

    //Bind Activity - Start
    function displayActivityDataTable() {
        vm.dtColumnsRgdAct = [
            DTColumnBuilder.newColumn('ActRefNo').withTitle('No. Aktiviti').renderWith(function (data, type, full) {
                return '<a target="_blank" href="/activity/profile/detail/' + full.ActivityID + '">' + data + '</a>';
            }).withOption('width', '18%'),
            DTColumnBuilder.newColumn('ActChannelName').withTitle('Aktiviti').withOption('width', '15%'),
            DTColumnBuilder.newColumn('Aliran').withTitle('Aliran').renderWith(function (data) {
                var input = data == 'Masuk' ? ' <span><i style="transform:rotate(-45deg)" class="arrow fa  fa-arrow-down"  title="Masuk"></i> </span>'
                    : '<span> <i style = "transform:rotate(-45deg)" class="arrow fa fa-arrow-up outboundArrow" title="Keluar"></i></span >';
                return input;
            }).withOption('width', '7%'),
            DTColumnBuilder.newColumn('Kategori1Name').withTitle('Kategori').renderWith(renderKategori).withOption('width', '50%'),
            DTColumnBuilder.newColumn('ActivityID').notSortable().withTitle('').renderWith(function (data, type, full) {
                var link;
                link = '<button type="button" ng-click="task.selectRegardingID(\'' + data + '\',\'' + full.ActRefNo + '\')" class="btn btn-primary" ><span class="fa fa-check-square"></span> Pilih</button>';
                return link;
            }).withOption('width', '10%')
        ];
        vm.dtOptionsRgdAct = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackAct)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withOption('filter', false)
            .withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);
            })
            .withOption('order', [])
            .withPaginationType('full_numbers')
            .withOption('autoWidth', false)
            .withDisplayLength(10);
    }
    var ajaxCallbackAct = function (data, callback, settings) {
        data.Regarding = vm.RegardingTxt == constAct ? "Activity" : "";
        data.RefNo = vm.SearchRefNo;
        data.Kategori1ID = vm.SearchKategori1ID;
        data.Kategori2ID = vm.SearchKategori2ID;
        data.Kategori3ID = vm.SearchKategori3ID;
        data.ActStatusID = vm.SearchActStatusID;
        data.ActChannelID = vm.SearchActChannelID;
        data.AliranID = vm.SearchAliranID;
        TaskSI.getCaseOrActivity(data).then(function (r) {
            if (r.status === 200) {
                callback(r.data);
            }
        });
    };
    //Bind Activity - End

    function renderKategori(data, type, row, meta) {
        var kategoriDesc = '';
        if (row.Kategori1Name != '' && row.Kategori1Name != undefined)
            kategoriDesc += '<ul class="list-inline"><li><b>' + row.Kategori1Name + ' </b></li>';
        if (row.Kategori2Name != '' && row.Kategori2Name != undefined)
            kategoriDesc += '<li class="arrow-separator" style="font-size:0.785em;"><b> ' + row.Kategori2Name + ' </b></li>';
        if (row.Kategori3Name != '' && row.Kategori3Name != undefined)
            kategoriDesc += '<li class="arrow-separator" style="font-size:0.785em;"><span> ' + row.Kategori3Name + '</span></li>';
        if (kategoriDesc != '')
            kategoriDesc = kategoriDesc + '</ul >';

        var label = '<span>' + kategoriDesc + '</span>';

        return label;
    }

    function renderStatusLevel(data, type, row, meta) {
        var statusDesc = '';
        if (row.StatusLevel1Name != '' && row.StatusLevel1Name != undefined)
            statusDesc += '<ul class="list-inline"><li><b>' + row.StatusLevel1Name + ' </b></li>';
        if (row.StatusLevel2Name != '' && row.StatusLevel2Name != undefined)
            statusDesc += '<li class="arrow-separator" style="font-size:0.785em;"><b> ' + row.StatusLevel2Name + ' </b></li>';
        if (row.StatusLevel3Name != '' && row.StatusLevel3Name != undefined)
            statusDesc += '<li class="arrow-separator" style="font-size:0.785em;"><span> ' + row.StatusLevel3Name + '</span></li>';
        if (statusDesc != '')
            statusDesc = statusDesc + '</ul >';

        var label = '<span>' + statusDesc + '</span>';

        return label;
    }


    vm.selectRegardingID = function (id, refNo) {
        if (vm.Regarding == "Case") { //from DB remain "Case"
            vm.RegardingTxt = constCase; //set to "Kes"
            vm.task.CaseID = id;
            vm.task.ActivityID = null;
            vm.regardingURL = "/case/profile/detail/" + id;
        } else if (vm.Regarding == "Activity") {
            vm.RegardingTxt = constAct; //set to "Aktiviti"
            vm.task.CaseID = null;
            vm.task.ActivityID = id;
            vm.regardingURL = "/activity/profile/detail/" + id;
        }
        vm.task.RefNo = refNo;
        if (refNo != "") vm.RefNoErr = false;

        vm.RefNoIsChanged = !(vm.task.RefNo == oriRefNo);
        vm.RegardingIsChanged = !(vm.Regarding == oriRegarding);
        vm.close();
    }

    vm.resetSearchCriteria = function () {
        vm.SearchRefNo = "";
        vm.SearchKategori1ID = "";
        vm.SearchKategori2ID = "";
        vm.SearchKategori3ID = "";
        vm.SearchCaseStatusLevel1ID = "";
        vm.SearchCaseStatusLevel2ID = "";
        vm.SearchCaseStatusLevel3ID = "";
        vm.SearchActStatusID = "";
        vm.SearchActChannelID = "";
        vm.SearchAliranID = "";
        vm.status2Disabled = true;
        vm.kategori2Disabled = true;
        vm.status3Disabled = true;
        vm.kategori3Disabled = true;

        //!vm.dtInstanceRgdCase.reloadData ?
        //    (vm.loadCaseTbl = true) :
        //    vm.dtInstanceRgdCase.reloadData();

        //!vm.dtInstanceRgdAct.reloadData ?
        //    (vm.loadActTbl = true) :
        //    vm.dtInstanceRgdAct.reloadData();

        vm.loadActTbl = false;
        vm.loadCaseTbl = false;
    }


    vm.browse = function (e) {
        vm.resetSearchCriteria();
        if (!vm.RegardingTxt) {
            vm.RegardingErr = true;
        } else {
            vm.RegardingErr = false;
            vm.openDialog(e, '#myModal');
        }
    }

    vm.search = function () {
        if (vm.RegardingTxt == constCase) {
            vm.Regarding = "Case";
            !vm.dtInstanceRgdCase.reloadData ?
            (vm.loadCaseTbl = true) :
            vm.dtInstanceRgdCase.reloadData();

            vm.loadCaseTbl = true;
        } else if (vm.RegardingTxt == constAct) {
            vm.Regarding = "Activity";
            !vm.dtInstanceRgdAct.reloadData ?
            (vm.loadActTbl = true) :
            vm.dtInstanceRgdAct.reloadData();

            vm.loadActTbl = true;
        }
    }

    //vm.SearchUser = function (query, click) {
    //    vm.UsersOption = [];
    //    vm.loading = true;
    //    if (query.length >= 3) {
    //        // TODO : To search users from DB or AD
    //        var m = $filter('filter')(vm.Users, query);
    //        if (m.length != 0) {
    //            vm.UsersOption = m;
    //            vm.loading = false;
    //        }
    //    }
    //}

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

    function returnResultPromise() {
        var result = null;
        var deferred = $q.defer();
        deferred.reject('');
        result = deferred.promise;
        return result;
    }

    vm.updateTask = function (taskForm) {
        vm.showValidationMsgPopup = false;
        var result = null;
        var isDirty = taskForm.$dirty;
        var validRegarding = true;
        vm.showErrInvalidDate = false;
        if (editor.checkDirty()) { isDirty = true; } //check if editor dirty, then set isDirty=true
       
        if (!taskForm.$valid) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
            vm.showValidationMsgPopup = true;
            return returnResultPromise();
        }

        //validation Due Date and Start Date
        if (vm.task.DueDate) {
            var df = new Date(vm.task.StartDate);
            var dt = new Date(vm.task.DueDate);

            if (df > dt) {
                vm.showErrInvalidDate = true;
                taskForm.$valid = false;
                vm.showValidationMsgPopup = true;
                swal("Gagal!", "Tarikh Susulan mesti melebihi Tarikh Mula.", "error");
                return returnResultPromise();
            }
        }

        if (taskForm.$valid) {
            if (vm.RegardingTxt != constNotRelated) {
                if (!vm.task.RefNo) {
                    vm.RefNoErr = true;
                    vm.showValidationMsgPopup = true;
                    swal("Gagal!", "Sila pilih No. Aktiviti/No. Kes", "error");
                    return returnResultPromise();
                } else {
                    var header = "";
                    if (vm.RegardingTxt == constAct)
                        header = "ACT";
                    else if (vm.RegardingTxt == constCase)
                        header = "CAS";
                    validRegarding = (header.toUpperCase() == vm.task.RefNo.substring(0, 3));
                } 
            };

            if (!validRegarding) {
                swal("Gagal!", "Your selected Ref No. is not match with " + vm.Regarding, "error");
                vm.showValidationMsgPopup = true;
                return returnResultPromise();
            } else {
                if (isDirty || vm.RefNoIsChanged) {
                    if (vm.RegardingTxt == constNotRelated) {
                        vm.task.RefNo = "";
                        vm.task.CaseID = null;
                        vm.task.ActivityID = null;
                        vm.RefNoIsChanged = !(vm.task.RefNo == oriRefNo);
                        vm.RegardingIsChanged = !(vm.RegardingTxt == oriRegarding);
                    }
                    if (vm.TaskId > 0) GetChangeHistory(isDirty); //IF NEW Task, SKIP GetChangeHistory
                    result = UpdateTask();
                }
                else {
                    swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
                    return returnResultPromise();
                }
            };
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
            vm.showValidationMsgPopup = true;
            return returnResultPromise();
        }
        return result == null ? returnResultPromise() : result;
    }

    vm.deleteTask = function () {
        var result = null;
        swal({
            title: "Adakah anda pasti untuk menghapuskan tugasan ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                model = {
                    TaskID: vm.TaskId,
                    TaskRefNo: vm.task.TaskRefNo,
                    ChangeStamp: vm.task.ChangeStamp
                }
                result = TaskSI.deleteTask(model).then(function (r) {
                    if (r.status === 200) {

                        if (r.data == 1) {
                            swal({
                                title: "Tugasan Dihapus!",
                                text: "Tugasan anda telah dihapuskan.",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/'); //redirect to dashboard if task deleted.
                            });
                        } else {
                            swal("Gagal!", "Tugasan anda gagal dihapuskan.", "error");
                            return returnResultPromise();
                        }
                    }
                    else {
                        swal("Gagal!", r.data, "error");
                        return returnResultPromise();
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                return returnResultPromise();
            }
        });
        return result == null ? returnResultPromise() : result;
    }

    vm.cancel = function () {
        var result = null;
        swal({
            title: "Adakah anda pasti untuk menutup paparan ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                window.close();
                //if (!vm.IsNew)
                //    window.close();
                //else
                //    vm.redirectTo('/');
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                return returnResultPromise();
            }
        });
        return result == null ? returnResultPromise() : result;
    }

    function GetChangeHistory(isDirty) {
        if (isDirty) {
            angular.forEach($scope.taskForm, function (value, key) {
                if (key[0] == '$') return;

                var displayName = $('#' + key).data('displayfield');

                if (value.$pristine == false) {

                    //get new value
                    var newvalue = "";
                    if ($(document.getElementById(key))[0].tagName == 'SELECT' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                        if ($(document.getElementById(key))[0]) {
                            if ($(document.getElementById(key))[0].selectedIndex && $(document.getElementById(key))[0].selectedIndex >= 0)
                                newvalue = $(document.getElementById(key))[0].options[$(document.getElementById(key))[0].selectedIndex].text;
                        }
                    } else {
                        newvalue = value.$viewValue;
                    }
                    //var newvalue = "";
                    //if ($('#' + key)[0].tagName == 'SELECT' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    //    newvalue = $('#' + key)[0].selectedOptions.length > 0 ? $('#' + key)[0].selectedOptions[0].text : "";
                    //} else {
                    //    newvalue = value.$viewValue;
                    //}

                    vm.ChangesHistory.push({
                        ID: vm.TaskId,
                        FieldName: key,
                        DisplayName: displayName,
                        OldValue: '',
                        NewValue: newvalue,
                        IsChanged: !value.$pristine
                    });
                }
            });
        }

        if (vm.RegardingIsChanged) {
            vm.ChangesHistory.push({
                ID: vm.TaskId,
                FieldName: "Berkenaan",
                DisplayName: "Berkenaan",
                OldValue: oriRegarding,
                NewValue: vm.RegardingTxt,
                IsChanged: vm.RegardingIsChanged
            });
        };

        if (vm.RefNoIsChanged) {
            vm.ChangesHistory.push({
                ID: vm.TaskId,
                FieldName: "RefNo",
                DisplayName: "Ref No.",
                OldValue: oriRefNo,
                NewValue: vm.task.RefNo,
                IsChanged: vm.RefNoIsChanged
            });
        };
    };

    function UpdateTask() {
        var model = angular.copy(vm.task);
        model.AssignToLogin = model.AssignTo.ID;
        model.AssignToName = model.AssignTo.DisplayName;
        model.AssignToEmail = model.AssignTo.Email;
        model.ChangeHistory = vm.ChangesHistory;
        model.Description = editor.getData(); //get editor content

        var msgTitle = vm.TaskId == "" ? "Tugasan dihasilkan!" : "Tugasan dikemaskini!";
        var msgDesc = vm.TaskId == "" ? "Tugasan berjaya dihasilkan." : "Tugasan berjaya dikemaskini.";
        model.DueDate = $filter('date')(model.DueDate, $scope.DateTimeFormat);
        model.StartDate = $filter('date')(model.StartDate, $scope.DateTimeFormat);
        
        var data = TaskSI.updateTask(model);
        data.then(function (r) {
            if (r.status === 200) {
                swal({
                    title: msgTitle,
                    text: msgDesc,
                    type: "success",
                    timer: 2500,
                    showConfirmButton: true
                }, function () {
                    vm.redirectTo("/task/detail/" + r.data);
                });
            }
            else {
                swal("Gagal!", r.data, "error");
            }
        });

        return data;
    };

    vm.kategori1Change = function (selectedKategori1ID) {
        vm.SubKategoriOptions = [];
        vm.kategori3Disabled = true;

        if (selectedKategori1ID != undefined) {
            vm.SubKategoriOptions = [];

            var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: selectedKategori1ID }, true);
            if (m != undefined && (m.length > 0)) {
                vm.SubKategoriOptions = m[0].SubKategori;
                vm.kategori2Disabled = m[0].SubKategori.length > 0 ? false : true;
            }
        }
    };

    vm.kategori2Change = function (selectedKategori2ID) {
        vm.InnerSubKategoriOptions = [];

        var m = $filter('filter')(vm.SubKategoriOptions, { Kategori2ID: selectedKategori2ID }, true);
        if (m != undefined && m.length > 0) {
            vm.InnerSubKategoriOptions = m[0].InnerSubKategori;
            vm.kategori3Disabled = m[0].InnerSubKategori.length > 0 ? false : true;
        }
    };

    vm.status1Change = function (selectedStatus1ID) {
        vm.caseStatus2Options = [];
        vm.status3Disabled = true;

        var m = $filter('filter')(vm.Status1Options, { StatusLevel1ID: selectedStatus1ID }, true);
        if (m != undefined && m.length > 0) {
            vm.caseStatus2Options = m[0].StatusLevel2;
            vm.status2Disabled = m[0].StatusLevel2.length > 0 ? false : true;
        }
    };

    vm.status2Change = function (selectedStatus2ID) {
        vm.caseStatus3Options = [];

        var m = $filter('filter')(vm.caseStatus2Options, { StatusLevel2ID: selectedStatus2ID }, true);
        if (m != undefined && m.length > 0) {
            vm.caseStatus3Options = m[0].StatusLevel3;
            vm.status3Disabled = m[0].StatusLevel3.length > 0 ? false : true;
        }
    };

    vm.reset = function () {
        vm.task.AssignTo = null;
        vm.ResetUserHierarchy();
        vm.showUserdetail = false;
    }

    //Unit and filter
    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.task.AssignTo = ""; }
    };


    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.task.AssignTo = ""; }
    };


    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.task.AssignTo = ""; }
    };

    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.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;
            });
        }

    }


    function SearchUserByUnitID(selectedUnitID) {
        if (selectedUnitID) {
            vm.NoUserMessage = false;
            vm.UserResultOption = [];
            vm.task.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.ShowFilterUserOption = function () {
        if (!vm.showUserdetail) {
            vm.showUserdetail = true;
        }
        else {
            vm.showUserdetail = false;
        }
    }


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

        vm.SelectedTimbalanUser = "";
        vm.SelectedJabatanUser = "";
        vm.SelectedCawanganUser = "";
        vm.SelectedUnitsUser = "";
        vm.task.AssignTo = "";

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

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

    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"];
                }
            }
        });
    }


    vm.clearDueDate = function (taskForm) {
        vm.task.DueDate = '';
        vm.task.DueDate.$setViewValue = '';
        taskForm.$pristine = false
        taskForm.$dirty = true;
        taskForm.DueDate.$dirty = true;
        vm.showErrInvalidDate = false;
    };

    vm.clearStartDate = function (taskForm) {
        vm.task.StartDate = '';
        vm.task.StartDate.$setViewValue = '';
        taskForm.$pristine = false
        taskForm.$dirty = true;
        taskForm.StartDate.$dirty = true;
    };


}

function SearchTaskController($scope, $window, $filter, DTOptionsBuilder, DTColumnBuilder, TaskSI, AntiForgeryService, $compile, GeneralService) {
    var vm = this;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    vm.RegardingOptions = ['Tidak Berkenaan', 'Aktiviti', 'Kes'];
    var constNotRelated = "Tidak Berkenaan";
    var constAct = "Aktiviti";
    var constCase = "Kes";
    vm.dtInstanceTask = {};
    var constBelumSelesai = "belum selesai";
    vm.TaskStatusID = $window.taskstatusid;
    vm.LinkfromDashboard = $window.isLinkfromDashboard;

    vm.redirectTo = function (url) {
        $window.beforeUnloadCanceled = true;
        $window.location.href = url;
    }

    vm.init = function () {

        vm.UsersOption = [];

        // datepicker
        vm.dateFromMinDate = null;
        vm.dateFromMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;
        vm.dateFromOptions = {
            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.dateToMinDate = null;
        vm.dateToMaxDate = null;
        vm.dateToOptions = {
            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,
            closed: function (args) {
                vm.closedArgs = args;
            } 
        };

        //drop down menu
        TaskSI.getDropdown().then(function (r) {
            if (r.status === 200) {
                for (var key in r.data.data) {
                    vm[key] = r.data.data[key];
                }
                vm.Users = r.data.users;

                //export excel record
                var m = $filter('filter')(vm.ParameterSettings, { ParameterID: 22 }, true);
                if (m && (m.length != 0)) {
                    vm.maxExportRecord = m[0].ParameterValue;
                }
            }

        });

        if (vm.TaskStatusID) {

            if ($window.taskstatusid == 261) {
                vm.TaskStatusID = 261;
                vm.AssignTo = $scope.UserInfo;
               
            }
            else {
                vm.TaskStatusID = 262;
                vm.AssignTo = $scope.UserInfo;
            }

            if(vm.AssignTo)
            {
                vm.AssignTo.ID = vm.AssignTo.LoginID;
            }

            vm.loadTbl = true
            vm.ShowTskFilter = false;
        }
        else {
            vm.ShowTskFilter = true;
        }

        vm.dtColumnsTask = [
               DTColumnBuilder.newColumn('TaskStatus').notSortable().withTitle(' ').renderWith(function (data, type) {
                   var input = data.toLowerCase() == constBelumSelesai ? '<i class="case fa fa-exclamation-circle" style="color:red;" title="Belum Selesai"></i>' : '';
                    return input;
               }).withOption('width', '2%'),
               DTColumnBuilder.newColumn('TaskRefNo').withTitle('No. Tugasan').renderWith(function (data, type, full) {
                   return '<a target="_blank" href="/task/detail/' + full.TaskID + '">' + data + '</a>';
               }),
               DTColumnBuilder.newColumn('Title').withTitle('Perkara'),
               DTColumnBuilder.newColumn('TaskStatus').withTitle('Status'),
               DTColumnBuilder.newColumn('RefNo').withTitle('Berkenaan').renderWith(function (data, type, full) {
                   var link;
                   if (data == null || data == "") {
                       link = constNotRelated;
                   }
                   else if (data.substring(0, 3).toUpperCase() == "ACT") {
                       link = '<a target="_blank" href="/activity/profile/detail/' + full.ActivityID + '">' + data + '</a>';
                   }
                   else if (data.substring(0, 3).toUpperCase() == "CAS") {
                       link = '<a target="_blank" href="/case/profile/detail/' + full.CaseID + '">' + data + '</a>';
                   }
                   return link;
               }),
               DTColumnBuilder.newColumn('AssignToName').withTitle('Pegawai Bertugas'),
               DTColumnBuilder.newColumn('DueDate').withTitle('Tarikh Susulan').renderWith(function (data, type) {
                   return $filter('date')(data?data:'-', 'dd MMM yyyy');
               })
        ];
        vm.dtOptionsTask = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallback)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withOption('filter', false)
            .withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);
            })
            .withOption('order', [])
            .withPaginationType('full_numbers')
            .withDisplayLength(10);

    };

    var ajaxCallback = function (data, callback, settings) {
        var regarding = "";
        if (vm.Regarding == constAct)
            regarding = "Activity";
        else if (vm.Regarding == constCase)
            regarding = "Case";
        else if (vm.Regarding == constNotRelated)
            regarding = "Not Related";

        data.TaskRefNo = vm.TaskRefNo;
        data.Subject = vm.Title;
        data.Regarding = regarding;
        data.RefNo = vm.RefNo;
        data.TaskStatusID = vm.TaskStatusID;
        //data.AssignToName = vm.AssignTo != undefined ? vm.AssignTo.DisplayName : "";
        data.AssignToName = vm.AssignTo != undefined ? vm.AssignTo.ID : ""; //take AssignToLogin instead of DisplayName
        data.DueDateFrom = $filter('date')(vm.DateFrom, $scope.DateTimeFormat);
        data.DueDateTo = $filter('date')(vm.DateTo, $scope.DateTimeFormat);
        data.IsLinkfromDashboard = vm.LinkfromDashboard;

        TaskSI.searchTask(data).then(function (r) {
            if (r.status === 200) {
                callback(r.data);
            }
        });

        if (vm.isExportExcel) {
            //set selected to undefined
            var dataCopy = angular.copy(data);

            if (!dataCopy.IsLinkfromDashboard)
                dataCopy.IsLinkfromDashboard = 0;

            angular.element('#strJSON').val(angular.toJson(dataCopy));
            angular.element('#btn-submitExport').click();
        }

        vm.isExportExcel = false;
    };

    vm.search = function () {
        vm.blnValid = true;
        vm.showErrCreatedDate = false;
        vm.ErrMsgCreatedDate = "";

        if ((!vm.DateFrom && vm.DateTo) ||
			(vm.DateFrom && !vm.DateTo)) {
            vm.ErrMsgCreatedDate = "Banjaran tarikh tidak sah.";
            vm.showErrCreatedDate = true;
            vm.blnValid = false;
        }

        var df = new Date(vm.DateFrom);
        var dt = new Date(vm.DateTo);

        if (df > dt) {
            vm.ErrMsgCreatedDate = "Tarikh Susulan mesti melebihi Tarikh Mula.";
            vm.showErrCreatedDate = true;
            vm.blnValid = false;
        }

        if (vm.blnValid) {
            vm.showErrCreatedDate = false;
            vm.ErrMsgCreatedDate = "";

            !vm.dtInstanceTask.reloadData ?
            (vm.loadTbl = true) :
            vm.dtInstanceTask.reloadData();

            vm.loadTbl = true;
        }
    };

    vm.reset = function () {
        vm.TaskRefNo = "";
        vm.Title = "";
        vm.Regarding = "";
        vm.RefNo = "";
        vm.TaskStatusID = "";
        vm.AssignTo = "";
        vm.DateFrom = "";
        vm.DateTo = "";
        vm.showErrCreatedDate = false;
        vm.ErrMsgCreatedDate = "";

        !vm.dtInstanceTask.reloadData ?
            (vm.loadTbl = true) :
            vm.dtInstanceTask.reloadData();

        vm.loadTbl = false;
    };

    vm.SearchUser = function (query, click) {
        vm.UsersOption = [];
        vm.loading = true;
        if (query.length >= 3) {
            // TODO : To search users from DB or AD
            var m = $filter('filter')(vm.Users, query);
            if (m.length != 0) {
                vm.UsersOption = m;
                vm.loading = false;
            }
        }
    }

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

    vm.clearDateFrom = function () {
        vm.DateFrom = null;
        vm.DateFrom.$dirty = true;
        vm.DateFrom.$pristine = false;
    };
    vm.clearDateTo = function () {
        vm.DateTo = null;
        vm.DateTo.$dirty = true;
        vm.DateTo.$pristine = false;
    };

    vm.exportExcel = function () {
        swal({
            title: "Adakah anda pasti untuk eksport rekod ke Excel?",
            text: "Maksimum rekod export =" + vm.maxExportRecord,
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                swal.close();
                vm.isExportExcel = true;
                vm.search();
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }
}