/**
 * [OElove webapp] (C)2010-2099 oelove.com Inc.biz
 * Email: service@phpcoo.com，phpcoo@qq.com
 * This is not a freeware, use is subject to license terms
 * $ LastTime 2020.04.09 Update by OE/CL&BO $
*/
var _inst_oechat = null;
$(function(){
    //聊天
    function OEChat() {
        this.api_url = WAP_APPFILE+"&c=msgchat";
        
        this.chat_sid = ''; //通信sid
        this.chat_uid = ''; //接收人UID
        this.lastid = ''; //最近一条
        this.content = ''; //内容
        this.obj_id = '';
        this.init_time = 10000; //首次刷新时间
        this.refresh_time = 2000; //即时刷新时间
        this.height = $("#content").outerHeight(); //输入框原始高度
        
        
        this.animate_timer = null; //播放动画时间
        this.isplay = false; //播放语音
        this.play_node = null; //语音节点
        this.play_url = ''; //语音地址
        this.amr = ''; //amr对象
        
        this.clickEmoji();
        this.clickSend();
        this.playAudio();
        this.clickFreeLock();
        this.scrollToView();
    }
    
    OEChat.prototype = {
        
        //异步加载表情
        clickEmoji:function() {
            var _this = this;
            var _emoji_timeout = null;
            //获取表情
            _emoji_timeout = setTimeout(function(){
                _this.getEmoji();
                clearTimeout(_emoji_timeout);
            }, 800);
            
            //展开表情
            $('[f="emoji"]').on('click', function () {
               if ($("#emoji").length > 0) {
                   _inst_oeemoji.showEmojiSelector();
               }
               else {
                   $.ajax({
                        type: "POST",
                        url: _this.api_url,
                        cache: false,
                        data:{
                            a:'emoji'
                        },
                        dataType: "json",
                        success: function($data) {
                            var $json = eval($data);
                            var $response = $json.response;
                            var $result = $json.result;
                            if ($response == "1") {
                                $("#send_wrap").append($result);
                                setTimeout(function(){
                                    _inst_oeemoji.showEmojiSelector();
                                }, 50);
                            }
                        },
                        error: function() {
                        }
                    });
               } 
            });
        },
        getEmoji:function(){
            var _this = this;
            $.ajax({
                type: "POST",
                url: _this.api_url,
                cache: false,
                data:{
                    a:'emoji'
                },
                dataType: "json",
                success: function($data) {
                    var $json = eval($data);
                    var $response = $json.response;
                    var $result = $json.result;
                    if ($response == "1") {
                        if ($("#emoji").length > 0) {
                        }
                        else {
                            $("#send_wrap").append($result);
                        }
                    }
                },
                error: function() {
                }
            });
        },
        
        //初始化
        clickSend:function() {
            var _this = this;
            
            _this.chat_uid = $("#chat_uid").val();
            _this.chat_sid = $("#sid").val();
            
            //加载js
            setTimeout(function(){
                _this.loadJs();
            }, 2000);
            
            //请求最新数据
            setTimeout(function(){
                _this.getNewList();
            }, _this.init_time);
            
            
            //点击发送按钮
            $(document).on("click", "[f='but_send_chat']", function(){
                _this.obj_id = $(this).attr("id");
                var content = $("#content").html();
                _this.content = _this.filterHtml(content);
                _this.content = _this.translateEmoji(_this.content);
                if (_this.content == '') {
                    OEUI.toast({
                        type: 'bottom',
                        text: '发送内容不能为空'
                    });
                    return;
                }
                _this.send();
            });
        },
        
        //执行发送
        send:function() {
            var _this = this;
            if (!$("#"+_this.obj_id).hasClass("forbid_submit")) {
                var loading = null;
                var timer = setTimeout(function () {
                    loading = OEUI.showLoading({
                        type:2
                    });
                }, 200);
                $("#"+_this.obj_id).addClass("forbid_submit");
                $.ajax({
                    type: "POST",
                    url: _this.api_url,
                    cache: false,
                    data:{
                        a:'savewrite', touid:_this.chat_uid, content:_this.content
                    },
                    dataType: "json",
                    success: function($data) {
                        var $json = eval($data);
                        var $response = $json.response;
                        var $result = $json.result;
                        
                        clearTimeout(timer);
                        loading && loading.hideLoading();
                        timer = null;
                        
                        if ($response == "1") {
                            $("#content").html('');
                            $('#emoji').hide();
                            _this.getLastSend($result); //读取我刚发的
                            $("#lastid").val($result);
                            _this.callBackNotify(); //回调其他
                        }
                        else if ($response == '2') {
                            if (_inst_oechat_dialog) {
                                
                                $("#double_tips_1").hide();
                                $("#double_tips_2").show();
                                _inst_oechat_dialog.openDialog('double');
                                
                            }
                        }
                        else {
                            if ($result.length == 0 || $result == '') {
                                $result = '发送失败，请检查';
                            }
                            OEUI.toast({
                                type: 'bottom',
                                text: $result
                            }); 
                        }
                        $("#"+_this.obj_id).removeClass("forbid_submit");
                    },
                    error: function() {
                        $("#"+_this.obj_id).removeClass("forbid_submit");
                        clearTimeout(timer);
                        loading && loading.hideLoading();
                        timer = null;
                        OEUI.toast({
                            type: 'bottom',
                            text: '网络繁忙，请稍后再试！'
                        });
                    }
                });
                
            } 
        },

        //获取我最后发的消息
        getLastSend($msgid) {
            var _this = this;
            $.ajax({
                type: "POST",
                url: _this.api_url,
                cache: false,
                data:{
                    a:'getlast', id:$msgid
                },
                dataType: "json",
                success: function($data) {
                    var $json = eval($data);
                    var $response = $json.response;
                    var $result = $json.result;
                    if ($response == "1") {
                        //判断页面是否存在了该条信息
                        if ($("#list_"+$msgid).length > 0) {
                            
                        }
                        else {
                            $("#pull_data").append($result);
                            //滚到最底下
                            $('#pull_box .scroll').scrollTop($('#pull_box .scroll').prop("scrollHeight"));
                            
                            //判断是否帮忙解锁
                            var $isfree = $json.isfree;
                            if (typeof($isfree) == 'undefined') {
                                $isfree = '';
                            }
                            var $sidstatus = $json.sidstatus;
                            if (typeof($sidstatus) == 'undefined') {
                                $sidstatus = '';
                            }
                            if ($isfree == '0' && $sidstatus == '0') {
                                $("#help_free_tips").show();
                            }
                        }
                    }
                },
                error: function() {
                    
                }
            });
        },
        
        //时时获取即时聊天
        getNewList() {
            var _this = this;
            var $lastid = $("#lastid").val();
            
            $.ajax({
                type: "POST",
                url: _this.api_url,
                cache: false,
                data:{
                    a:'lastlist', sid:_this.chat_sid, lastid:$lastid
                },
                dataType: "json",
                success: function($data) {
                    var $json = eval($data);
                    var $response = $json.response;
                    var $result = $json.result;
                    var $lastid = $json.lastid;
                    var $total = $json.total;
                    if ($response == "1") { 
                        //有新消息
                        if ($total > 0) {
                            $("#pull_data").append($result);
                            //滚到最底下
                            $('#pull_box .scroll').scrollTop($('#pull_box .scroll').prop("scrollHeight"));
                            $("#lastid").val($lastid); //重置lastid
                        }
                        
                        //时时更新
                        setTimeout(function(){
                            _this.getNewList();
                        }, _this.refresh_time);
                    }
                    
                    else {

                    }
                },
                error: function() {
                    
                }
            });
        }, 
        
        //微信、邮件通知收件人
        callBackNotify:function() {
            var _this = this;
            $.ajax({
                type: "POST",
                url: _this.api_url,
                cache: false,
                data:{
                    a:'callback', touid:_this.chat_uid
                },
                dataType: "json",
                success: function($data) {
                    var $json = eval($data);
                    var $response = $json.response;
                    var $result = $json.result;
                    if ($response == '1') {
                        
                    }
                },
                error: function() {
                    
                }
            });
            
        },
        
        //过滤HTML标签
        filterHtml: function (content) {
            var reg = /<div>|<\/div>|<br>|<\/br>/ig;
            var str  = content.replace(reg, '');
            return str;
        },
        
        //表情替换
        translateEmoji: function (data) {
            var reg = /<img[^>]*src[=\"\'\s]+[../|..\\]*[^\.]*\/([^\.]+)\.[^\"\']+[\"\']?[^>]*>/ig;
            var content  = data.replace(reg, '{emf_$1}');
            return content;
        },
        
        
        loadJs:function() {
            var _this = this;
            var $html_content = "<script src='"+_ROOT_PATH +"tpl/static/js/amrplay.min.js?v="+VERSION+"'></script>"; 
            $("body").append($html_content);
        },
        
        //播放语音
        playAudio: function () {
            var _this = this;
            
            $(document).on('click', '[f="listen_voice"]', function (e) {
                var voice_url = e.currentTarget.dataset.voice;
                var s = e.currentTarget.dataset.voicelong;
                var target = $(this);
                //播放
                if (typeof BenzAMRRecorder == 'function') {
                    if(_this.amr && _this.amr.isPlaying()) {
                        _this.amr.stop();
                        if(_this.play_url == voice_url) {
                            _this.isplay = false;
                            _this.play_url = voice_url;
                            return;
                        }
                    }
                    _this.play_url = voice_url;
                    _this.amr = new BenzAMRRecorder();
                    _this.amr.initWithUrl(voice_url).then(function() {
                        _this.play_node = target;
                        _this.addAnimate(_this.play_node);
                        _this.isplay = true;
                        _this.amr.play();
                    });
                    _this.amr.onStop(function() {
                        _this.removeAimate(_this.play_node);
                        _this.isplay = false;
                    });
                    _this.amr.onEnded(function() {
                        _this.removeAimate(_this.play_node);
                        _this.isplay = false;
                    });
                }
            });
        },
        //播放动画
        addAnimate: function (el) {
            var _this = this;
            var path = el.find('path');
            var i = 0;
            _this.animate_timer = setInterval(function() {
                i %=3;
                if(i == 0) {
                    path[0].setAttribute('fill', '#666');
                    path[1].setAttribute('fill', '#666');
                    path[2].setAttribute('fill', '#000');
                } else if(i == 1) {
                    path[0].setAttribute('fill', '#666');
                    path[1].setAttribute('fill', '#000');
                    path[2].setAttribute('fill', '#000');
                } else {
                    path[0].setAttribute('fill', '#000');
                    path[1].setAttribute('fill', '#000');
                    path[2].setAttribute('fill', '#000');
                }
                i++
            }, 500);
        },
        //取消动画
        removeAimate: function (el) {
            var _this = this;
            clearInterval(_this.animate_timer);
            _this.animate_timer = null;
            var path = el.find('path');
            path[0].setAttribute('fill', '#000');
            path[1].setAttribute('fill', '#000');
            path[2].setAttribute('fill', '#000');
        },
        
        //解锁
        clickFreeLock:function() {
            var _this = this;
            
            $(document).on("click", "[f='but_free_chat']", function(){
                var $type = $(this).attr("data-type");
                if (typeof($type) == 'undefined') {
                    $type = '';
                }
                
                _this.sendFree($type);
            });
        },
        //发送解锁
        sendFree:function($type) {
            var _this = this;
            
            var loading = null;
            var timer = setTimeout(function () {
                loading = OEUI.showLoading({
                    type:2
                });
            }, 200);
            $.ajax({
                type: "POST",
                url: _this.api_url,
                cache: false,
                data:{
                    a:'freesid', sid:_this.chat_sid, type:$type
                },
                dataType: "json",
                success: function($data) {
                    var $json = eval($data);
                    var $response = $json.response;
                    var $result = $json.result;
                    
                    clearTimeout(timer);
                    loading && loading.hideLoading();
                    timer = null;
                    
                    if ($response == "1") {
                        OEUI.toast({
                            text: '解锁成功'
                        }); 
                        if (_inst_oechat_dialog) {
                            _inst_oechat_dialog._chat_dialog.hide(function(){
                                setTimeout(function(){
                                    window.location.reload();
                                }, 800);
                            });
                        }
                    }
                    else if ($response == '2') {
                        if (_inst_oechat_dialog) {
                            _inst_oechat_dialog._chat_dialog.hide(function(){
                                setTimeout(function(){
                                    window.location.href = WAP_APPFILE + '&c=pay&paynum='+$result;
                                }, 100);
                            });
                        }
                    }
                    else if ($response == '22') {
                        //呼出微信支付
                        var $back_url = WAP_APPFILE+'&c=msgchat&a=sid&id='+_this.chat_sid+'&nofollow=1';
                        var $pay_data = {
                            'paynum': $result,
                            'forward': $back_url
                        };
                        _inst_oewx_pay.initPay($pay_data, function(){
                            OEUI.toast({
                                //type: 'bottom',
                                text: '解锁成功'
                            });
                            _inst_oechat_dialog._chat_dialog.hide(function(){
                                setTimeout(function(){
                                    window.location.reload();
                                }, 800);
                            });
                        });
                    }
                    else {
                        if ($result.length == 0 || $result == '') {
                            $result = '解锁失败，请检查';
                        }
                        OEUI.toast({
                            text: $result
                        }); 
                    }
                },
                error: function() {
                    $("#"+_this.obj_id).removeClass("forbid_submit");
                    clearTimeout(timer);
                    loading && loading.hideLoading();
                    timer = null;
                    OEUI.toast({
                        text: '网络繁忙，请稍后再试！'
                    });
                }
            });
        },
        //IOS下点击表情是滚动body,防止键盘挡住表请输入框
        scrollToView: function () {
            $('#content').on('focus', function () {
                var sTop = window.screen.height;
                setTimeout(function(){
                    var driver = ''; //设备
                    var u_agent = navigator.userAgent; //客户端
                    if (/(iPhone|iPad|iPod|iOS)/i.test(u_agent)) {
                        driver = 'ios'; //判断iPhone|iPad|iPod|iOS
                    }
                    if (driver == 'ios') {
                        // OEUI.toast({
                        //     type: 'top',
                        //     text: sTop
                        // })
                        // window.scrollTo(0, sTop);
                    }
                }, 1000);
            });
        }
    }
    
    _inst_oechat = new OEChat();
});