var dd = dialog({contentType:'load', skin:'bk-popup', content:'发送中...'});
var d = dialog({
contentType: 'load',
skin: 'bk-popup'
});
var userAgent = JSON.parse(window.localStorage.getItem(agentName));
var dialroll;
var content = "";
var timeStr = "";
var id = 1;
var pagesize = 10;
var consultCode = "";
var patientcode = "";
var networkStatus = "";
var $ipt_content = $('#input_content');
var recordTimer = null;
var realStartTime = 0;
var aud = document.getElementById('audio');
var $playingDom;
var serverId = "";
var images = [];
var chooseType; //记录选择的咨询类型
//标记renew状态
var isRenew;
var participants = []; //记录参与者的信息
var recordCancel = false;
var recorder = null;
var audio_tips = document.getElementById("audio_tips");
var startTimestamp = null;
var stopTimestamp = null;
var stopTimer = null;
var MIN_SOUND_TIME = 500;
var expensesStatus="";//'扣费状态 【""没有签约信息 "0"未扣费 "1"已扣费 "2"已退费】'
var ui = {
body: document.querySelector('body'),
btnMsgType: document.querySelector('#msg-type'),
boxMsgText: document.querySelector('#msg-text'),
boxMsgSound: document.querySelector('#msg-sound'),
btnMsgImage: document.querySelector('#msg-image'),
areaMsgList: document.querySelector('#msg-list'),
boxSoundAlert: document.querySelector('#sound-alert')
};
var request = GetRequest();
patientcode = request.patientcode;
var patientName = "";
var consulting = {
//初始化页面
getInfo: function(){
d.show();
id = 1;
var reqList = [{
//判断当前是否有未结束的咨询
url:'/patient/consult/is_consult_unfinished',
reqType:'POST',
data:{doctor: request.doctor}
},{
//获得会话窗口的用户的头像等信息
url: '/patient/consult/participants',
reqType: 'POST',
data: {
sessionId: patientcode+"_"+request.doctor+"_1"
}
},{
//获得咨询记录
url: '/patient/consult/logs',
reqType: 'POST',
data: {
sessionId: patientcode+"_"+request.doctor+"_1",
startMsgId:"",
endMsgId: "",
page: id,
pagesize: pagesize
}
}];
isRenew = request.isRenew;
getReqPromises(reqList).then(function(res){
// if(isRenew == 1){
// d.close();
// $("#input_div").hide();
// $("#finish_list").hide();
// $(".xzzx").hide();
// winSize(125); //70+45
// }else{
doResponse(res);
// }
});
// var userAgent1 = JSON.parse(window.localStorage.getItem(agentName1));
// patientName = userAgent1.name;
},
bindEvents: bindConsultEvents
};
//请求回调处理
function doResponse(res){
var res1 = res[0],
res2 = res[1],
res3 = res[2];
if(res1.status == 200 && res2.status == 200 && res3.status == 200){
d.close();
loadSocket();
if(res1.data == ""){
//无正在进行中的咨询
$("#input_div").hide();
$("#finish_list").hide();
$(".xzzx").show();
winSize(125); //70+45
//-1患者已取消,-2已拒绝,-3已解约,-4已到期
switch(request.status){
case "-1":
case "-2":
case "-3":
case "-4":
$(".xzzx").hide();
winSize(45);
break;
}
}else if(res1.data){
//有正在咨询中的问卷
$("#input_div").show();
$("#finish_list").show();
$(".xzzx").hide();
consultCode = res1.data;
//提示谁进入咨询
var data = {
consult:consultCode
}
sendPost('patient/consult/intoTopic', data, "json", "post", null,function(res){})
winSize(167); //102+45
}
participants = res2.list;
var pulldownAction = function() {
getConsultLog();
};
dialroll = iscrollAssist.newVerScrollForPull($('.pull-iscroll-wrap'), pulldownAction, null);
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
querySuccess2(res3, false);
}else{
queryFailed2();
}
}
//加载socket组件
function loadSocket(){
jQuery.getScript(imurl+"/socket.io/socket.io.js").done(function() {
var socket = io.connect(imurl);
var sessionId = patientcode+"_"+request.doctor+"_1";
var userInfo = JSON.parse(window.localStorage.getItem(agentName));
socket.emit('login', {userId: userInfo.represented?userInfo.represented:userInfo.uid, password: userInfo.represented?userInfo.represented:userInfo.uid,sessionId:sessionId,clientType:"patient"});
socket.on('message', function (data) {
// console.log(data)
if((data.type == 1) ||(data.type == 2) || (data.type == 3) || (data.type == 6) || (data.type == 12)){
addReply(1, data.content, new Date(data.timestamp).Format('yyyy-MM-dd HH:mm:ss'), data.type, data.name, getImgUrl(data.sender_img));
// setTimeout(function(){
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
// },300)
}
});
socket.on('error', function (data) {
// console.log(data);
});
socket.on('ack', function (data) {
// console.log(data);
});
function getLocalTime(nS) {
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');
}
})
.fail(function() {
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:"医生实时对话连接失败!"}).show();
});
}
//获得咨询记录
function getConsultLog(){
var url = "/patient/consult/logs",
params = {
sessionId: patientcode+"_"+request.doctor+"_1",
startMsgId:"",
endMsgId: "",
page: id,
pagesize: pagesize
};
d.show();
sendPost(url, params, "json", "post", queryFailed2, function(res){
querySuccess2(res, true);
});
}
//控制“发送”按钮的变化
function sendBtn() {
var tval = $(".talk-input input").val();
if (tval != "") {
$(".talk-send a").removeClass("disab");
} else {
$(".talk-send a").addClass("disab");
}
}
//控制页面高度
function winSize(h) {
var totH = $(window).height();
$("#talkwrap").height(totH - h);
}
function queryMsg(logId,msgType){
var data={};
data.consult = consultCode;
data.logId = logId;
data.msgType=msgType;
sendPost('patient/consult/oneLog', data, 'json', 'GET', queryFailed2, function(res){
if(res.status==200){
var reply = res.consult;
if((reply.msgType == 1) || (reply.msgType == 2) || (reply.msgType == 6)){
addReply(reply.type, reply.content, reply.time, reply.msgType, reply.doctorName, reply.photo);
setTimeout(function(){
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
},300)
}
}
d.close();
});
}
function queryFailed2(res) {
d.close();
if (res && res.msg) {
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:res.msg}).show();
} else {
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:'加载失败'}).show();
}
}
function querySuccess2(res, prepend) {
if (res.status == 200) {
id++;
var list = res.list;
if (list && list.length > 0) {
for (var j = list.length-1; j >=0; j--) {
var reply = JSON.parse(list[j]);
//屏蔽全科医生求助专科医生的消息
if(reply.content_type != 5){
var date = new Date();
date.setTime(reply.timestamp);
var time = date.format('yyyy-MM-dd hh:mm:ss');
var p;
for(var k in participants){
if(participants[k].id==reply.sender_id)
p = participants[k].avatar;
}
var isSystem = reply.sender_id == 'system';
addReply(reply.sender_id==patientcode? 2 : 1, reply.content, time, reply.content_type, reply.sender_name, p, prepend, isSystem);
}
}
dialroll.refresh();
if(!prepend){
dialroll.scrollTo(0, dialroll.maxScrollY);
}
}else{
dialroll.refresh();
}
d.close();
}
else{
queryFailed2(res);
}
}
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
//点击发送按钮
function send(){
content = $("#input_content").text().replace(/\s+/g,"");
if (content && content != null && content != "") {
var now = new Date();
timeStr = "";
if(now.getMonth()<9){
//补0
timeStr = now.getFullYear() + "-0"+ (now.getMonth()+1) + "-" +now.getDate() +' '
+ now.getHours() + ":" +now.getMinutes() + ":" +now.getSeconds();
}else{
timeStr = now.getFullYear() + "-"+ (now.getMonth()+1) + "-" +now.getDate() +' '
+ now.getHours() + ":" +now.getMinutes() + ":" +now.getSeconds();
}
$("#input_content").blur();
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
dd.showModal();
var data = {};
data.consult = consultCode;
data.content = utf16toEntities(content);
data.type = 1;
sendPost('patient/consult/append', data, 'json', 'post', submitFailed, submitSuccess);
} else {
return;
}
}
function submitFailed(res) {
dd.close();
if (res && res.msg) {
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:res.msg}).show();
} else {
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:'发送失败'}).show();
}
}
function submitSuccess(res) {
if (res.status == 200) {
//置空
$("#input_content").text("");
$(".talk-send a").addClass("disab");
addReply(2, content, timeStr, 1, "");
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
showSendBtn(false);
dd.close();
} else {
submitFailed(res);
}
}
//回复单条内容填写
var defaultPhoto = "../../../images/p-default.png";
var doctorDefaultPhoto = "../../../images/d-default.png";
function addReply(isDoctor, content, time, msgType, sender_name,photo,prepend, isSystem) {
//time = time.substr(10);
var doctorPhoto = photo ? getImgUrl(photo) : doctorDefaultPhoto;
var $div = $("
");
if(msgType == 7 || msgType == 10 || msgType == 13 ||msgType == 14){
if(msgType == 7 && isSystem){
content = "您24小时内未回复,系统自动结束咨询";
}
if(prepend){
$(".talk-box").prepend('' + content + '
');
} else
$(".talk-box").append('' + content + '
');
return;
}
if (isDoctor == 1) {
$div.addClass('chat-left');
img = doctorPhoto;
} else {
$div.addClass('chat-right');
img = photo? getImgUrl(photo):defaultPhoto;
defaultPhoto = img;
}
name = sender_name;
var temp = '' +
'' + name + ''
switch(parseInt(msgType)) {
case 0: //签约信息
case 1://信息
case 6://咨询问题
temp += '
' + content + '';
if(isDoctor == 1){
temp += '仅供参考
';
}else{
temp += '';
}
break;
case 2://图片
// alert(content);
temp += '
';
//医生回复的内容底部加上“仅供参考”的字样
if(isDoctor == 1){
temp += '仅供参考
';
}else{
temp += '';
}
break;
case 3://语音
var rec = JSON.parse(content);
temp += "
"+
"" +
""+(rec? rec.times: "") +"\'\'"+
"
";
//医生回复的内容底部加上“仅供参考”的字样
if(isDoctor == 1){
temp += '仅供参考
';
}else{
temp += "
";
}
break;
case 4: //文章
temp += formatJyzd(content, "","", time);
// temp += '' + matchUrl(contentMsg) + '';
break;
case 12://视频
var videoInfo = content.split(",");
var shichang = formatSeconds(videoInfo[2]);//时长
if(isDoctor == 1){
temp += ''+
''+
''+
''+
''+shichang+''+
'仅供参考
'+
'';
}else{
temp += ''+
''+
''+
''+
''+shichang+''+
'';
}
break;
}
if(prepend){
$(".talk-box").prepend($div.append(temp)).prepend('' + time + '
');
} else{
$(".talk-box").append('' + time + '
').append($div.append(temp));
}
if(isDoctor != null && isDoctor != 1) {
$(".tw-add-detail").hide(200);
}
}
function formatJyzd(msg, sendErrDom,yiduHtml, time){
// {"title":"2016年春节放假调休门诊安排通知","id":"ff1b39cfdf6a482c958140ba768474cc","img":"http://f1.yihuimg.com/TFS/upfile/WBJ/111/2016-02-05/160294_1454633481085_fullsize.png","content":"为了您的健康,我给您发送了一篇文章,请咨询查阅,如有问题,可随时与我沟通"}
if(msg){
//针对\n,\r等特殊字符,在json转换时会报错
msg = msg.replace(/\n/g, "\\n");
msg = msg.replace(/\r/g, "\\r");
msg = JSON.parse(msg);
// msg.img = msg.type==1? "../../../images/jkjl_share.png" : msg.img;
if(msg.type == 1){ //健康记录
msg.img = "../../../images/jkjl_share.png";
}else if(msg.type == 2){ //健康指导
var img = msg.img.split(",");
if(img[0] && img[0] != "null"){
msg.img = getImgUrl(img[0]);
}else{
msg.img = "../../../images/default_share_blue.png";
}
}else{ //健康教育
msg.img = getImgUrl(msg.img);
if(!msg.img){
msg.img = "../../../images/default_share_blue.png";
}
}
var temp =
''+'
'
// + yiduHtml
+ ''+ msg.title +'
'
+ ''
+ '
'+ msg.content+'
'
+ '
'
+ ' ';
return temp;
}
return "";
}
//毫秒转换成时分秒
function formatSeconds(value) {
var theTime = parseInt(value/1000);// 秒
var theTime1 = 0;// 分
var theTime2 = 0;// 小时
if(theTime > 60) {
theTime1 = parseInt(theTime/60);
theTime = parseInt(theTime%60);
if(theTime1 > 60) {
theTime2 = parseInt(theTime1/60);
theTime1 = parseInt(theTime1%60);
}
}
var result = ""+parseInt(theTime);//秒
if(parseInt(theTime)<=9){
result = "0"+parseInt(theTime);//秒
}
if(theTime1 > 0) {//分
if(parseInt(theTime1)>9){
result = ""+parseInt(theTime1)+":"+result;
}else{
result = "0"+parseInt(theTime1)+":"+result;
}
}
if(theTime2 > 0) {//小时
if(parseInt(theTime2)>9){
result = ""+parseInt(theTime2)+":"+result;
}else{
result = "0"+parseInt(theTime2)+":"+result;
}
}
var resResult = "";
if(result.split(":").length==1){//秒
resResult = "00:"+result;
}else if(result.split(":").length==2){//分
resResult = "00:"+result;
}else{//时
resResult = result;
}
return resResult;
}
//向上拉取更多
function addReplyBefore(type, content, time, msgType, doctorName) {
//time = time.substr(10);
var doctorPhoto = doctorDefaultPhoto;
var patientPhoto = defaultPhoto;
var $div = $("");
if (type == 1) {
if(msgType == 2){
$div.addClass('talk-left');
$div.addClass('clearfix');
$div.html(''+ doctorName + '
'
+'' + time+''
+''
+'
'
+'
');
}
else{
$div.addClass('talk-left');
$div.addClass('clearfix');
$div.html(''+ doctorName + '
'
+'' + time+''
+''
+' '+content
+'
');
}
} else {
if(msgType == 2){
$div.addClass('talk-right');
$div.addClass('clearfix');
$div.html(' '
+''+time+''
+''
+'
'
+'
');
}
else{
$div.addClass('talk-right');
$div.addClass('clearfix');
$div.html (''
+ '' + time + ''
+ '' + content + '
');
}
}
$(".talk-box").prepend($div);
}
//结束咨询
function finish(){
dialog({
content:'是否确认结束该次咨询?结束后医生将无法回复',
ok: function (){
d.show();
var params = {}
params.code = consultCode;
//发送ajax请求, 查询设备列表信息
sendPost("patient/consult/finish", params, "json", "post", submitFailed3,finish_Successs);
function finish_Successs(res){
if (res.status == 200) {
d.close();
localStorage.setItem("evaluate",0);//标志未评价
location.reload();
}
else{
submitFailed3(res);
}
}
},
cancel: function () {
return;
}
}).showModal();
}
function submitFailed3(res) {
if (res && res.msg) {
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:res.msg}).show();
} else {
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:'操作失败'}).show();
}
}
//查看图片
function viewImg(dom) {
var $img = $(dom);
var thissrc = $img.attr("src");
var mWid = $(window).width();
var mHei = $(window).height();
var nHtml = '';
$("body").append(nHtml);
$(".delimgpop").click(function() {
$(this).remove()
});
}
//微信上传图片
function chooseImageWx(){
// dd.showModal();
wx.chooseImage({
count: 1, //限制一次只能上传一张图片
success: function (res) {
for (var i in res.localIds) {
images.push(res.localIds[i]);
}
uploadImage();
}
});
}
function uploadImage(){
dd.showModal();
if (images.length == 0) {
dd.close();
return;
}
var i = 0, length = images.length;
serverId = "";
var faillength = 0 ;
function upload() {
wx.uploadImage({
localId: images[i],
isShowProgressTips: 0,
success: function (res) {
faillength= 0;
// dd.close();
i++;
if(serverId.length == 0){
serverId = res.serverId;
}
else{
serverId =serverId + "," + res.serverId;
}
if (i < length) {
upload();
}
if(i == images.length){
sendImages();
}
},
fail: function (res) {
dd.close();
faillength+=1;
if(faillength<=5){
//失败从传
upload();
}else{
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:"图片上传失败,请控制发送频率"}).show();
}
}
});
}
upload();
}
//保存图片
function sendImages(){
var now = new Date();
//清空images
images = [];
timeStr = "";
if(now.getMonth()<9){
//补0
timeStr = now.getFullYear() + "-0"+ (now.getMonth()+1) + "-" +now.getDate() +' '
+ now.getHours() + ":" +now.getMinutes() + ":" +now.getSeconds();
}else{
timeStr = now.getFullYear() + "-"+ (now.getMonth()+1) + "-" +now.getDate() +' '
+ now.getHours() + ":" +now.getMinutes() + ":" +now.getSeconds();
}
var data = {};
data.consult = consultCode;
data.content = "";
data.mediaIds = serverId;
data.type = 2;
data.times = 0;
// dd.showModal();
sendPost('patient/consult/append', data, 'json', 'post', submitFailed, submitImageSuccess);
}
function submitImageSuccess(res) {
if (res.status == 200) {
var data= JSON.parse(res.data)
dd.close();
addReply(2, data.content, timeStr, 2, "");
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
} else {
submitFailed(res);
}
}
//function wslogin() {
// var userid = patientcode;
// var ws;
// if (typeof MozWebSocket != "undefined") {
// ws = new MozWebSocket(wsurl, 'netex');
// } else {
// ws = new WebSocket(wsurl, 'netex');
// }
//
// function onopen() {
// var reg = {};
// reg.id = 'reg';
// reg.uid = userid;
// reg.pwd = '';
// ws.send(JSON.stringify(reg));
// }
//
// function onclose() {
// // 断链重连
// if (typeof MozWebSocket != "undefined") {
// ws = new MozWebSocket(wsurl, 'netex');
// } else {
// ws = new WebSocket(wsurl, 'netex');
// }
// }
// function onmessage(msg) {
// var result = eval("("+msg.data+")");
// if(result.msgid){
// queryMsg(result.msgid,result.msgType);
// }
// }
// ws.onopen = onopen;
// ws.onmessage = onmessage;
// ws.onclose = onclose;
// }
function playSoundEnd(){
$playingDom.removeClass('active');
$playingDom = null;
}
function playError(){
var src = $('#audio').attr('src');
if(!$.trim(src)) {
return ;
}
dialog({contentType:'tipsbox', skin:'bk-popup' ,bottom:true, content:"播放语音失败"}).show();
$playingDom.removeClass('active');
$playingDom = null;
}
function showSendBtn(isShow){
if(isShow){
$('.tw-add').hide();
$('#reply').fadeIn('fast', 'swing');
} else {
$('#reply').fadeOut('fast', 'swing', function(){
$('.tw-add').show();
});
}
}
function setSoundAlertVisable(show){
if(show){
ui.boxSoundAlert.style.display = 'block';
ui.boxSoundAlert.style.opacity = 1;
}else{
ui.boxSoundAlert.style.opacity = 0;
//fadeOut 完成再真正隐藏
setTimeout(function(){
ui.boxSoundAlert.style.display = 'none';
},200);
}
};
function recordErr(res){
if(res && res.errMsg == "stopRecord:tooshort") {
audio_tips.innerHTML = "录音时间太短";
ui.boxSoundAlert.classList.add('rprogress-sigh');
recordCancel = true;
stopTimer=setTimeout(function(){
setSoundAlertVisable(false);
},500);
startTimestamp = 0;
//小于300ms,不录音
if(recordTimer)clearTimeout(recordTimer);
return;
}
if(!recordCancel){
dialog({
content:'录音失败,请重试',
okValue:'我知道了',
ok: function() {}
}).showModal();
}
}
//保存图片
function sendSounds(times){
var now = new Date();
timeStr = "";
if(now.getMonth()<9){
//补0
timeStr = now.getFullYear() + "-0"+ (now.getMonth()+1) + "-" +now.getDate() +' '
+ now.getHours() + ":" +now.getMinutes() + ":" +now.getSeconds();
}else{
timeStr = now.getFullYear() + "-"+ (now.getMonth()+1) + "-" +now.getDate() +' '
+ now.getHours() + ":" +now.getMinutes() + ":" +now.getSeconds();
}
var data = {};
data.consult = consultCode;
data.content = "";
data.type = 3;
data.times = times;
wx.uploadVoice({
localId: serverId,
success: function (res) {
data.voices = res.serverId;
dd.showModal();
sendPost('patient/consult/append', data, 'json', 'post', submitFailed,
function submitSoundSuccess(res) {
if (res.status == 200) {
dd.close();
var data = JSON.parse(res.data[0]);
addReply(2, data.content, timeStr, 3, "");
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
} else {
submitFailed(res);
}
});
}
});
}
function bindConsultEvents(){
//录制视频
/*$(".lz-video-img").click(function(){
$("#upload_input").click();
//dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'请录制10秒左右的短视频,以防录制完成后无法发送'}).show();
return false;
})*/
//点击内容区域输入框失焦
$('#talkwrap').click(function(){
$("#input_content").blur();
// dialroll.refresh();
// dialroll.scrollTo(0, dialroll.maxScrollY);
return false;
});
//发送以后定位至最底部
$("#reply a").click(function() {
send();
});
//立即发送
$("#lijifasong").on("tap", function(){
uploadVideo();
mui('#sheet1').popover('toggle');
return false;
});
//不再提醒
$("#buzaitixing").on("tap", function(){
window.localStorage.setItem("isTiXingVideoFaSong","1");
uploadVideo();
mui('#sheet1').popover('toggle');
return false;
});
// window.localStorage.removeItem("isTiXingVideoFaSong");//测试
$('.talk-box').on('click', '.word-bread img', function(){
var src = $(this).attr('src')
$(this).attr('src',src+'?'+$.now())
if(!$(this).closest(".word-bread").hasClass("preview-video")){
var urls = [];
$.each($('.word-bread img'), function(i, v) {
urls.push($(v).attr('src'));
});
wx.previewImage({
current: $(this).attr('src'), // 当前显示图片的http链接
urls: urls // 需要预览的图片http链接列表
});
}
})
.on('touchstart', '.audio', function(){
if($playingDom){
aud.pause();
//aud.stop();
$playingDom.removeClass('active');
if($playingDom[0] == this){
$playingDom = null;
return;
}
}
$playingDom = $(this);
$playingDom.addClass('active');
var ser = JSON.parse($(this).attr('data-audio'));
aud.src = getImgUrl(ser.path);
aud.load();
aud.play();
})
.on('click','.preview-video',function() {
$(document.body).find('video').remove();
var url = $(this).attr('data-video');
var html = '';
$(document.body).append(html);
var video = $(document.body).find('video')[0];
video.play();
});
//键盘输入解决输入框被软键盘覆盖的问题
var bfscrolltop = document.body.scrollTop;//获取软键盘唤起前浏览器滚动部分的高度
var interval;
$ipt_content.focus(function(){//当它获取焦点时触发事件
$(".tw-add-detail").hide();
interval = setInterval(function(){//设置一个计时器,时间设置与软键盘弹出所需时间相近
document.body.scrollTop = document.body.scrollHeight;//获取焦点后将浏览器内所有内容高度赋给浏览器滚动部分高度
},100)
}).blur(function(){//设定输入框失去焦点时的事件
clearInterval(interval);//清除计时器
document.body.scrollTop = bfscrolltop; //将软键盘唤起前的浏览器滚动部分高度重新赋给改变后的高度
});
/**
* 显示发送按钮的事件
*/
$ipt_content.on('input', function(e){
if($(this).prop('comstart')) {
//console.log("true");
return;
}
var text = $.trim($(this).text());
showSendBtn(text.length > 0)
}).on('compositionstart', function(){
$(this).prop('comstart', true);
//console.log('中文输入:开始');
}).on('compositionend', function(){
$(this).prop('comstart', false);
// console.log('中文输入:结束');
var text = $.trim($(this).text());
showSendBtn(text.length > 0)
})
.on('tap', function(){
$(".tw-add-detail").hide();
// $ipt_content.focus();
//mui.later(scrollToEnd, 300);
})
/*
* 附加功能
*/
$(".tw-add").click(function() {
$(".tw-add-detail").toggle(200);
});
$('body')
//隐藏打开的附加功能
.on('tap', '#talkwrap', function(){
$('.tw-add-detail').hide();
$ipt_content.blur();
})
$(".yy-add").click(function() {
if($('#msg-sound:visible').length){
$ipt_content.show();
ui.boxMsgSound.style.display = 'none';
$(this).find('img:eq(0)').show().next().hide();
} else {
$ipt_content.hide();
ui.boxMsgSound.style.display = 'block';
$(this).find('img:eq(0)').hide().next().show();
}
});
$("body").on('tap', '.word-article', function(){
var type = $(this).attr('data-inner-type');
var code = $(this).attr('data-code');
if(type == 2){
window.location.href = "../../yszd/html/guidance-detail.html?id="+code;
} else{
//根据时间判断该文章是旧的文章还是改造后发送的文章,时间是:2017-12-29 00:00:00
var sendTimeStr = $(this).attr("Data-code"),
sendTime = new Date(sendTimeStr),
cDate = new Date("2017-12-29 00:00:00");
if(sendTime < cDate){
window.location.href = "../../jkjy/html/article.html?dataId="+code;
}else{
window.location.href = "../../jkjy/html/article2.html?dataId="+code;
}
}
});
$(".xzzx").on('tap', function(){
//获取患者信息 判断该患者是否已经缴费 若缴费则正常咨询 未缴费提示咨询次数信息
// getPatientInfo();
checkDocInWork();
})
ui.boxMsgSound.addEventListener("touchstart", function(e) {
e.preventDefault();
event.preventDefault();
$(this).addClass('yy-hold');
if(stopTimer)clearTimeout(stopTimer);
recordCancel = false;
audio_tips.innerHTML = "手指上划,取消发送";
ui.boxSoundAlert.classList.remove('rprogress-sigh');
setSoundAlertVisable(true);
startTimestamp = new Date().getTime();
recordTimer = setTimeout(function(){
wx.startRecord({
success: function(){
realStartTime = new Date().getTime();
},
fail: recordErr
});
wx.onVoiceRecordEnd({
// 录音时间超过一分钟没有停止的时候会执行 complete 回调
complete: function (res) {
serverId = res.localId;
sendSounds(60);
},
fail: recordErr
});
},MIN_SOUND_TIME);
}, false);
ui.boxMsgSound.addEventListener("touchend", function(e){
e.preventDefault();
event.preventDefault();
$(this).removeClass('yy-hold');
if (audio_tips.classList.contains("cancel")) {
audio_tips.classList.remove("cancel");
audio_tips.innerHTML = "手指上划,取消发送";
}
var endTimestamp = new Date().getTime();
var times = endTimestamp - startTimestamp;
var realTimes = endTimestamp - realStartTime;
if(times < MIN_SOUND_TIME || realTimes < MIN_SOUND_TIME){
audio_tips.innerHTML = "录音时间太短";
ui.boxSoundAlert.classList.add('rprogress-sigh');
recordCancel = true;
stopTimer=setTimeout(function(){
setSoundAlertVisable(false);
},500);
startTimestamp = 0;
realStartTime = 0;
//小于300ms,不录音
clearTimeout(recordTimer);
wx.stopRecord({
success: function (res) {
},
fail: function(){}
});
}else{
setSoundAlertVisable(false);
wx.stopRecord({
success: function (res) {
if(!recordCancel) {
serverId = res.localId;
sendSounds(Math.round(times/1000));
}
},
fail: recordErr
});
}
}, false)
ui.body.addEventListener('drag', function(event) {
if (Math.abs(event.detail.deltaY) > 50) {
if (!recordCancel) {
recordCancel = true;
if (!audio_tips.classList.contains("cancel")) {
audio_tips.classList.add("cancel");
}
audio_tips.innerHTML = "松开手指,取消发送";
}
} else {
if (recordCancel) {
recordCancel = false;
if (audio_tips.classList.contains("cancel")) {
audio_tips.classList.remove("cancel");
}
audio_tips.innerHTML = "手指上划,取消发送";
}
}
}, false);
}
//录制视频回调
function videoFileChange(target) {
var fileSize = (target.files[0].size/1024/1024).toFixed(2);//字节转换成M
if(parseInt(fileSize)>30){
dialog({
content:'对不起,视频超过30Mb,无法发送,请录制10秒左右的短视频',
okValue:'我知道了',
ok: function() {
return;
}
}).showModal();
}else{
if(networkStatus=="wifi" || window.localStorage.getItem("isTiXingVideoFaSong")=="1"){//wifi环境或用户点击移动网络弹框中的”不再提醒“按钮
uploadVideo();
}else{
$("#mui-content").html('您正在使用移动网络,继续发送将消耗'+fileSize+'Mb流量,是否继续发送?');
mui('#sheet1').popover('toggle');
}
}
}
//上传视频
function uploadVideo(){
dd.showModal();
var fd=new FormData();
fd.append('file',document.getElementById("upload_input").files[0]);
$.ajax(server+"/upload/chat?type=4", {
data: fd,
contentType: false,
cache: false,
processData: false,
type: 'post',
success: function(resData) {
if(resData.status==200){
var data = {consult:consultCode,content:resData.urls,type:12};
sendPost('patient/consult/append', data, 'json', 'post', submitFailed,
function submitSoundSuccess(res) {
if (res.status == 200) {
dd.close();
var data = JSON.parse(res.data[0]);
addReply(2, data.content, new Date(data.timestamp).Format('yyyy-MM-dd HH:mm:ss'), 12, "");
dialroll.refresh();
dialroll.scrollTo(0, dialroll.maxScrollY);
} else {
submitFailed(res);
}
});
}else{
dd.close();
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.readyState);
console.log(textStatus)
}
});
}
Date.prototype.format = function(fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
//未缴费居民限制咨询次数
function limitZxTimes(){
//获取剩余家庭咨询次数
var url = '/patient/consult/remainConsultTimes';
var remainTimes;//剩余咨询次数
var countTimes;//总咨询次数
var zxTimes;//已咨询次数
d.show();
sendPost(url, {}, 'json', 'get', queryFailed, function(res){
if(res.status == 200){
d.close();
remainTimes = res.data.amount;
countTimes = res.data.count;
zxTimes = countTimes - remainTimes;
if(zxTimes == countTimes){
//未缴费的总咨询次数已达上限 提示去缴费
dialog({
content: '您本年度家庭医生签约暂未缴费,当前10次免费健康咨询已全部使用.如果需要家庭医生继续为您提供服务,请尽快完成缴费操作',
okValue:'前往缴费',
ok: function (){
window.location.href = "signing_management.html";
}
}).showModal();
}else{
dialog({
content: '您本年度家庭医生签约暂未缴费,可使用10次免费健康咨询,当前剩余:'+remainTimes+'次.为避免影响您的服务体验,请尽快完成缴费操作',
okValue:'前往缴费',
ok: function (){
window.location.href = "signing_management.html";
},
cancelValue: '开始咨询',
cancel: function () {
querySignType(2)
}
}).showModal();
}
}else{
queryFailed(res);
}
});
}
//查询签约类型
function querySignType(type){
chooseType = type;
d.show();
sendPost('patient/sign_doctors', {}, 'json', 'post', function(res){
queryFailed(res, '获取咨询类型失败');
}, querySignTypeSuccess);
}
//查询签约类型成功回调处理事件
function querySignTypeSuccess(res){
if (res.status == 200) {
d.close();
var doctors = "";
switch(Number(chooseType)) {
case 1: doctors = res.teamDoctors; break;
case 2: doctors = res.familyDoctors; break;
default: break;
}
var docInfo,docQkInfo;
$.each(doctors, function(i, v) {
if(v.teamlevel){
if(v.teamlevel == 3){
docInfo = v;
}
if(v.teamlevel == 2){
docQkInfo = v;
}
}else{
if(v.level == 3){
docInfo = v;
}
if(v.level == 2){
docQkInfo = v;
}
}
});
if(!docInfo){
docInfo = docQkInfo;
}
checkDocInWork(chooseType, docInfo,docQkInfo)
}else {
queryFailed(res);
}
}
//获取签约医生的工作时间
function checkDocInWork(type, doctor,docQkInfo){
var url = 'patient/consult/isDoctorWorkWhenconsult',
params = {doctor: request.doctor};
sendPost(url, params, 'json', 'post', queryFailed, function(res){
if(res.status == 200){
// data:0-医生不接受咨询/1-医生当前接受咨询/2-全科医生和健管师当前都不在工作时间/3-全科医生当前不在工作时间/4-健管师当前不在工作时间 健管师当前不在工作时间
if(!(res.data == "1")){
dialog({
content: '您好,由于您关注的医生工作繁忙,设置了每日回复咨询的时间段,所以,在该时间段外的时间,您的咨询将不会马上获得医生的回复。',
okValue:'查看医生工作时间',
ok: function (){
window.location.href = "../../yszx/html/doctor-work-hours.html?doctor=" + request.doctor;
},
cancelValue: '继续新增咨询',
cancel: function () {
window.location.href = "../../yszx/html/add-consult.html?doctorCode="+request.doctor;
}
}).showModal();
}else{
//跳转到新增咨询页面
window.location.href = "../../yszx/html/add-consult.html?doctorCode=" + request.doctor;
}
}else{
queryFailed(res);
}
});
}
//获得患者信息判断用户是否已缴费
function getPatientInfo(){
d.show();
sendPost('patient/baseinfo', {}, 'json', 'post', queryFailed, function(res){
if (res.status == 200) {
expensesStatus = res.data.expensesStatus;
if(expensesStatus == 1){
//如果已经缴费 先判断医生是否在工作空间 若在泽可咨询 若不在则进行相关提示
querySignType(2);
}else{
//咨询问题的居民未缴费
limitZxTimes();
}
} else {
queryFailed(res);
}
});
}
//请求失败处理事件
function queryFailed(res, message){
d.close();
if(message){
dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content: message}).show();
}else{
if (res && res.msg) {
dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:res.msg}).show();
} else {
dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'加载失败'}).show();
}
}
}