var request = getRequest(),
    sessionId = request.sessionId,
    patiCode,
    patiName,
    consultCode,
    prescriptionStatus,
    prescriptionCode,
    page = 1,
    members = [],
    fv_id,
    quickReplyList,
    survey_1_obj, //身体异常症状问卷obj
    survey_2_obj; //体征及生活方式调查问卷obj

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;
        for(var i=0; i<members.length; i++){
            if(members[i].is_patient == 1){
                patiName = members[i].name;
                break;
            }
        }
        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({
                    scrollTo: 'bottom'
                });
            }
            
            $(".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 = APIService.getImgUrl(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 followup = res.data.followup;
            if(followup){
                followup = JSON.parse(followup);
                fv_id = followup.id;
            }
            var html = template('prescriptionInfo_tmp', res.data);
            prescriptionStatus = res.data.status;
            prescriptionCode = res.data.code;
            var statusName = getStatusName(res.data.status == '69' ? '61' : res.data.status);
            $(".status-btn").text(statusName);
            $("#prescriptionInfo").empty().append(html);
            $("#prescriptionInfo").slimscroll({
                height: '100%',
                width: '100%'
            });
        }else{
            showWarningMsg(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{
            showWarningMsg(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);
            if(data.read && data.read == "all"){
                return ;
            }
            var html = formatMsg(data);
            $("#talkBox").append(html);
            $("#talkBox").slimscroll({
                scrollTo: 'bottom'
            });
        });
        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({
                        scrollTo: 'bottom'
                    });
                    $('.info-panel').html("咨询求助已结束");
                    $(".send-btn").addClass("disabled");
                    $("#file_head").attr("disabled", true);
                    showSuccessMsg("已结束咨询");
                } else {
                    showErrorMsg(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){
                showWarningMsg('发送内容不能为空');
                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: 'bottom'
                });
            }
        }
    });

    $("#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: 'bottom'
                });
            }else{

            }
        });
    });

    //查看详情
    $("body").on('click', '.view-detail', function(){
        //修改顶部tab页面的
        var url = parent.document.getElementById("tab").src;
        parent.document.getElementById("tab").src = "prescription-tabs.html?sessionId="+sessionId+"&patiCode="+patiCode+"&code="+prescriptionCode+"&tab=1&fromTabIdx=0";
    });
    
    template.helper('getSourceUrl', function(str){
        return APIService.getImgUrl(str);
    });
    
    //导入随访相关控件监听
    $("body").on('click', '.import-fv', function(){
        var $this = $(this),
            type = $this.attr("data-type"), // 1-血压，2-血糖
            health = $this.attr("data-health"),
            params = {
                prescriptioncode: prescriptionCode,
                followupid: fv_id,
                healthindexid: health
            };
        if(type == 1){
            consultingAPI.importbloodpressure(params).then(function(res){
                if(res.status == 200){
                    showSuccessMsg("已填入");
                }else{
                    showErrorMsg(res.msg)
                }
            })
        }else if(type == 2){
            consultingAPI.importbloodsugar(params).then(function(res){
                if(res.status == 200){
                    showSuccessMsg("已填入");
                }else{
                    showErrorMsg(res.msg)
                }
            })
        }
    });
    
    //导入药品到随访记录中
    $(".import-drugs").on('click', function(){
        var params = {
            prescriptioncode: prescriptionCode,
            followupid: fv_id
        };
        consultingAPI.importdrugs(params).then(function(res){
            if(res.status == 200){
                showSuccessMsg("已将续方药品填入本次随访记录");
            }else{
                showErrorMsg(res.msg);
            }
        });
    });
    
    //查看问卷记录
    $("body").on('click', '.view-survey', function(){
        var $this = $(this),
            msgType = $this.attr("data-type");
            
        parent.gotoPrescriptionTab(8);
    });
    
    //快捷回复相关监听事件
    bindReplyEvents();
}

//-------------------------------快捷回复相关内容--------------------------
var count = 0;
function showQuickReplyPanel(e){
    var $el = $(e),
        offset = $el.offset();
    if(count == 0){
        $(".quick-reply-panel").css({"left": offset.left});
        //获得快捷回复列表
        getQuickReplayList();
        $(".quick-reply-panel").toggle("show");
    }else{
        //渲染前4条记录
        var list = quickReplyList.slice(0, 4),
            html = template("quick_reply_tmp", {list: list});
        $(".quick-reply-panel ul").empty().append(html);
        $(".quick-reply-panel").toggle("show");
    }
}
function getQuickReplayList(){
    consultingAPI.getReplyList({type: 1}).then(function(res){
        if(res.status == 200){
            count ++;
            formatReplyList(res.data);
            
            //渲染前4条记录
            var list = quickReplyList.slice(0, 4),
                html = template("quick_reply_tmp", {list: list});
            $(".quick-reply-panel ul").empty().append(html);
            
            //判断问卷是否填写
            getFollowupContentList();
        }else{
            showErrorMsg(res.msg);
        }
    })
}

function formatReplyList(data){
    quickReplyList = _.map(data, function(o){
        //"systag":0为医生自定义消息，大于0的为系统该消息，1体征生活方式 2症状 3血糖 4血压
        if(o.systag == 1 || o.systag == 2){
            o.name = "survey"; //问卷 
        }else if(o.systag == 3 || o.systag == 4){
            o.name = "test"; //体检
        }else{
            o.name = "";
        }
        if(o.systag == 1 || o.systag == 3){
            o.tagType = 2;
        }else if(o.systag == 2 || o.systag == 4){
            o.tagType = 1;
        }else{
            o.tagType = 0;
        }
        return o;
    });
}

//获得问卷列表，判断个问卷是否已经填写
function getFollowupContentList(){
    var params = {
        prescriptioncode: prescriptionCode
    };
    consultingAPI.getFollowupCountList(params).then(function(res){
        if(res.status == 200){
            //'type': '1',//1身份异常症状问卷，2体征及生活方式调查问卷
            // 'statue': '1',//1已填写，2未填写
            var len = res.data.length;
            for(i=0; i<len; i++){
                var item = res.data[i];
                if(item.type == '1'){
                    survey_1_obj = item;
                }
                if(item.type == '2'){
                    survey_2_obj = item;
                }
            }
        }else{
            showErrorMsg(res.msg);
        }
    })
}

function bindReplyEvents(){
    $("body").on('click', ".reply-item", function(){
        var $this = $(this),
            json = $this.data("json"),
            name = json.name,
            type = json.tagType;
        
        var params = {
            prescriptionCode: prescriptionCode,
            type: type,
            followupid: fv_id
        };
        if(name == "test"){ //发送血糖血压快捷回复咨询
            consultingAPI.addPrescriptionBloodStatusConsult(params).then(function(res){
                if(res.status == 200){
                    $(".quick-reply-panel").hide();
                    layer.close(layer.index);
                    //发送成功后，socket会响应退出最新的消息
                }else{
                    showErrorMsg(res.msg);
                }
            })
        }else if(name == "survey"){//发送问卷快捷回复咨询
            //判断是否已经填写过问卷
            if(type == '1' && survey_1_obj.statue == '1'){
                var content = "居民"+patiName+"已在"+survey_1_obj.createtime+"填写"+survey_1_obj.name;
                layer.open({
                    title: " ",
                    content: content,
                    skin: 'alert-info',
                    btn: ['查看问卷'],
                    yes: function(index){
                        parent.gotoPrescriptionTab(8);
                        layer.close(index);
                    }
                });
                return false;
            }
            if(type == '2' && survey_2_obj.statue == '1'){
                var content = "居民"+patiName+"已在<br/>"+survey_2_obj.createtime+"填写"+survey_2_obj.name;
                layer.open({
                    title: " ",
                    content: content,
                    skin: 'alert-info',
                    btn: ['查看问卷'],
                    yes: function(index){
                        parent.gotoPrescriptionTab(8);
                        layer.close(index);
                    }
                });
                return false;
            }
            consultingAPI.addPrescriptionFollowupContentConsult(params).then(function(res){
                if(res.status == 200){
                    layer.close(layer.index);
                    $(".quick-reply-panel").hide();
                    //发送成功后，socket会响应退出最新的消息
                }else{
                    showErrorMsg(res.msg);
                }
            })
        }else{
            //发送普通文本
            sendMessage(1, json.content);
            var obj = {
                content: json.content,
                content_type: '1',
                sender_id: docInfo.code,
                timestamp: new Date().getTime()
            }
            var html = formatMsg(obj);
            
            $("#talkBox").append(html);
            $("#talkBox").slimscroll({
                scrollTo: 'bottom'
            });
            layer.close(layer.index);
            $(".quick-reply-panel").hide();
        }
    });
    
    $("body").on("click", '.addMore', function(){
        showReplyListPanel();
        $(".quick-reply-panel").hide();
    })
    
    template.helper("getJsonStr", function(obj){
        if(typeof obj == "object"){
            return JSON.stringify(obj);
        }else{
            return "";
        }
    });
    
    $("body").on("click", ".del-icon", function(e){
        e.stopPropagation();
        var $this = $(this),
            $parent = $this.closest(".reply-item"),
            json = $parent.data("json"),
            systag = json.systag;
        if(systag > 0){
            layer.msg('系统默认回复内容不可删除');
        }else{
            //删除快捷回复
            consultingAPI.deleteQuickReply({id: json.id}).then(function(res){
                if(res.status == 200){
                    showSuccessMsg(res.msg);
                    $parent.remove();
                    //将quickReplyList数组中对应的元素删除
                    for(i=0; i< quickReplyList.length; i++){
                        var item = quickReplyList[i];
                        if(item.id == json.id){
                            quickReplyList.splice(i, 1);
                            break;
                        }
                    }
                }else{
                    showErrorMsg(res.msg);
                }
            });
        }
    });
    
    $("body").on('click', '.up-icon', function(e){
        e.stopPropagation();
        var li = this.parentNode.parentNode;
        if(li.previousElementSibling){
            swapNode(li,li.previousElementSibling);
        }
    });
    
    $("body").on('click', '.down-icon', function(e){
        e.stopPropagation();
        //通过链接对象获取表格行的引用
        var li = this.parentNode.parentNode;
        //如果不是最后一行，则与下一行交换顺序
        if(li.nextElementSibling){
            swapNode(li,li.nextElementSibling);
        }
    })
}

function showReplyListPanel(){
    //准备content html 内容
    var html = template('reply_tmp', {list: quickReplyList});
    layer.open({
        type: "1",
        title: '<img src="img/shezi_tankuang_icon.png" class="mr10">快捷回复设置',
        content: html,
        area: ['430px', '360px'],
        skin: 'quick-reply-setting',
        btn: ['添加', '取消'],
        yes: function(index){
            var html2 = '<div class="pl30 pr20"><p>回复内容：</p><textarea style="margin:0px; width: 100%; height: 80px;" maxlength="100" id="reply_content"></textarea></div>';
            layer.open({
                type: "1",
                title: '<img src="img/shezi_tankuang_icon.png" class="mr10">添加自动回复',
                content: html2,
                area: ['420px', '227px'],
                skin: 'quick-reply-setting',
                btn: ['确定', '取消'],
                yes: function(index2){
                    var text = $.trim($("#reply_content").val());
                    saveNewReply(text, index2);
                }
            });
        }
    });
}

//定义通用的函数交换两个结点显示的内容，不移动DOM
function swapNode(node1,node2){
    //获取两个节点的json数据和content数据
    var json1 = $(node1).attr("data-json"),
        content1 = $(node1).find(".content").text(),
        id1 = $(node1).data("id"),
        json2 = $(node2).attr("data-json"),
        content2 = $(node2).find(".content").text(),
        id2 = $(node2).data("id");
    
    $(node1).attr("data-json", json2);
    //data修改和attr修改不一致
    $(node1).data("id", id2);
    $(node1).attr("data-id", id2);
    $(node1).find(".content").text(content2);
    $(node2).attr("data-json", json1);
    $(node2).data("id", id1);
    $(node2).attr("data-id", id1);
    $(node2).find(".content").text(content1);
    //请求排序接口
    sortQuickReply();
}

function sortQuickReply(){
    var $lis = $(".reply-list2 li"),
        len = $lis.length,
        ids = [];
    
    for(i=0; i<len; i++){
        var $li = $($lis[i]),
            id = $li.data("id");
        ids.push(id);
    }
    //重新排序
    var params = {
        id: ids.join(","),
        type: 1 //"type":1,//快捷回复类型(1为续方咨询,0为健康咨询)
    };
    consultingAPI.sortList(params).then(function(res){
        consultingAPI.getReplyList({type: 1}).then(function(res){
            if(res.status == 200){
                formatReplyList(res.data);
            }
        })
    })
}

function saveNewReply(text, layerIndex){
    var params = {
        content: text,
        type: 1
    }
    consultingAPI.addQuickReply(params).then(function(res){
        if(res.status == 200){
            showSuccessMsg("保存成功");
            consultingAPI.getReplyList({type: 1}).then(function(res){
                if(res.status == 200){
                    formatReplyList(res.data);
                    //重新渲染列表
                    var html = template('reply_tmp', {list: quickReplyList});
                    var preLayerIndex = layerIndex - 1;
                    $("#layui-layer"+preLayerIndex).find(".layui-layer-content").empty().append(html);
                    layer.close(layerIndex);
                }
            })
        }else{
            showErrorMsg(res.msg);
        }
    });
}
