myscheduleApp.value('THROTTLE_MILLISECONDS', 1250);
// var schedule_pagesize = $('#schedule_pagesize');
myscheduleApp.controller('myscheduleCtrl', function($cordovaFile, $cordovaActionSheet, $cordovaCamera, $cordovaFileTransfer, //
    $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $cordovaToast, $ionicLoading, $ionicPopup, $scope, $http, $window, //
    $interval, Login, Schedule, Appointments, Notetasks, Customerfiles , Users, Notetasktypes, dataHtml, $ionicHistory, $stateParams) {
    $scope.switchNotetasksCtrl = 'mys';
    $scope.fshortDate = 'h:mm a';
    $scope.currentIdLogin = currentIdLogin;
    $scope.currentPage = 1;
    var pager = '200';
    $scope.itemsPerPage = pager ? pager : 200;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.appointment_id = getParameterByName('appointment_id');
    localStorage.setItem('schedule_pagesize', $scope.itemsPerPage);
    $scope.my_scheduleDate = {};
    $scope.my_scheduleDate.from_date = moment().format(conFig.formatDate.toUpperCase());
    $scope.my_scheduleDate.to_date = moment().format(conFig.formatDate.toUpperCase());

    $scope.searchSchedule = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: "",
        my_scheduleDate: $scope.my_scheduleDate
    };
    $scope.editNotetasksData = [];
    $scope.my_schedules = 0;
    $scope.Loading_data = 0;
    $scope.Loading_data_star = 1;
    $scope.myschedule = [];
    $scope.tier = tier;
    //role
    $scope.roleName = role;
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.isWarehouse = isWarehouse;
    $scope.check_init_myschedule = false;
    $scope.dataMyAppHtml = {};
    if ($scope.tier.t1) {
        $scope.NoCAIdString = NoCAId.toString();
        $scope.differentNoCaAndRouteColor = differentNoCaAndRouteColor;
    }



    $scope.renderTemplateData = function() {
        dataHtml.getTemplate('templates/dashboard/myschedules/myshedulesMenuHeadermodal.tpl').success(function(results) {
            $scope.dataMyAppHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/myschedules/myshedulesContentmodal.tpl').success(function(results) {
                $scope.dataMyAppHtml.myscheduleContent = results;
                dataHtml.getTemplate('templates/dashboard/myschedules/myshedulesAppQueryTimemodal.tpl').success(function(results) {
                    $scope.dataMyAppHtml.appQueryTime = results;
                    $timeout(function() {
                        $("#myscheduleDisplayFromDay .day").html(moment().format('DD'));
                        $("#myscheduleDisplayFromDay .month").html(moment().format('MMMM'));
                        $("#myscheduleDisplayToDay .day").html(moment().format('DD'));
                        $("#myscheduleDisplayToDay .month").html(moment().format('MMMM'));
                    }, 500)
                    $scope.getSchedule();
                    $scope.getUsers();
                    setHeight("#main-content");
                });
            });
        });
    }
        // status picker
        $scope.getAppointments = function() {
            Appointments.getSelect().success(function(data) {
                $scope.appointments = data;
                $('.dashboard > .tblloader').hide();
                $('#footer').show();
                $('#document').show();
                $scope.getSchedule();
                $scope.includeJs();
                // $scope.my_scheduleDate.from_date = moment().format(conFig.formatDate.toUpperCase());
                // $scope.my_scheduleDate.to_date = moment().format(conFig.formatDate.toUpperCase());
            });
        }
        //$scope.getAppointments();
        $scope.getNotetasks = function() {
            Notetasks.getSelect().success(function(data) {
                $scope.notetasks = data;
            });
        }
        $scope.getSchedule = function(onRefresh) {
            $scope.searchSchedule.currentUserId = $scope.currentIdLogin;
            var startDate = moment($scope.my_scheduleDate.from_date).format(conFig.formatDate.toUpperCase());
            var endDate = moment($scope.my_scheduleDate.to_date).format(conFig.formatDate.toUpperCase());
            if (moment(startDate, conFig.formatDate.toUpperCase()).format('x') > moment(endDate, conFig.formatDate.toUpperCase()).format('x')) {
                $scope.my_scheduleDate.to_date = moment($scope.my_scheduleDate.from_date).add(1, 'days').format(conFig.formatDate.toUpperCase());
                $cordovaToast.showLongTop('End time must be greater than start time');
                return;
            }
            if(!onRefresh){
                $ionicLoading.show({
                    template: templateLoading
                });
            }
            
            $scope.searchSchedule.my_scheduleDate = {
                from_date: startDate,
                to_date: endDate
            }
            Schedule.getPaging($scope.searchSchedule).success(function(data) {
                $ionicLoading.hide();
                $scope.myschedule = data.data;
                $scope.timeToDay = data.timeToDay;
                $scope.myschedule = _.each($scope.myschedule, function(val, index) {
                    if(val.workingTime != 'Off'){
                        val.workingTimeFrom = val.workingTime.split("-")[0].trim();
                        val.workingTimeTo = val.workingTime.split("-")[1].trim();
                    }
                    $scope.myscheduleData = [];
                    val.dataTask = _.each(val.dataTask, function(value) {
                        _.extend(value, {
                            re_str: Date.parseDate(val.moth + ' ' + val.day + ' ' + val.year + ' ' + String(value.startime)),
                            re_end: Date.parseDate(val.moth + ' ' + val.day + ' ' + val.year + ' ' + String(value.endtime)),
                        });
                        $scope.myscheduleData.push(value);
                    });
                    val.dataAppointment = _.each(val.dataAppointment, function(value) {
                        _.extend(value, {
                            re_str: Date.parseDate(val.moth + ' ' + val.day + ' ' + val.year + ' ' + String(value.startime)),
                            re_end: Date.parseDate(val.moth + ' ' + val.day + ' ' + val.year + ' ' + String(value.endtime)),
                        });
                        $scope.myscheduleData.push(value);
                    })
                    $scope.myscheduleData = _.sortBy(_.sortBy($scope.myscheduleData, 'endtime'), 'startime');
                    var notetaskIndex = 0;
                    var appIndex = 0;
                    var position = 0;
                    $scope.myscheduleData = _.each($scope.myscheduleData, function(value) {
                        if (value.action == 'notetasks') {
                            _.extend(value, {
                                index: notetaskIndex++,
                                position: position++
                            });
                        } else {
                            _.extend(value, {
                                index: appIndex++,
                                position: position++
                            });
                        }
                    });
                    _.extend(val, {
                        dataMerge: $scope.myscheduleData,
                    });
                });
                $scope.currentPage = data.page;
                $scope.itemsPerPages = $scope.searchSchedule.rows;
            // schedule_pagesize.val($scope.searchSchedule.rows);
            localStorage.setItem('schedule_pagesize', $scope.searchSchedule.rows);
            $scope.entryLimit = $scope.searchSchedule.rows;
            $scope.totalItems = data.total_rows;
            if (data.total_rows <= $scope.searchSchedule.rows) {
                $scope.Loading_data_star = 0;
            }
            $scope.Loading_data = 1;
            // $scope.includeJs($scope.highlightCurrentDate($scope.myschedule, $scope.transferDate()));
            !$scope.check_init_myschedule ? $interval($scope.checkLogin, time_refresh) : '';
            request_notify_get_chat = true;
            $scope.check_init_myschedule = true;
            $scope.$broadcast('scroll.refreshComplete');
            //THUANDINH fix
            // $scope.includeJs();
            // $scope.my_scheduleDate.from_date = moment().format(conFig.formatDate.toUpperCase());
            // $scope.my_scheduleDate.to_date = moment().format(conFig.formatDate.toUpperCase());
            //end THUANDINH
            // edit by haudao
            $timeout(function() {
                getData = true;
            }, 2000);
            // end edit
        });
        };
        $scope.transferDate = function() {
            var date = new Date();
            date = new Date((date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear());
            return moment(date, "MM-DD-YYYY");
        }
        $scope.highlightCurrentDate = function(objSchedule, currentDate) {
            for (var i = 0; i < objSchedule.length; i++) {
                if (moment(new Date(objSchedule[i]['date']), "MM-DD-YYYY").format() == currentDate.format()) {
                    if ((objSchedule[i].dataMerge.length) > 1) {
                        if (objSchedule[i].dataMerge[0]['action'] == 'appointments') {
                            return '#app-' + objSchedule[i].dataMerge[0]['id'];
                        } else {
                            return '#tak-' + objSchedule[i].dataMerge[0]['id'];
                        }
                    }
                }
            }
            return '';
        }
        $scope.loadMore = function() {
            $('#Loading_data').show();
            if ($scope.Loading_data == 1 && $scope.Loading_data_star == 1) {
                $scope.Loading_data = 0;
                $scope.searchSchedule.rows = parseInt($scope.searchSchedule.rows) + 7;
                $scope.getSchedule();
            } else {
                $('#Loading_data').hide();
            }
        }
        //$scope.getSchedule();
        $scope.searchChanged = function() {
            $scope.getSchedule();
        }
        $scope.sizeChangedschedule = function(entryLimit) {
            $scope.searchSchedule.my_scheduleDate = {};
            $scope.my_scheduleDate.from_date = '';
            $scope.my_scheduleDate.to_date = '';
            $('#from_date').val('');
            $('#to_date').val('');
            $scope.searchSchedule.rows = entryLimit;
            $scope.searchSchedule.current_page = 1;
            $scope.getSchedule();
        }
        $scope.pageChangedschedule = function(currentPage) {
            $scope.currentPage = currentPage;
            $scope.searchSchedule.current_page = $scope.currentPage;
            $scope.getSchedule();
        };
        $scope.setPage = function(pageNo) {
            $scope.currentPage = pageNo;
        };
        $scope.addScheduleData = {};
        $scope.createSchedule = function() {
            Schedule.save($scope.addScheduleData).success(function(data) {
                $scope.addScheduleData = {};
                $scope.getSchedule();
                if (data.status) {
                    toastr.success(data.msg);
                } else {
                    toastr.error(data.msg);
                }
            });
        }
        $scope.editScheduleData = {};
        $scope.editSchedule = function(id) {
            $('.loader').show();
            Schedule.show(id).success(function(data) {
                $('.loader').hide();
                $scope.editScheduleData = data;
            });
        }
        $scope.updateSchedule = function() {
            var id = $scope.editScheduleData.id;
            $('.loader').show();
            Schedule.update(id, $scope.editScheduleData).success(function(data) {
                $('.loader').hide();
                if (data.status) {
                    $scope.editScheduleData = {};
                    toastr.success(data.msg);
                } else {
                    toastr.error(data.msg);
                }
                $scope.getSchedule();
            });
        }
        $scope.deleteScheduleData = {};
        $scope.deleteScheduleData = {};
        $scope.confrimSchedule = function(id, title, content) {
            $scope.deleteScheduleData = {
                id: id
            };
            var confirm = $.confirm(title, '<div class="text-content baseline">' + content + '</div>', {
                messageType: 'warning',
                titleIcon: 'remove',
                overlayTransparent: .75
            }, function() {
                $scope.deleteSchedule(id, confirm);
            });
        }
        $scope.deleteSchedule = function(id, confirm) {
            Schedule.destroy(id).success(function(data) {
                $scope.deleteScheduleData = {};
                if (data.status) {
                    $.notification('<div class="text-content">' + data.msg + '</div>', {
                        messageType: 'message-success',
                        autoClose: true
                    });
                    confirm.switchStateDialog("close");
                } else {
                    $.notification('<div class="text-content">' + data.msg + '</div>', {
                        messageType: 'message-success',
                        autoClose: true
                    });
                    confirm.switchStateDialog("close");
                }
                $scope.getSchedule();
            });
        }
        $scope.getUsers = function () {
            var _param = {
                rows: 'All'
            }
            $ionicLoading.show({template: templateLoading});
            if ($scope.allUser == undefined) {
                $scope.allUser = [];
                Users.getPaging(_param).success(function (data) {
                    _.each(data.data, function (val, index) {
                        nick_name = val.first_name + ' ' + val.last_name;
                        var _item = {
                            id: val.id,
                            screen_name: nick_name + ' - ' + val.positiontitles_name,
                            name: nick_name,
                            imgprofile: pathToPublic + val.image_pic,
                            email: val.email
                        }
                        $scope.allUser.push(_item);
                    });
                });
            }
        };
        $scope.getUserLogin = function() {
            return Login.getUserLogin().success(function(data) {
                if (data == false) {
                    localStorage.setItem("login_status", "0");
                    redirectTo('index.html');
                } else {
                    $scope.imagePath = pathToPublic + data.image_pic;
                    var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
                    if ($.trim(displayname) == "") {
                        $scope.displayname = "Hello, " + data.email;
                    } else {
                        $scope.displayname = "Hello, " + displayname;
                    }
                    var _param = {
                        rows: 'All'
                    }
                    if ($scope.allUser == undefined) {
                        $scope.allUser = [];
                        Users.getPaging(_param).success(function(data) {
                            _.each(data.data, function(val, index) {
                                nick_name = val.first_name + ' ' + val.last_name;
                                var _item = {
                                    id: val.id,
                                    screen_name: nick_name + ' - ' + val.positiontitles_name,
                                    name: nick_name,
                                    imgprofile: pathToPublic + val.image_pic,
                                    email: val.email
                                }
                                $scope.allUser.push(_item);
                            });
                        });
                    }
                    $scope.getSchedule();
                }
            });
        }
        $scope.logout = function() {
            return Login.logout().success(function(data) {
                $window.location.href = url_login;
            });
        }
        $scope.checkLogin = function() {
            return Login.checkLogin().success(function(data) {
                if (data.status == false) {
                    $window.location.href = url_login;
                } else {
                    //$scope.getUserLogin();
                }
            });
        }
        /*include jquery*/
        // $scope.includeJs = function($hook) {
        //         setTimeout(function() {
        //             $scope.$apply(function(val) {
        //                 // for change due time of task
        //                 if (!$scope.picker) {
        //                     $('#my_scheduleDate').unbind();
        //                     $('#my_scheduleDate').daterangepicker({
        //                         ranges: {
        //                             'Today': [moment(), moment()],
        //                             'Tomorrow': [moment(), moment().add(1, 'days')],
        //                             'One Week': [moment(), moment().add(6, 'days')]
        //                         }
        //                     }, function(start, end) {
        //                         var time = {
        //                             start: start.format(conFig.formatDate.toUpperCase()),
        //                             end: end.format(conFig.formatDate.toUpperCase())
        //                         }
        //                         $('#my_scheduleDate input[name="starttime"]').val(start.format(conFig.formatDate.toUpperCase()));
        //                         $('#my_scheduleDate input[name="endtime"]').val(end.format(conFig.formatDate.toUpperCase()));
        //                         // $scope.searchSchedule.my_scheduleDate.from_date = start.format(conFig.formatDate.toUpperCase());
        //                         // $scope.searchSchedule.my_scheduleDate.to_date = end.format(conFig.formatDate.toUpperCase());
        //                         $scope.searchSchedule.my_scheduleDate = {
        //                             from_date: start.format(conFig.formatDate.toUpperCase()),
        //                             to_date: end.format(conFig.formatDate.toUpperCase())
        //                         }
        //                         $scope.searchSchedule.current_page = 1;
        //                         $scope.Loading_data_star = 1;
        //                         $scope.getSchedule();
        //                         $scope.picker = true;
        //                     });
        //                 }
        //                 // for slideToggle
        //                 $('.times-schedule > li .detail span').unbind();
        //                 $('.times-schedule > li .detail span').click(function() {
        //                     var self = $(this);
        //                     $('.times-schedule > li .detail span').each(function(index) {
        //                         if ($(this).attr('id') != self.attr('id')) {
        //                             $(this).html('(+)');
        //                             $(this).parent().parent().parent().parent().find('.none').slideUp();
        //                         }
        //                     });
        //                     $(this).text() == '(+)' ? $(this).html('(-)') : $(this).html('(+)');
        //                     $(this).parent().parent().parent().parent().find('.none').slideToggle();
        //                 });
        //                 if ($hook != '' && $hook != undefined) $('.times-schedule > li .detail span' + $hook).trigger("click");
        //             });
        //         }, 100);
        //     }
        // onload

    // edit by haudao
    var getData = false;
    $scope.$watch('my_scheduleDate.from_date', function(value) {
        if (value == '' || value == undefined) return;
        if (moment(value).isValid() && moment($scope.my_scheduleDate.to_date).isValid() && getData) {
            $("#myscheduleDisplayFromDay .day").html(moment(value).format('DD'));
            $("#myscheduleDisplayFromDay .month").html(moment(value).format('MMMM'));

            $scope.getSchedule();
        }
    });
    $scope.$watch('my_scheduleDate.to_date', function(value) {
        if (value == '' || value == undefined) return;
        if (moment(value).isValid() && moment($scope.my_scheduleDate.from_date).isValid() && getData) {
            $("#myscheduleDisplayToDay .day").html(moment(value).format('DD'));
            $("#myscheduleDisplayToDay .month").html(moment(value).format('MMMM'));
            $scope.getSchedule();
        }
    })
    $scope.picker = false;
    $scope.editNotetasksFormMyschedule = function(id) {
        dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupTaskNoteEditmodal.tpl').success(function(results) {
            $scope.dataMyAppHtml.editTaskNote = results;
            $scope.$broadcast('editNotetasksFormMyschedule', {
                id: id
            })
            $timeout(function(){
                $scope.showTarget("#popupEditScheduleNote");
            },500)
        })

    }
    if (page == 'myschedule.html') $scope.renderTemplateData();
    // if ($stateParams.appID) ;
    // end edit
})
