var request = getRequest(),
    sessionId = request.sessionId,
    patiCode,
    consultCode,
    prescriptionStatus,
    page = 1,
    members = [];

var docInfo = window.localStorage.getItem("docInfo");
docInfo = JSON.parse(docInfo);

$(function(){
    //续方咨询的sessionId 格式 居民code+咨询code+咨询类型（ 8 ）
    patiCode = sessionId.split("_")[0];
    consultCode = sessionId.split("_")[1];

    getConsultStatus();
    
    //获得会话参与人员
    consultingAPI.getMembers(sessionId).then(function(res){
        members = res;
        getMessage(true);
    })
    getPrescriptionInfo();
    getPatientServiceType(); //获得患者的标签类型
    connectSocket();
    bindEvents();
})

function getConsultStatus(){
    var params = {consult: consultCode};
    consultingAPI.getConsultStatus({data: params}).then(function(res){
        if(res.status == 200){
            //咨询状态（0进行中，1已完成，-1患者取消，-2超时未响应自动关闭）
            if(res.data == 0) { //咨询未结束
                
            } else { //咨询已结束
                $('.info-panel').html('咨询求助已结束');
                $('.send-btn').addClass("disabled");
                $("#file_head").attr("disabled", true);
            }
        }else{

        }
    });
}

function getMessage(isInit){
    var params = {
        page: page,
        pagesize: 10,
        end_msg_id: '',
        start_msg_id: '',
        user: docInfo.code,
        session_id: sessionId,
        content_type: '',
        isoffset: ''
    }
    consultingAPI.getMessages(sessionId, {data: params}).then(function(res){
        var list = res;
        if (list && list.length > 0) {
            id = list[list.length - 1].id;
            var html = '',
                length = list.length;
            
            for (var j = list.length-1; j >= 0; j--) {
                var reply = list[j];
                html += formatMsg(reply);
            }
            if(isInit){
                $("#talkBox").append(html);
                $("#talkBox").slimScroll({
                    height: '100%',
                    width: '100%',
                    alwaysVisible: true,
                    start : 'bottom',
                }).bind('slimscroll', function(e, pos) {
                    if(pos == 'top'){
                        if(length == 10){
                            page++;
                            getMessage();
                        }
                    }
                });
            }else{
                $("#talkBox").prepend(html);
                $("#talkBox").slimScroll();
            }
            
            $(".fancybox").fancybox({openEffect:"none",closeEffect:"none"});
            plyr.setup();
        }
    });
}

function formatMsg(reply){
    try{
        reply = JSON.parse(reply);
    }catch(e){
    }
    var isSelf = (reply.sender_id==docInfo.code) ? true : false;
    var isSystem = reply.sender_id == 'system';
    var html = '';
    if(reply.content_type == 7 || reply.content_type == 10){
        var content = reply.content;
        if(isSystem){
            content = '居民24小时内未回复，系统自动结束咨询';
        }
        html = template('sys_msg_tmp', {content: content});
    }else{
        var member;
        for(var i=0; i<members.length; i++){
            if(reply.sender_id == members[i].id){
                member = members[i];
                break;
            }
        }
        var img = member.avatar;
        if((img.indexOf('http') == -1) && (img.indexOf("https") == -1)){
            img = member.is_patient ? 'img/p-default.png' : 'img/d-male.png';
        }
        var content = '';
        try{
            content = JSON.parse(reply.content);
        }catch(e){
            if(reply.content_type == 12){ //视频文件
                var arr = reply.content.split(",");
                content = {};
                content.img = arr[0];
                content.path = arr[1];
                content.time = arr[2];
            }else{
                content = reply.content;
            }
        }
        var obj = {
            isSelf: isSelf,
            time: new Date(reply.timestamp).format('yyyy-MM-dd HH:mm:ss'),
            type: reply.content_type,
            name: member.name,
            img: img,
            content: content
        };
        html = template('msg_tmp', obj);
    }
    return html;
}

function getPrescriptionInfo(){
    var params = { consult: consultCode};
    consultingAPI.getPrescriptionInfo({data: params}).then(function(res){
        if(res.status == 200){
            var html = template('prescriptionInfo_tmp', res.data);
            prescriptionStatus = res.data.status;
            var statusName = getStatusName(res.data.status);
            $(".status-btn").text(statusName);
            $("#prescriptionInfo").empty().append(html);
            $("#prescriptionInfo").slimscroll({
                height: 'calc(100% - 60px)',
                width: '100%'
            });
        }else{
            toastr && toastr.warning(res.msg);
        }
    });
}

function getPatientServiceType(){
    var params = {patient: patiCode};
    consultingAPI.getPatientServiceType({data: params}).then(function(res){
        if(res.status == 200){
            //slowDiseasePatient: 0 //0表示没有慢病服务类型，1表示有
            if(res.data.slowDiseasePatient == 0){
                $(".diseaseInfo").html("此居民未被标注【慢病】相关标签，请在i健康APP上核实");
            }else{
                var disease = "";
                for(var i=0; i<res.data.signFamilyServer.length; i++){
                    var item = res.data.signFamilyServer[i];
                    if(i>0){
                        disease += '，'+item.name;
                    }else{
                        disease += item.name;
                    }
                }
                $(".diseaseInfo").text("该居民为"+disease+"患者");
            }
        }else{
            toastr && toastr.warning(res.msg);
        }
    });
}

function connectSocket(){
    jQuery.getScript(APIService.socketUrl+"/socket.io/socket.io.js").done(function() {
        var socket = io.connect(APIService.socketUrl );
        socket.emit('login', {
            userId: docInfo.code, 
            password: docInfo.code, 
            sessionId: sessionId,
            clientType: "doctor"
        });
        socket.on('message', function (data) {
            console.log(data);
            var html = formatMsg(data);
            $("#talkBox").append(html);
            $("#talkBox").slimscroll();
        });
        socket.on('error', function (data) {
            console.log(data)
        });
        socket.on('ack', function (data) {
        });
    }).fail(function() {
        // dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:"医生实时对话连接失败！"}).show();     
    });
}

function sendMessage(contentType, content){
    var params = {
        sender_id: docInfo.code,
        sender_name: docInfo.name,
        content_type: contentType,
        content: content,
        view: 0
    };
    consultingAPI.sendMessage(sessionId, {data: params}).then(function(res){
        console.log(res);
        // var html = "";
        // for(var i=0; i<res.messages.length; i++){
        //     var reply = res.messages[i];
        //     console.log(reply);
        //     html += formatMsg(reply);
        // }
        // $("#talkBox").append(html);
        // $("#talkBox").slimscroll({
        //     scrollTo: this.height
        // });
    });
}

//结束咨询
function finish(){
    //判断续方状态，如果未审核，则不可以结束咨询
    if(prescriptionStatus > 0 && prescriptionStatus < 21){
        dialog({
            content:'续方申请未审核，不能结束咨询',
            width: 460,
            okValue:'我知道了',
            ok: function() {
                return;
            }
        }).width(320).showModal();
        return false;
    }
    dialog({
        content:'结束咨询后，居民及所有医生均无法再次回复，是否确认继续结束？',
        width: '460px',
        okValue:'继续结束',
        ok: function() {
            var params = {consult: consultCode};
            consultingAPI.finishConsult({data: params}).then(function(res){
                if(res.status == 200) {
                    var content = docInfo.name+'结束了咨询',
                        html = template('sys_msg_tmp', {content: content});
                    $("#talkBox").append(html);
                    $("#talkBox").slimScroll();
                    $('.info-panel').html("咨询求助已结束");
                    $(".send-btn").addClass("disabled");
                    $("#file_head").attr("disabled", true);
                    toastr.success("已结束咨询");
                } else {
                    toastr.error(res.msg);
                }
            })
        },
        cancelValue: '我再看看',
        cancel: function(){}
    }).showModal();
}

function bindEvents(){
    $(".send-btn").on('click', function(){
        var $this = $(this);
        if($this.hasClass("disabled")){
            return false;
        }else{
            var text = $.trim($("#input_content").text());
            if(text.length == 0){
                toastr.options = {
                    "positionClass": "toast-top-center",
                }
                toastr.warning('发送内容不能为空');
                return false;
            }else{
                sendMessage(1, text);
                $("#input_content").text('');
                var obj = {
                    content: text,
                    content_type: '1',
                    sender_id: docInfo.code,
                    timestamp: new Date().getTime()
                }
                var html = formatMsg(obj);
                
                $("#talkBox").append(html);
                $("#talkBox").slimscroll({
                    scrollTo: this.height + 80
                });
            }
        }
    });

    $("#file_head").on('change', function(){
        var file = this.files[0];
        //先上传图片去服务器，然后再发送消息
        var fd=new FormData();
        fd.append("action", "UploadVMKImagePath");  
        fd.append("file", file); //加入文件对象
        fd.append("type", '2');
        var ajaxObj = {
            data: fd,
            cache: false,
            processData: false,
            contentType: false 
        }
        consultingAPI.uploadImage(ajaxObj).then(function(res){
            if(res.status == 200){
                sendMessage(2, res.urls);
                var obj = {
                    content: res.urls,
                    content_type: '2',
                    sender_id: docInfo.code,
                    timestamp: new Date().getTime()
                }
                var html = formatMsg(obj);
                
                $("#talkBox").append(html);
                $("#talkBox").slimscroll({
                    scrollTo: this.height + 80
                });
            }else{

            }
        });
    })

}

