// main ext
extAppDetailView = function() {
    this.apppointment = null;
    this.queue_app = [];
    this.io_server_socket = null;
}
    // contructor ext
    extAppDetailView.prototype = {
        initCtrl: function() {
            if (appScope) {
                this.apppointment = appScope;
                this.initShareVar();
            }
        },
        initShareVar: function() {
            var self_app = this.apppointment;
            self_app.flongDate = 'MM/dd/yyyy h:mm:ss a';
            self_app.fshortDate = 'h:mm a';
            self_app.flags = [];
            self_app.leadsources = [];
            // self_app.fieldWorkerByAppGroupList = [];
            self_app.holdFieldWorkerOnApp.id = -1;
            self_app.dataFileMan = {};
            self_app.mobileShow = false;
            self_app.frmMobile = false;
            self_app.customer_data = {};
            self_app.dataApp = {};
            self_app.jobShow = true;
        },
        onSocket: function($server_chat_ip, $config_chat) {
            var _self = this;
            if (_self.queue_app.length > 0 && _self.io_server_socket != null) {
                _self.io_server_socket.on('connect_error', (error) => {
                    if (_self.queue_app.length > 0) {
                        console.log('new message on app in queue connect_error');
                        setTimeout(function() {
                            _self.io_server_socket != null ? _self.io_server_socket.close() : '';
                            _self.io_server_socket = io($server_chat_ip, $config_chat);
                            _self.onSocket($server_chat_ip, $config_chat);
                        }, 5000);
                    }
                }).on('connect_timeout', (timeout) => {
                    if (_self.queue_app.length > 0) {
                        console.log('new message on app in queue connect_timeout');
                        setTimeout(function() {
                            _self.io_server_socket != null ? _self.io_server_socket.close() : '';
                            _self.io_server_socket = io($server_chat_ip, $config_chat);
                            _self.onSocket($server_chat_ip, $config_chat);
                        }, 5000);
                    }
                }).on('connect', () => {
                    if (_self.queue_app.length > 0) {
                        socket.emit('new message', _self.queue_app[0]);
                        hold_app = _self.queue_app.shift(0);
                        queue_app = hold_app;
                        console.log('new message on app ok connect');
                        _self.io_server_socket != null ? _self.io_server_socket.close() : '';
                        _self.io_server_socket = io($server_chat_ip, $config_chat);
                        _self.onSocket($server_chat_ip, $config_chat);
                    }
                });
            }
        },
        socketImit: function($room, $msg_content) {
            // var self_app = this.apppointment;
            // if (socket) {
            //     socket.emit('new message', {
            //         from_user: self_app.currentIdLogin,
            //         room_id: $room,
            //         user_id: 0,
            //         contents: $msg_content,
            //         content_raw: $msg_content,
            //         hashtag: '',
            //         applicationtype: aplicationtype.text
            //     },function(confirmation){
            //         if(confirmation == false){
            //             self_app.openByGetTemplate('popupRetrySentMessegemodal');
            //         }
            //     });
            // }
            var _self = this;
            var self_app = this.apppointment;
            var obj_app = {
                from_user: self_app.currentIdLogin,
                room_id: $room,
                user_id: 0,
                contents: $msg_content,
                content_raw: $msg_content,
                hashtag: '',
                applicationtype: aplicationtype.text
            }
            _self.queue_app.push(obj_app);
            _self.io_server_socket != null ? _self.io_server_socket.close() : '';
            _self.io_server_socket = io(server_chat_ip, config_chat);
            _self.onSocket(server_chat_ip, config_chat);
        },
        setActionJob: function($status) {
            var self_app = this.apppointment;
            $status == 6 ? self_app.jobShow = false : self_app.jobShow = true;
            switch (localStorage.getItem('role').toLowerCase()) {
                case 'admin':
                case 'manager':
                case 'reporter':
                self_app.jobShow = true;
                break;
                default:
                break;
            }
        },
        sendPushRoom: function(status, inputValue) {
            var self_app = this.apppointment;
            var date = String(new Date(_.now()).dateFormat('MM/DD/YYYY')) + ' ';
            var name = _.where(self_app.detailAppointmentData._userss, {
                id: self_app.detailAppointmentData.fieldworker
            })[0];
            var strMsg = '';
            if(self_app.detailAppointmentData.appointmentjobsites && parseInt(self_app.detailAppointmentData.appointmentjobsites.id) > 0){
                var cityInMsg = self_app.detailAppointmentData.appointmentjobsites.city
            }else{
                var cityInMsg = self_app.detailCustomerData.city;
            }
            switch (status) {
                case 'to_enroute':
                    // "Field Worker Nameâ€ + â€˜s + "ETA to" + "City Name" + is + "Entered Time"
                    // VĂ­ dá»¥: Bryan's ETA to Minneapolis is 8:43am
                    // date = date + $('#creatAppStatusEtc input[name="etatime"]').val();
                    // date = moment(date).format("h:mm a");
                    date = inputValue;
                    strMsg += (name.first_name + ' ' + name.last_name + "'s ETA to ");
                    strMsg += (cityInMsg + ' is ');
                    strMsg += date;
                    this.socketImit(name.pushchatroom, strMsg);
                    break;
                    case 'to_arrived_on_site':
                    // notthing
                    break;
                    case 'to_working':
                    //  Field Worker Nameâ€ + â€˜s + ETC at + City Name + is + Entered Time;
                    // VĂ­ dá»¥: Bryan's ETC at Minneapolis is 9:20am
                    // date = date + $('#creatAppStatusEtc input[name="etctime"]').val();
                    // date = moment(date).format("h:mm a");
                    date = inputValue;
                    strMsg += (name.first_name + ' ' + name.last_name + "'s ETC at ");
                    strMsg += (cityInMsg + ' is ');
                    strMsg += date;
                    this.socketImit(name.pushchatroom, strMsg);
                    break;
                    case 'to_finish':
                    // Field Worker Name' + â€œisâ€ + Warping Up + input message;
                    strMsg += (name.first_name + ' ' + name.last_name + "'s finishing up at ");
                    strMsg += (cityInMsg + ' and Completion in ');
                    strMsg += inputValue;
                    this.socketImit(name.pushchatroom, strMsg);
                    break;
                    case 'to_complete':
                    // notthing
                    break;
                    default:
                    break;
                }
            // closePopupById('popupPendingToEnRoute');
            // openPopup('#popupAppointmentDetail');
            if (page == 'scheduleapp.html') {
                // self_app.setCalendarDate();
                // self_app.beforeSetCalendar();
                self_app.loadAppointmentByDay(self_app.selectedDay);
            }
            self_app.getDetailAppointment(self_app.detailAppointmentData.id);
        },
        getFlags: function() {
            var self_app = this;
            ionicLoading.show({ template: templateLoading });
            cusFlag.getSelect().success(function(data) {
                if (!startpage) ionicLoading.hide();
                self_app.apppointment.flags = data;
            });
        },
        getLeadSource: function() {
            var self_app = this;
            ionicLoading.show({ template: templateLoading });
            cusLeadSource.getSelect().success(function(data) {
                if (!startpage) ionicLoading.hide();
                self_app.apppointment.leadsources = data;
                self_app.getFlags();
                setTimeout(function() {
                    self_app.apppointment.$apply(function(val) {
                        $('.timepicker').attr('readonly', true);
                        $(".timepicker").keydown(function(event) {
                            event.preventDefault();
                        });
                    });
                }, 100);
            });
        },
        getBookingAgent: function() {
            var self_app = this.apppointment;
            var name = _.where(self_app.detailAppointmentData._userss, {
                id: self_app.detailAppointmentData.addby_id
            })[0];
            if (name) {
                var booking_agent_name = (name.first_name + ' ' + name.last_name + ' - ' + name.positiontitles_name);
                _.extend(self_app.detailAppointmentData, {
                    booking_agent_name: booking_agent_name
                });
            }
        },
        getFieldWorker: function() {
            var _fieldworker = [];
            var self_app = this.apppointment;
            _.each(self_app.detailAppointmentData._userss, function(val) {
                if (val.role_id == 6 || val.role_id == 7) {
                    _fieldworker.push(_.extend(val, {
                        name: val.first_name + ' ' + val.last_name + ' - ' + val.positiontitles_name
                    }));
                }
            });
            _.extend(self_app.detailAppointmentData, {
                _fieldworker: _fieldworker
            });
        },
        getFieldWorkerByAppGroup: function() {
            var self_app = this.apppointment;
            if (self_app.detailAppointmentData.appointmentgroup_parent_id) {
                appGroup.getUserByAppGroupId(self_app.detailAppointmentData.appointmentgroup_parent_id).success(function(result) {
                    self_app.fieldWorkerByAppGroupList = result;
                    self_app.holdFieldWorkerOnApp.id = self_app.detailAppointmentData.fieldworker;
                    self_app.detailAppointmentData.prefieldworker = self_app.detailAppointmentData.prefieldworker;
                    self_app.Input_value.fieldWorker = "";
                    var value = _.where(self_app.fieldWorkerByAppGroupList, { id: self_app.holdFieldWorkerOnApp.id });
                    if (value[0]) self_app.Input_value.fieldWorker = value[0].name;
                });
            }
            self_app.detailAppointmentData.appointmentgroup_name = _.where(self_app.allAppointmentGroupsData, {
                id: self_app.detailAppointmentData.appointmentgroup_parent_id
            })[0].name;
        },
        renderDateFileMan: function($by) {
            var self_app = this.apppointment;
            // by all
            if ($by == 'all') {
                _.each(self_app.detailAppointmentData.files, function(val) {
                    val.created_date = Date.parseDate(val.created_date);
                });
            } else if ($by == 'app') {
                // by app
                _.each(self_app.allAppointmentHistoryData, function(val) {
                    if (val.files.length > 0) {
                        _.each(val.files, function(item) {
                            item.created_date = Date.parseDate(item.created_date);
                        })
                    }
                })
            }
        },
        eOnlyMobile: function() {
            var self_app = this.apppointment;
            var onMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(andRoid)|(Linux)|(webOS)/i) != null;
            if (onMobile) {
                return self_app.frmMobile = true;
            }
        },
        viewForm: function($viewForm, $viewBy) {
            $('.required').removeClass('onmacos');
            var self = this;
            var self_app = this.apppointment;
            var _tagId = '#' + $viewForm;
            var _viewForm = openPopup($(_tagId));
            $(_tagId).parent().parent().find('.close-title-button').addClass('dismis-popup');
            $(_tagId).parent().parent().find('.dismis-popup').unbind();
            $(_tagId).parent().parent().find('.dismis-popup').click(function() {
                self.eOnlyMobile();
                closePopupById($viewForm);
                $viewForm == 'popupFileManagementUpload' ? openPopup('#popupApptFileManagement') : openPopup('#popupAppointmentDetail');
                $('.app_file_man').next('.app_file_none').slideUp();
                $('.app_toggle.none').slideUp();
                $('.back_top_default').animate({
                    scrollTop: 0
                }, 1);
            });
            $(_tagId).find('form').children('div.fields').addClass('back_top_default').css({
                maxHeight: ($(window).outerHeight() - 120) + 'px',
                overflow: 'auto'
            });
            this.slideToggle();
            switch ($viewBy) {
                case 0:
                break;
                case 1:
                self_app.filetypeAppointment = 'All';
                break;
                case 2:
                self_app.filetypeAppointment = 'Photo';
                break;
                case 3:
                self_app.filetypeAppointment = 'PDFs';
                break;
                case 4:
                self_app.filetypeAppointment = 'Other';
                break;
                default:
                    // add new files
                    self_app.frmMobile = false;
                    break;
                }
            },
            slideToggle: function() {
                $('.app_file_none li').parent().prev('.app_file_man').html('(+)');
                $('.app_file_man').unbind();
                $('.app_file_man').click(function() {
                    var self = $(this);
                    $('.app_file_man').each(function(index) {
                        if ($(this).attr('id') != self.attr('id')) {
                            if ($(this).parent().find('.app_file_none li').length > 0) {
                                $(this).html('(+)');
                                $(this).parent().find('.app_file_none').slideUp();
                            }
                        }
                    });
                    $(this).text() == '(+)' ? $(this).html('(-)') : $(this).html('(+)');
                    $(this).parent().find('.app_file_none').slideToggle();
                });
            },
            checkSafari: function($onDevice) {
                $('.required').removeClass('onmacos');
                var status = true;
                if (navigator.userAgent.indexOf("Safari") > -1) {
                    if ($onDevice == 'desktop') {
                        $('#frmAppFileMan .required').each(function() {
                            if ($(this).val() == '') {
                                $(this).addClass('onmacos');
                                status = false;
                            }
                        });
                    } else {
                        $('#frmAppFileManOnMobile .required').each(function() {
                            if ($(this).val() == '') {
                                $(this).addClass('onmacos');
                                status = false;
                            }
                        });
                    }
                }
                return status;
            },
            upLoadFileMan: function($onDevice) {
                var self = this;
                if (this.checkSafari($onDevice)) {
                    _.extend(this.apppointment.dataFileMan, {
                        file_type: self.checkFileType(this.apppointment.dataFileMan.oFile.name),
                        file_size: this.apppointment.dataFileMan.oFile.size,
                        customer_id: this.apppointment.detailCustomerData.id,
                        appointment_id: this.apppointment.detailAppointmentData.id,
                    });
                    $('.f.tblloader').show();
                    appDetail.upLoadFileMan(this.apppointment.dataFileMan, this.apppointment.dataFileMan.oFile).success(function(data) {
                        if (data.status) {
                            self.apppointment.getDetailAppointment(self.apppointment.detailAppointmentData.id);
                            if ($onDevice == 'desktop') {
                                var confirmExit = $.confirm("Confirm to continue", '<div class="text-content baseline">Do you want to continue for uploading?</div></div>', {}, function() {
                                    confirmExit.switchStateDialog("close");
                                });
                                confirmExit.e.parent().parent().find('.close-title-button').addClass('dismis-popup');
                                confirmExit.e.parent().parent().find('.close-title-button').unbind();
                                confirmExit.e.parent().parent().find('.dismis-popup').click(function() {
                                    self.eOnlyMobile();
                                    confirmExit.switchStateDialog("close");
                                    openPopup('#popupAppointmentDetail');
                                });
                                confirmExit.e.parent().parent().find('.button input').first().addClass('dismis-popup').addClass('first');
                                confirmExit.e.parent().parent().find('.button input.first').first().unbind();
                                confirmExit.e.parent().parent().find('.dismis-popup.first').click(function() {
                                    confirmExit.switchStateDialog("close");
                                    self.apppointment.frmMobile = false;
                                    openPopup('#popupFileManagementUpload');
                                });
                                confirmExit.e.parent().parent().find('.button input').last().addClass('dismis-popup').addClass('last');
                                confirmExit.e.parent().parent().find('.button input.last').last().unbind();
                                confirmExit.e.parent().parent().find('.dismis-popup.last').click(function() {
                                    self.eOnlyMobile();
                                    confirmExit.switchStateDialog("close");
                                    openPopup('#popupAppointmentDetail');
                                });
                            } else {
                                closePopupById('popupFileManagementUpload');
                                openPopup('#popupAppointmentDetail');
                            }
                            $('#frmAppFileMan input[name="oFile"]').val('');
                            $('#frmAppFileMan input[name="file_name"]').val('');
                            toastr.success(data.msg);
                            self.apppointment.dataFileMan = {};
                            $('.f.tblloader').hide();
                        } else {
                            toastr.error(data.msg);
                        }
                    });
                }
            },
            checkFileType: function($fname) {
                var fileName = $fname;
                var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
                return ext;
            },
            captureOnMobile: function() {
                this.apppointment.mobileShow = true;
                var onMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(andRoid)|(Linux)|(webOS)/i) != null;
                onMobile ? this.apppointment.mobileShow = true : this.apppointment.mobileShow = false;
            },
            upLoadOnMobile: function($file) {
                if ($file == null || $file == undefined) return;
                this.apppointment.dataFileMan.oFile = $file;
                openPopup('#popupFileManagementUpload');
                this.apppointment.frmMobile = true;
                $('#popupFileManagementUpload').parent().parent().find('.close-title-button').addClass('dismis-popup');
                $('#popupFileManagementUpload').parent().parent().find('.dismis-popup').unbind();
                $('#popupFileManagementUpload').parent().parent().find('.dismis-popup').click(function() {
                    closePopupById('popupFileManagementUpload');
                    openPopup('#popupAppointmentDetail');
                });
            },
            sendToPushRoomFromAppDetail: function(data) {
                var self_app = this.apppointment;
                if (socket) {
                    socket.emit('new message', {
                        from_user: self_app.currentIdLogin,
                        room_id: data.room_id,
                        user_id: 0,
                        contents: data.msg,
                        content_raw: data.msg,
                        hashtag: '',
                        applicationtype: aplicationtype.text
                    });
                }
                ionicLoading.hide();
                closeTarget('#popupAppointmentDetailJobStatusChat');
            },
            updateAppDetail: function() {
                var self_app = this.apppointment;
            // first relate customer
            self_app.customer_data.first_name = self_app.detailCustomerData.first_name;
            self_app.customer_data.last_name = self_app.detailCustomerData.last_name;
            self_app.customer_data.street = self_app.detailCustomerData.street;
            self_app.customer_data.apt_unit = self_app.detailCustomerData.apt_unit;
            self_app.customer_data.city = self_app.detailCustomerData.city;
            self_app.customer_data.state = self_app.detailCustomerData.state;
            self_app.customer_data.zipcode = self_app.detailCustomerData.zipcode;
            self_app.customer_data.phone_number = self_app.detailCustomerData.phone_number;
            self_app.customer_data.email = self_app.detailCustomerData.email;
            self_app.customer_data.note = self_app.detailCustomerData.note;
            self_app.customer_data.flag_id = self_app.detailCustomerData.flag_id;
            self_app.customer_data.flag_note = self_app.detailCustomerData.flag_note;
            self_app.customer_data.id = self_app.detailCustomerData.id;
            self_app.customer_data.leadsource_id = self_app.detailCustomerData.leadsource_id;
            self_app.customer_phone = self_app.detailCustomerData.additionalPhone;
            self_app.is_customer = true;
            oppService.update_or_insert_customer(self_app.customer_data, self_app.customer_phone, self_app.is_customer).success(function(data) {
                ionicLoading.show({
                    template: templateLoading
                });
                if (data.status) {
                    // second relate appointment
                    self_app.dataApp.appointmentgroup_id = self_app.detailAppointmentData.appointmentgroup_id;
                    self_app.dataApp.fieldworker = self_app.holdFieldWorkerOnApp.id;
                    self_app.dataApp.prefieldworker = self_app.detailAppointmentData.prefieldworker;
                    self_app.dataApp.callahead_id = self_app.detailAppointmentData.callahead_id;
                    self_app.dataApp.customertype_id = self_app.detailAppointmentData.customertype_id;
                    self_app.dataApp.customer_id = self_app.detailAppointmentData.customer_id;
                    self_app.dataApp.flexiblecustomer_id = self_app.detailAppointmentData.flexiblecustomer_id;
                    self_app.dataApp.fieldworkernote = self_app.detailAppointmentData.fieldworkernote;
                    self_app.dataApp.officeapptnote = self_app.detailAppointmentData.officeapptnote;
                    self_app.editApp = {
                        'dataApp': self_app.dataApp,
                        'dataJobsite': self_app.detailAppointmentData.appointmentjobsites
                    }

                    var check = validateTime(self_app.detailAppointmentData.arrivalwindow, self_app.detailAppointmentData.endarrivalwindow);
                    if (!check.status) {
                        self_app.detailAppointmentData.endarrivalwindow = '';
                        location_.hash('endarrivalwindow'); //set the location hash
                        // var handle = ionicScrollDelegate.$getByHandle('popupAppointmentEdit');
                        // handle.anchorScroll(true);
                        ionicScrollDelegate.$getByHandle('popupAppointmentEdit').scrollTop();
                        ionicLoading.hide();
                        $cordovaToast.showLongTop('End time must be greater than start time');
                        return;
                    }
                    self_app.dataApp.dateofappt = $('#frmEditAppointment input[name="dateofappt"]').val();
                    self_app.dataApp.nothomeutil = $('#frmEditAppointment input[name="nothomeutil"]').val();
                    self_app.dataApp.arrivalwindow = moment(check.start, 'HH:mm:ss').format('hh:mmA');
                    self_app.dataApp.endarrivalwindow = moment(check.end, 'HH:mm:ss').format('hh:mmA');
                    appDetail.update(self_app.detailAppointmentData.id, self_app.editApp).success(function(data) {
                        if (data.status) {
                            ionicLoading.hide();
                            closeTarget('#scheduleDetailEdit');
                            self_app.refreshPageFromApp();
                            if (page == 'scheduleapp.html') {
                                self_app.loadAppointmentByDay(moment(self_app.dataAppHtml.scheduleDay).format('YYYY-MM-DD'));
                            }
                            cordovaToast.showLongTop(data.msg);
                        } else {
                            ionicLoading.hide();
                            cordovaToast.showLongTop(data.msg);
                        }
                    });
                } else {
                    ionicLoading.hide();
                    cordovaToast.showLongTop(data.msg);
                }
            });
        }
    }
    // variale
    scope = new extAppDetailView();
// delay render scope all controller
setTimeout(function() {
    scope.initCtrl();
}, 1000);
