chatRoom.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  1. var winHeight=window.innerHeight;//窗体高度
  2. var winWidth=window.innerWidth;//窗体高度
  3. var self;
  4. var docInfo;
  5. var teamInfo;
  6. var members; //{"37906b9986f211e6b394fa163e424525": {"jobName":"","code":"37906b9986f211e6b394fa163e424525","level":0,"sex":2,"name":"叶亚娟","photo":"","id":3317,"hospital":"3502120800"}}
  7. var pageSize = 10;
  8. var myScroll;
  9. var chatCache = {};
  10. var firstMsg;
  11. var offTop = 16, offBot = 52;
  12. var winHei;
  13. var otherCode, isPatient;
  14. var observer = false;
  15. var imMsg = '';
  16. var isSend = true;
  17. var andriodVideoUrl = "";//andriod录像文件地址
  18. var urlRegex = new RegExp('((https|http|ftp|rtsp|mms)?://)'
  19. + '?(([0-9a-zA-Z_!~*\'().&=+$%-]+: )?[0-9a-zA-Z_!~*\'().&=+$%-]+@)?' //ftp的user@
  20. + '(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184
  21. + '|' // 允许IP和DOMAIN(域名)
  22. + '([0-9a-zA-Z_!~*\'()-]+\\.)*' // 域名- www.
  23. + '([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\\.' // 二级域名
  24. + '(gov|edu|int|com|cn|cx|cn|wang|cc|xin|net|org|top|tech|red|pub|ink|info|xyz|win))' // first level domain- .com or .museum
  25. + '(:[0-9]{1,4})?' // 端口- :80
  26. + '((/[0-9a-zA-Z_!~*\'().;?:@&=+$,%#-]+)+/?)?'
  27. + '((\\?[0-9a-zA-Z_!~*\'().;:@&=+$,%#-]+)+/?)?');
  28. mui.init({
  29. gestureConfig:{
  30. doubletap: true,
  31. longtap: true,
  32. hold: true,
  33. release: true
  34. }
  35. });
  36. var UIPasteboard;
  37. var AndroidClip;
  38. var AndroidContext;
  39. var AndroidMain;
  40. //开启websql数据库
  41. sqlite.open('MyData','1.0','My Database', 128);
  42. var networkStatus = "";//当前网络状态
  43. mui.plusReady(function(){
  44. self = plus.webview.currentWebview();
  45. var opener = self.opener();
  46. if(opener && (opener.id=="jumingim.html" || opener.id=="yishengim.html")){
  47. mui.fire(self.opener(), "xiaoxiUpdate");
  48. }
  49. winHei = $('body').height();
  50. self.setStyle({
  51. softinputMode: "adjustResize"
  52. });
  53. if(plus.os.name == "Android"){
  54. $(".andriod-video-li").show();
  55. AndroidContext = plus.android.importClass("android.content.Context");
  56. AndroidMain = plus.android.runtimeMainActivity();
  57. AndroidClip = AndroidMain.getSystemService(AndroidContext.CLIPBOARD_SERVICE);
  58. } else{
  59. $(".ios-video-li").show();
  60. UIPasteboard = plus.ios.importClass("UIPasteboard");
  61. }
  62. //观察者模式隐藏输入框
  63. // var userAgent = JSON.parse(plus.storage.getItem("userAgent"));
  64. // if(userAgent.observer == "1"){
  65. // observer = true;
  66. // $("#input_div").hide();
  67. // $('#wrapper1').css({top:'16px', bottom: '0px'});//也不能发送指导和教育
  68. // }
  69. document.addEventListener("netchange",onNetChange,false);
  70. onNetChange();
  71. bindEvents();
  72. })
  73. function onNetChange(){
  74.   var nt = plus.networkinfo.getCurrentType();
  75.   switch(nt){
  76.     case plus.networkinfo.CONNECTION_ETHERNET:
  77.     case plus.networkinfo.CONNECTION_WIFI:
  78.       networkStatus = "wifi";
  79.       break;
  80.     case plus.networkinfo.CONNECTION_CELL2G:
  81. networkStatus = "2g";
  82. break;
  83.      case plus.networkinfo.CONNECTION_CELL3G:
  84. networkStatus = "3g";
  85. break;
  86.     case plus.networkinfo.CONNECTION_CELL4G:
  87. networkStatus = "4g";
  88. break;
  89.     default:
  90.       mui.toast("当前没有网络");
  91.       break;
  92.   }
  93. }
  94. /**
  95. * 获取成员信息
  96. */
  97. function getMembers(callBack){
  98. // if(members) {
  99. // callBack? callBack() : getNewMsgs(true);
  100. // } else {
  101. console.log(sessionId)
  102. imClient.Sessions.getParticipants(sessionId, function(rs){
  103. members = {};
  104. var patientCode;
  105. $.each( rs , function(i, v) {
  106. if(v.id!=docInfo.code)
  107. otherCode = v.id;
  108. if(v.is_patient==1){
  109. isPatient = true;
  110. patientCode = v.id;
  111. }
  112. members[v.id] = {
  113. code: v.id,
  114. name: v.name,
  115. sex: v.sex,
  116. photo: v.avatar,
  117. role: v.role,
  118. is_patient: v.is_patient,//0 医生,1 患者
  119. last_fetch_time:v.last_fetch_time
  120. };
  121. });
  122. otherCode = patientCode||otherCode;
  123. callBack? callBack() : getFirstMsgs();
  124. // getNewMsgs(true); //读取对话消息,
  125. }, function(msg){
  126. console.log("e:"+JSON.stringify(msg))
  127. mui.toast("获取成员列表失败!");
  128. })
  129. // }
  130. }
  131. /*
  132. * 医生缓存信息 姓名和头像
  133. */
  134. function getMineInfo(){
  135. myScroll = $('#contain').lscroll({
  136. type: 2, pullDownMsg1: "下拉加载更多", pullDownMsg2: "松手开始加载",
  137. pullDownAction: function(g){
  138. getMsgList(g.options.page, false, true);
  139. }, style: "top: "+ offTop +"px; bottom: "+ offBot +"px"});
  140. var infoStr = plus.storage.getItem("docInfo");
  141. if(infoStr) {
  142. docInfo = JSON.parse(infoStr);
  143. console.log(docInfo.code)
  144. docName = docInfo.name;
  145. docPhoto = docInfo.photo || (docInfo.sex==1 ? "../../../images/d-male.png" : "../../../images/d-female.png");
  146. }
  147. }
  148. function getUserId(){
  149. return docInfo.code;
  150. }
  151. /*
  152. * 回复消息
  153. */
  154. function clickReply() {
  155. var text = $("#input_content").text().trim();
  156. // $("#input_content").focus()
  157. if(text.length == 0) {
  158. mui.toast("发送内容不能为空,请重新输入");
  159. return;
  160. }
  161. $("#input_content").text("");
  162. isSend = false;
  163. showSendBtn(false);
  164. uploadMsg(1, text);
  165. }
  166. /**
  167. * 插入预浏览图片
  168. * @param {Object} imgs
  169. */
  170. function appendPrevImgs(imgs){
  171. if(imgs){
  172. var html = "";
  173. $.each(imgs, function(i, v) {
  174. html += '<img class="l-previmg" style="display: none;" data-code="'+ v.id +'" data-preview-src="'+ v.content +'" data-preview-group="1">';
  175. });
  176. $('body').prepend(html);
  177. }
  178. }
  179. /**
  180. * 获取未读消息成功处理(初始化获取消息)
  181. * @param {Object} data
  182. */
  183. function getNewMsgHandle(data, isInit) {
  184. // debugger
  185. console.log("newdata:" + JSON.stringify(data));
  186. if(!isInit){
  187. // addMsgToCache(data, true);
  188. showMsg(data, false, false, true);
  189. // refreshBadge();
  190. }else {
  191. var len = data.length;
  192. if(len == 0){
  193. // if(isCached){
  194. // //取缓存数据,并展示信息
  195. // getCacheMsg(undefined, pageSize, function(tx, rs){
  196. // showMsg(rs, false, false, true);
  197. // });
  198. // } else {
  199. //从服务端加载数据, 并插入缓存, 展示信息
  200. getMsgs(1, pageSize, "", "", function(res){
  201. showMsg(res, false, false, true);
  202. // addMsgToCache(res, true);
  203. });
  204. // }
  205. } else {
  206. if(len < pageSize) {
  207. // if(isCached){
  208. // addMsgToCache(data, true);
  209. // //从缓存中取剩余数据
  210. // getCacheMsg(undefined, pageSize-len, function(tx, rs){
  211. // rs = rs.concat(data);
  212. // showMsg(rs, false, false, true);
  213. // })
  214. // } else {
  215. //从服务端加载剩余数据
  216. getMsgs( 1, pageSize-len, "", data[0].id,
  217. function(res){
  218. data = data.concat(res);
  219. showMsg(data, false, false, true);
  220. // addMsgToCache(data, true);
  221. } , null, 1);
  222. // }
  223. } else {
  224. //将消息插入缓存, 并展示信息
  225. // addMsgToCache(data, true);
  226. showMsg(data, false, false, true);
  227. }
  228. // refreshBadge();
  229. }
  230. }
  231. }
  232. /**
  233. * 定位聊天记录位置
  234. * @param {Object} id
  235. */
  236. function locationLog(id){
  237. var $logdom = $('.chat-log[data-code="'+ id +'"]');
  238. if($logdom.length){
  239. myScroll.scrollToElement( $logdom[0], 0, 0, -20 );
  240. plus.nativeUI.closeWaiting();
  241. } else {
  242. getCacheMsgById(id, function(tx, data){
  243. if(data.length>0){
  244. getCacheMsg("", "", function(tx, ls){
  245. showMsg(ls, false, true, false, true);
  246. }, data[0].timestamp, true )
  247. } else {
  248. getLastCacheMsg(function(tx, msg){
  249. var startmsg = msg.length>0? msg[msg.length-1] : undefined;
  250. getMsgs(1, 1000, startmsg? startmsg.id : "", id, function(ls){
  251. if(ls.length>0 && (!firstMsg || (firstMsg.timestamp<ls[0].timestamp) ))
  252. firstMsg = ls[0];
  253. // addMsgToCache(ls);
  254. showMsg(msg.concat(ls), false, true, false, true);
  255. }, function(res){
  256. console.error("e:"+JSON.stringify(res))
  257. })
  258. }, lastTimestamp);
  259. }
  260. })
  261. }
  262. }
  263. /**
  264. * 定位图片位置
  265. * @param {Object} id
  266. */
  267. function locationImg(id){
  268. var $logdom = $('.chat-log[data-code="'+ id +'"]');
  269. if($logdom.length){
  270. myScroll.scrollToElement( $logdom[0], 0, 0, -20 );
  271. plus.nativeUI.closeWaiting();
  272. } else {
  273. getCacheMsgById(id, function(tx, data){
  274. if(data.length>0){
  275. getCacheMsg("", "", function(tx, ls){
  276. showMsg(ls, false, true, false, true);
  277. }, data[0].timestamp, true )
  278. } else {
  279. getLastCacheMsg(function(tx, msg){
  280. var startmsg = msg.length>0? msg[msg.length-1] : undefined;
  281. getMsgs(1, 1000, startmsg? startmsg.id : "", id, function(ls){
  282. if(ls.length>0 && (!firstMsg || (firstMsg.timestamp<ls[0].timestamp) ))
  283. firstMsg = ls[0];
  284. addMsgToCache(ls);
  285. showMsg(msg.concat(ls), false, true, false, true);
  286. }, function(res){
  287. console.error("e:"+JSON.stringify(res))
  288. })
  289. }, lastTimestamp);
  290. }
  291. })
  292. }
  293. }
  294. /**
  295. * 设置获取到的最后一条消息
  296. */
  297. function setLastMsg(msg){
  298. if(!lastTimestamp || lastTimestamp>msg.timestamp){
  299. lastTimestamp = msg.timestamp;
  300. lastSeq = msg.seq;
  301. lastId = msg.id.indexOf("loc")==0? lastId : msg.id;
  302. }
  303. }
  304. /**
  305. * 显示消息
  306. */
  307. function showMsg(msgList, isClear, isPre, appendImg, scrollToTop) {
  308. if(msgList.length == 0) {
  309. plus.nativeUI.closeWaiting();
  310. myScroll.refresh(msgList.length==0);
  311. return;
  312. }
  313. var html = "";
  314. var preTime = 0;
  315. var typeMsg = 1;
  316. var doctor_img ;
  317. var doctor_name = "";
  318. var msg;
  319. var sender;
  320. //设置对方已读标志
  321. var lastFetchTime = members[otherCode]?members[otherCode].last_fetch_time:new Date("1970-01-01");//对聊医生最后读取消息时间或对聊患者最后读取消息时间
  322. for(var i = msgList.length - 1; i >= 0; i--) {
  323. msg = msgList[i];
  324. setLastMsg(msg);
  325. typeMsg = parseInt(msg.content_type);
  326. var contentMsg = msg.content;
  327. if(typeMsg == 7 || typeMsg==10 || typeMsg==13 || typeMsg==14){
  328. if(typeMsg == 7 && msg.sender_id == 'system'){
  329. contentMsg = "居民24小时内未回复,系统自动结束咨询";
  330. }
  331. if(typeMsg != 14){ //14标记患者进入咨询
  332. html += '<div class="time-tips"><div>'+ contentMsg +' </div></div>';
  333. }
  334. continue;
  335. } else if(typeMsg == 5){
  336. var con = JSON.parse(msg.content);
  337. if(msg.sender_id == docInfo.code){
  338. console.log(msg.content)
  339. html += '<div class="time-tips"><div>已向'+ con.doctor_name +'医生求助<a data-name="'+ con.doctor_name +'" data-code="'+ con.doctor +'" class="qiuzhu5" href="javascript:void(0)">立即查看</a> </div></div>';
  340. }
  341. continue;
  342. }
  343. sender = members[msg.sender_id];
  344. if(!sender){
  345. sendPostNoAsync("doctor/baseinfo", {code:msg.sender_id}, null, function(res) {
  346. if(res.status == 200) {
  347. var dtemp = res.data;
  348. doctor_name = dtemp.name;
  349. doctor_img = getImgUrl(dtemp.photo);
  350. members[dtemp.code] = {
  351. code: dtemp.code,
  352. name: dtemp.name,
  353. sex: dtemp.sex,
  354. photo: getImgUrl(dtemp.photo),
  355. role: 1,//角色不再此讨论组中
  356. is_patient: 0 //不是患者
  357. };
  358. sender = members[msg.sender_id];
  359. }
  360. });
  361. }else{
  362. doctor_name = sender.name;
  363. // doctor_img = sender.photo ? sender.photo : (sender.avatar || "../../../images/p-default.png");
  364. doctor_img = getImgUrl(sender.photo);
  365. }
  366. if(msg.sender_id == docInfo.code) {
  367. doctor_img = getImgUrl(docInfo.photo);
  368. }
  369. var _class = ["chat-log"];
  370. if(docInfo.code != msg.sender_id) {
  371. _class.push("chat-left");
  372. } else {
  373. _class.push("chat-right");
  374. }
  375. if(inMoreOpera) _class.push("checkbox");//更多操作模式下
  376. if(msg.timestamp - preTime > 60 * 1000) {
  377. preTime = msg.timestamp;
  378. var date = new Date();
  379. date.setTime(msg.timestamp);
  380. var time = date.format('yyyy-MM-dd hh:mm:ss');
  381. html += '<div class="time-tips"><span>' + time + '</span></div>';
  382. }
  383. //type:1.文字 2.图片 3.音频
  384. var temp = '<dl data-type="'+ typeMsg +'" data-code="'+ msg.id +'" class="' + _class.join(" ") + '">'+
  385. '<dt style="height: auto; text-align: center;"><a><img src="' + doctor_img + '" class="c-images-cycle" /></a></dt>' +
  386. '<div class="c-content"><span class="c-f12 name">' + doctor_name + '</span>';
  387. var sendErrDom = "";
  388. if(!msg.beforeSend && msg.id && msg.id.indexOf('loc')==0){
  389. sendErrDom = "<i data-info='"+ JSON.stringify(msg) +"' class='c-tips'></i>";
  390. }
  391. //设置已读标志
  392. var yiduHtml1 = '<span class="yidu"></span>';
  393. var yiduHtml2 = '<span class="yidu yidu1"></span>';
  394. var yiduHtml3 = '<span class="yidu yidu2"></span>';
  395. if(self.id=="p2dzixun" || self.id=="p2p" && !(!msg.beforeSend && msg.id && msg.id.indexOf('loc')==0)){//医生和患者对聊、医生和医生对聊,显示是否已读
  396. //var ydText = "居民已读";
  397. // TODO "居民已读" 临时改为 "已读"
  398. var ydText = "已读";
  399. if(!isPatient){//医生对聊
  400. ydText = "已读";
  401. }
  402. if (!isSend) {
  403. ydText = '';
  404. }
  405. if(docInfo.code == msg.sender_id) {
  406. if(msg.timestamp<=lastFetchTime){
  407. yiduHtml1 = '<span class="yidu">'+ydText+'</span>';//除了视频,文章
  408. yiduHtml2 = '<span class="yidu yidu1">'+ydText+'</span>';//视频、文章
  409. yiduHtml3 = '<span class="yidu yidu2">'+ydText+'</span>';//图片
  410. }
  411. }
  412. }else{//团队群聊、求助群聊不显示是否已读
  413. yiduHtml1 = '';
  414. yiduHtml2 = '';
  415. yiduHtml3 = '';
  416. }
  417. switch(typeMsg) {
  418. case 0:
  419. case 1://普通文本
  420. case 6://开始咨询文本
  421. case 8://求助文本
  422. temp += '<div class="c-msg">'+ sendErrDom + yiduHtml1+'<dd class="word-bread" data-is-doctor="' + sender.is_patient + '" data-type="1"><span>' + matchUrl(contentMsg) + '</span></dd></div>';
  423. break;
  424. case 2://图片
  425. case 9://求助图片
  426. if(msg.local_src=="data:,")
  427. contentMsg = msg.content;
  428. else if(msg.local_src)
  429. contentMsg = msg.local_src.indexOf('data:')==0? msg.local_src: plus.io.convertLocalFileSystemURL(msg.local_src);
  430. else
  431. contentMsg = msg.content;
  432. var imgUrl = contentMsg;
  433. if(imgUrl.indexOf("/storage") > -1){
  434. //本地图片
  435. imgUrl = imgUrl;
  436. }else{
  437. imgUrl = getImgUrl(contentMsg);
  438. }
  439. temp += '<div class="c-msg">'+ sendErrDom + '<dd class="word-bread word-bread-img" data-type="2">'+yiduHtml3+'<img onload="imgLoad(this)" data-src="'+ imgUrl +'" data-code="'+ msg.id +'" data-preview-src="" data-preview-group="1" width="100" height="100" src="'+ imgUrl +'" /></dd></div>';
  440. $('img.l-previmg[data-code="'+ msg.id +'"]').remove();
  441. break;
  442. case 3://语音
  443. var rec = msg.local_src? JSON.parse(msg.local_src) : contentMsg? JSON.parse(contentMsg) : undefined;
  444. if(rec){
  445. var path = msg.local_src?msg.local_src:msg.content;
  446. temp += "<div class='c-msg'>"+ sendErrDom + yiduHtml1+"<dd class='word-bread audio' data-type='3' data-code='"+ msg.id +"' data-audio='" + contentMsg + "' data-loc-audio='" + path +"'>"+
  447. "<div style='width:"+ (rec.times*1.5+30) +"px' class='soundWav'>" +
  448. "<span class='soundWavT'>"+(rec? rec.times: "") +"\'\'</span>"+
  449. "</div>"+
  450. "</dd></div>";
  451. }
  452. break;
  453. case 4: //文章
  454. temp += formatJyzd(contentMsg, sendErrDom,yiduHtml2, msg.timestamp);
  455. // temp += '<dd class="word-bread" data-type="1"><span>' + matchUrl(contentMsg) + '</span></dd>';
  456. break;
  457. case 12: //视频
  458. var videoInfo = msg.content.split(",");
  459. var shichang = formatSeconds(videoInfo[2]);//时长
  460. if(docInfo.code != msg.sender_id) {
  461. temp += '<div class="c-msg"><dd data-content="'+msg.content+'" class="preview-video" data-type="12" data-video="'+getImgUrl(videoInfo[1])+'">'+yiduHtml2+
  462. '<img class="video-img-left" src="'+getImgUrl(videoInfo[0])+'">'+
  463. '<img class="bofang-icon-left" src="../images/bofang_icon.png">'+
  464. '<img class="jianjiao-icon-left" src="../images/zuoshanjiao_bg.png">'+
  465. '<span class="shichang-time-left">'+shichang+'</span>'+
  466. '</dd></div>';
  467. }else{
  468. temp += '<div class="c-msg"><dd data-content="'+msg.content+'" class="preview-video" data-type="12" data-video="'+getImgUrl(videoInfo[1])+'">'+yiduHtml2+
  469. '<img class="video-img-right" src="'+getImgUrl(videoInfo[0])+'">'+
  470. '<img class="bofang-icon-right" src="../images/bofang_icon.png">'+
  471. '<img class="jianjiao-icon-right" src="../images/youshanjiao_bg.png">'+
  472. '<span class="shichang-time-right">'+shichang+'</span>'+
  473. '</dd></div>';
  474. }
  475. break;
  476. }
  477. html += temp + '</div></dl>';
  478. }
  479. if(isPre)
  480. lastId = msgList[msgList.length - 1].id;
  481. if(typeMsg != null && typeMsg != 1) {
  482. $(".tw-add-detail").hide(200);
  483. }
  484. if(isClear){
  485. $("#input_content").text("");
  486. showSendBtn(false);
  487. $("#contain").html(html);
  488. }else{
  489. if(isPre){
  490. $("#contain").prepend(html);
  491. if(scrollToTop)
  492. myScroll.refreshToTop();
  493. else
  494. myScroll.refresh(msgList.length==0);
  495. return;
  496. } else {
  497. $("#contain").append(html);
  498. }
  499. }
  500. isSend = true;
  501. myScroll.refreshToEnd();
  502. plus.nativeUI.closeWaiting();
  503. }
  504. //毫秒转换成时分秒
  505. function formatSeconds(value) {
  506. var theTime = parseInt(value/1000);// 秒
  507. var theTime1 = 0;// 分
  508. var theTime2 = 0;// 小时
  509. if(theTime > 60) {
  510. theTime1 = parseInt(theTime/60);
  511. theTime = parseInt(theTime%60);
  512. if(theTime1 > 60) {
  513. theTime2 = parseInt(theTime1/60);
  514. theTime1 = parseInt(theTime1%60);
  515. }
  516. }
  517. var result = ""+parseInt(theTime);//秒
  518. if(parseInt(theTime)<=9){
  519. result = "0"+parseInt(theTime);//秒
  520. }
  521. if(theTime1 > 0) {//分
  522. if(parseInt(theTime1)>9){
  523. result = ""+parseInt(theTime1)+":"+result;
  524. }else{
  525. result = "0"+parseInt(theTime1)+":"+result;
  526. }
  527. }
  528. if(theTime2 > 0) {//小时
  529. if(parseInt(theTime2)>9){
  530. result = ""+parseInt(theTime2)+":"+result;
  531. }else{
  532. result = "0"+parseInt(theTime2)+":"+result;
  533. }
  534. }
  535. var resResult = "";
  536. if(result.split(":").length==1){//秒
  537. resResult = "00:"+result;
  538. }else if(result.split(":").length==2){//分
  539. resResult = "00:"+result;
  540. }else{//时
  541. resResult = result;
  542. }
  543. return resResult;
  544. }
  545. function formatJyzd(msg, sendErrDom,yiduHtml, timestamp){
  546. // {"title":"2016年春节放假调休门诊安排通知","id":"ff1b39cfdf6a482c958140ba768474cc","img":"http://f1.yihuimg.com/TFS/upfile/WBJ/111/2016-02-05/160294_1454633481085_fullsize.png","content":"为了您的健康,我给您发送了一篇文章,请咨询查阅,如有问题,可随时与我沟通"}
  547. if(msg){
  548. //针对\n,\r等特殊字符,在json转换时会报错
  549. msg = msg.replace(/\n/g, "\\n");
  550. msg = msg.replace(/\r/g, "\\r");
  551. msg = JSON.parse(msg);
  552. // msg.img = msg.type==1? "../../../images/jkjl_share.png" : msg.img;
  553. var imgHtml = '';
  554. if(msg.type == 1){ //健康记录
  555. msg.img = "../../../images/jkjl_share.png";
  556. imgHtml = '<img src="'+msg.img+'">';
  557. }else if(msg.type == 2){ //健康指导
  558. var img = msg.img.split(",");
  559. if(img[0] && img[0] != "null"){
  560. msg.img = getImgUrl(img[0]);
  561. }else{
  562. msg.img = "../../../images/default_share_blue.png";
  563. }
  564. imgHtml = '<img src="'+msg.img+'">';
  565. }else{ //健康教育
  566. if(msg.img && msg.img!="null"){
  567. msg.img = getImgUrl(msg.img);
  568. imgHtml = '<img src="'+msg.img+'">';
  569. }
  570. }
  571. var temp =
  572. '<div class="c-msg">'+ sendErrDom +'<dd class="word-bread word-article" data-code="'+ msg.id+'" data-inner-type="'+ msg.type +'" data-type="4" data-time="'+timestamp+'">'
  573. + yiduHtml
  574. + '<h4 class="text-ellipsis c-f18">'+ msg.title +'</h4>'
  575. + '<div class="article-content">'+imgHtml
  576. + '<div>'+ msg.content+'</div>'
  577. + '</div>'
  578. + '</dd></div>';
  579. return temp;
  580. }
  581. return "";
  582. }
  583. /**
  584. * 缓存消息
  585. * @param {Object} data
  586. */
  587. function addMsgToCache(list, appendImg) {
  588. // id TEXT, sender_id TEXT, sender_name TEXT, content_type TEXT,
  589. // content TEXT, timestamp TEXT, local_src TEXT, seq
  590. isCached = true;
  591. var tmp ;
  592. sqlite.db.transaction(function(tx){
  593. for(var i=0; i<list.length; i++){
  594. tmp = list[i];
  595. tx.executeSql(
  596. 'INSERT INTO '+ tableName +
  597. ' (id, sender_id, sender_name, content_type, content, timestamp, local_src) '+
  598. ' VALUES(?,?,?,?,?,?,?)',
  599. [
  600. tmp.id, tmp.sender_id, tmp.sender_name, tmp.content_type,
  601. tmp.content, tmp.timestamp, tmp.local_src || ""
  602. ],
  603. function(tx, rs){
  604. console.log(rs)
  605. }, function(tx, rs){
  606. console.log(rs)
  607. });
  608. }
  609. }, function(rs){
  610. console.error(JSON.stringify(rs));
  611. })
  612. }
  613. /*
  614. * 刷新数字角标
  615. */
  616. function refreshBadge(){
  617. var userId = plus.storage.getItem('im_userid');
  618. imClient.Application.getBadgeNo(userId, function(result) {
  619. console.log(JSON.stringify(result));
  620. try {
  621. if (result && result.badge != null) {
  622. plus.runtime.setBadgeNumber(result.badge);
  623. }
  624. } catch (e) {
  625. }
  626. });
  627. }
  628. /*
  629. * 附加功能
  630. */
  631. $(".tw-add").click(function() {
  632. $(".tw-add-detail").toggle(200);
  633. });
  634. var recordCancel = false;
  635. var recorder = null;
  636. var audio_tips = document.getElementById("audio_tips");
  637. var startTimestamp = null;
  638. var stopTimestamp = null;
  639. var stopTimer = null;
  640. var timer = null;
  641. var MIN_SOUND_TIME = 800;
  642. var isEnded = false;
  643. var ui = {
  644. body: document.querySelector('body'),
  645. btnMsgType: document.querySelector('#msg-type'),
  646. boxMsgText: document.querySelector('#msg-text'),
  647. boxMsgSound: document.querySelector('#msg-sound'),
  648. btnMsgImage: document.querySelector('#msg-image'),
  649. areaMsgList: document.querySelector('#msg-list'),
  650. boxSoundAlert: document.querySelector('#sound-alert')
  651. };
  652. ui.boxMsgSound.addEventListener('hold', function(){
  653. $(this).addClass('yy-hold');
  654. $(".audio").removeClass("active");
  655. recordCancel = false;
  656. if(stopTimer)clearTimeout(stopTimer);
  657. audio_tips.innerHTML = "手指上划,取消发送";
  658. ui.boxSoundAlert.classList.remove('rprogress-sigh');
  659. setSoundAlertVisable(true);
  660. recorder = plus.audio.getRecorder();
  661. if (recorder == null) {
  662. plus.nativeUI.toast("不能获取录音对象");
  663. return;
  664. }
  665. startTimestamp = (new Date()).getTime();
  666. timer = setInterval(function(){
  667. var t = (new Date()).getTime();
  668. if( Math.round( (t-startTimestamp)/1000 ) >=60){
  669. clearInterval(timer);
  670. recordEnd();
  671. mui.toast("最多录制60秒");
  672. isEnded = true;
  673. }
  674. }, 1000)
  675. recorder.record({
  676. filename: "_doc/audio/",
  677. format: "amr"
  678. }, function(path) {
  679. if (recordCancel) return;
  680. var recTime = Math.round((stopTimestamp - startTimestamp)/1000) ;
  681. var p = JSON.stringify(plus.io.convertLocalFileSystemURL( path ));
  682. uploadMsg(3, "", {path: path, times: recTime>60? 60 : recTime}, true, function(data){
  683. uploadImg(data)
  684. });
  685. }, function(e) {
  686. plus.nativeUI.toast("录音时出现异常: " + e.message);
  687. });
  688. })
  689. function recordEnd(event) {
  690. if(isEnded){
  691. isEnded = false;
  692. return;
  693. }
  694. clearInterval(timer);
  695. $(ui.boxMsgSound).removeClass('yy-hold');
  696. if (audio_tips.classList.contains("cancel")) {
  697. audio_tips.classList.remove("cancel");
  698. audio_tips.innerHTML = "手指上划,取消发送";
  699. }
  700. stopTimestamp = (new Date()).getTime();
  701. if (stopTimestamp - startTimestamp < MIN_SOUND_TIME) {
  702. audio_tips.innerHTML = "录音时间太短";
  703. ui.boxSoundAlert.classList.add('rprogress-sigh');
  704. recordCancel = true;
  705. stopTimer=setTimeout(function(){
  706. setSoundAlertVisable(false);
  707. },800);
  708. }else{
  709. setSoundAlertVisable(false);
  710. }
  711. recorder.stop();
  712. }
  713. ui.boxMsgSound.addEventListener('release', recordEnd, false);
  714. ui.body.addEventListener('drag', function(event) {
  715. if (Math.abs(event.detail.deltaY) > 50) {
  716. if (!recordCancel) {
  717. recordCancel = true;
  718. if (!audio_tips.classList.contains("cancel")) {
  719. audio_tips.classList.add("cancel");
  720. }
  721. audio_tips.innerHTML = "松开手指,取消发送";
  722. }
  723. } else {
  724. if (recordCancel) {
  725. recordCancel = false;
  726. if (audio_tips.classList.contains("cancel")) {
  727. audio_tips.classList.remove("cancel");
  728. }
  729. audio_tips.innerHTML = "手指上划,取消发送";
  730. }
  731. }
  732. }, false);
  733. var setSoundAlertVisable=function(show){
  734. if(show){
  735. ui.boxSoundAlert.style.display = 'block';
  736. ui.boxSoundAlert.style.opacity = 1;
  737. }else{
  738. ui.boxSoundAlert.style.opacity = 0;
  739. //fadeOut 完成再真正隐藏
  740. setTimeout(function(){
  741. ui.boxSoundAlert.style.display = 'none';
  742. },200);
  743. }
  744. };
  745. $(".yy-add").click(function() {
  746. if($('#msg-sound:visible').length){
  747. $ipt_content.show();
  748. ui.boxMsgSound.style.display = 'none';
  749. $(this).find('img:eq(0)').show().next().hide();
  750. } else {
  751. $ipt_content.hide();
  752. ui.boxMsgSound.style.display = 'block';
  753. $(this).find('img:eq(0)').hide().next().show();
  754. }
  755. });
  756. var inMoreOpera = false;
  757. var $logOper = $('.log-oper');
  758. var $curChatLog;
  759. $('#contain').on('longtap', '.word-bread[data-type!="4"][data-type!="3"],.preview-video[data-type="12"]', function(e){
  760. //弹出操作菜单 复制、转发、更多
  761. if(!inMoreOpera){
  762. var w = 264;//264
  763. if($(this).attr('data-type') != 1){
  764. w = 114;
  765. $logOper.find('.fz').hide();
  766. $logOper.find('.kjhf').hide();
  767. } else {
  768. $logOper.find('.fz').show();
  769. $logOper.find('.kjhf').show();
  770. }
  771. if ($(this).attr('data-type') == 1 && $(this).attr('data-is-doctor') == 0) {
  772. w = 378;
  773. imMsg = $(this).find('span').html();
  774. $('.zdmb').show();
  775. } else {
  776. $('.zdmb').hide();
  777. }
  778. // alert(w);
  779. var sx = e.originalEvent.detail.touches[0].screenX;
  780. var left = 0;
  781. if(sx-(w/2)<0){
  782. left = 0;
  783. } else if(sx+(w/2)>winWidth) {
  784. left = winWidth - w;
  785. } else {
  786. left = sx - (w/2);
  787. }
  788. var top = e.originalEvent.detail.touches[0].screenY - 56;
  789. $logOper.find('div').css('left', (sx-left)+ 'px');
  790. $logOper.css({'top': top +'px', 'left': left + 'px', 'display': '-webkit-box'});
  791. $curChatLog = $(this).parent().parent();
  792. if (w == 378) {
  793. var wW = $(window).width(),
  794. c = wW - w,
  795. ol = $logOper[0].offsetLeft;
  796. if ((ol + w) > wW) {
  797. left = c;
  798. $logOper.css({'top': top +'px', 'left': left + 'px', 'display': '-webkit-box'});
  799. }
  800. }
  801. return false;
  802. }
  803. }).on('tap', '.chat-log', function(){
  804. //选择聊天记录
  805. if(inMoreOpera){
  806. $(this).toggleClass('checked');
  807. return false;
  808. }
  809. }).on('tap', '.c-tips', function(){
  810. var tips = $(this);
  811. if(tips.length==0) return false;
  812. dialog({
  813. content:'重发该消息?',
  814. okValue:'重发',
  815. ok: function() {
  816. var data = JSON.parse(tips.attr('data-info'));
  817. if(data.content_type==2){
  818. uploadImg(data);
  819. } else if(data.content_type==3){
  820. } else {
  821. sendMsg(data);
  822. }
  823. tips.remove();
  824. },
  825. cancelValue: '取消',
  826. cancel: function () {
  827. return;
  828. }
  829. }).showModal();
  830. return false;
  831. }).on('tap', '.word-bread[data-type="3"]', function(){
  832. $('#contain').find('.word-bread[data-type="3"]').removeClass("active");
  833. var $dom = $(this);
  834. var loc = $(this).attr('data-loc-audio');
  835. $dom.addClass('active');
  836. if(!loc){
  837. var ser = $(this).attr('data-audio');
  838. if(ser){
  839. ser = JSON.parse(ser);
  840. //下载
  841. var path = "_doc/audio/"+new Date().getTime()+".wav";
  842. var dtask = plus.downloader.createDownload( ser.path, {
  843. filename: path
  844. },
  845. function ( d, status ) {
  846. if ( status == 200 ) {
  847. //更新数据,播放语音
  848. playRecord(path, $dom);
  849. } else {
  850. $dom.removeClass('active');
  851. mui.toast("下载语音失败!");
  852. }
  853. });
  854. dtask.start();
  855. } else{
  856. $dom.removeClass('active');
  857. mui.toast("语音数据丢失!");
  858. }
  859. } else {
  860. loc = JSON.parse(loc);
  861. var filename = "_doc/audio/",
  862. path = "";
  863. if(loc.path.indexOf(filename) > -1){
  864. path = loc.path;
  865. }else{
  866. path = getImgUrl(loc.path);
  867. }
  868. //播放语音
  869. playRecord(path, $dom);
  870. }
  871. }).on('tap', '.preview-video[data-type="12"]', function(){//播放视频
  872. var url = $(this).attr('data-video');
  873. if(plus.os.name=="iOS"){//ios
  874. $(document.body).find('video').remove();
  875. var html = '<video controls style="display:none;" preload="auto" width="1" height="1" src="'+url+'" ></video>';
  876. $(document.body).append(html);
  877. var video = $(document.body).find('video')[0];
  878. video.play();
  879. }else{//andriod
  880. var Intent = plus.android.importClass("android.content.Intent");
  881. var Uri = plus.android.importClass("android.net.Uri");
  882. var main = plus.android.runtimeMainActivity();
  883. var intent=new Intent(Intent.ACTION_VIEW);
  884. var uri=Uri.parse(url);
  885. intent.setDataAndType(uri,"video/*");
  886. main.startActivity(intent);
  887. }
  888. })
  889. var player;
  890. var $playDom = false;
  891. function playRecord(path, dom){
  892. var isPlayBenDi = path.indexOf('.amr')>=0;
  893. if($playDom){
  894. if(player){
  895. if(plus.os.name=="iOS" && !isPlayBenDi){//ios
  896. player.pause();
  897. }else{
  898. player.stop();
  899. }
  900. $playDom.removeClass('active');
  901. if($playDom.attr('data-code') == dom.attr('data-code')){
  902. $playDom = false;
  903. return;
  904. }
  905. }
  906. }
  907. $playDom = dom;
  908. if(plus.os.name=="iOS" && !isPlayBenDi){//ios
  909. $(document.body).find('audio').remove();
  910. var html = '<audio preload="auto" src="'+path+'"></audio>';
  911. $(document.body).append(html);
  912. player = $(document.body).find('audio')[0];
  913. player.play();
  914. player.addEventListener('ended', function () {
  915. $playDom.removeClass('active');
  916. $playDom = false;
  917. }, false);
  918. }else{//andriod
  919. player = plus.audio.createPlayer(path);
  920. player.play(function() {
  921. $playDom.removeClass('active');
  922. $playDom = false;
  923. }, function(e) {
  924. $playDom.removeClass('active');
  925. $playDom = false;
  926. });
  927. }
  928. }
  929. /**
  930. * 批量操作按钮事件
  931. */
  932. $logOper.on('touchstart', '.pl', function(){
  933. inMoreOpera = true;
  934. $logOper.hide();
  935. $curChatLog.addClass('checked');
  936. $('.chat-log[data-type!=4][data-type!=3]').addClass('checkbox');
  937. $('#input_div').addClass('c-hide');
  938. $('.footer-bar').removeClass('c-hide');
  939. $('#qun_detail').hide();
  940. $('#cancel').show();
  941. myScroll.refresh();
  942. })
  943. /**
  944. * 复制操作按钮事件
  945. */
  946. $logOper.on('touchstart', '.fz', function(){
  947. $logOper.hide();
  948. copy($curChatLog.find('.word-bread span').text(), 1);
  949. return false;
  950. })
  951. /**
  952. * 转发操作按钮事件
  953. */
  954. $logOper.on('touchstart', '.zf', function(){
  955. $logOper.hide();
  956. var type = $curChatLog.find('.word-bread').attr("data-type");
  957. var text = "";
  958. if(type=="1"){//文本
  959. var $d = $curChatLog.find('.word-bread span');
  960. text = $d.text();
  961. }else {
  962. if($curChatLog.closest("dl").attr("data-type")=="12"){//视频
  963. text = $curChatLog.find(".c-msg dd").attr("data-content");
  964. type = 12;
  965. }else{//图片
  966. var $d = $curChatLog.find('.word-bread img');
  967. text = $d.attr('data-src');
  968. type = 2;
  969. }
  970. }
  971. toZf([{content: text, type: type}]);
  972. return false;
  973. })
  974. /**
  975. * 快捷回复操作按钮事件
  976. */
  977. $logOper.on('touchstart', '.kjhf', function(){
  978. $logOper.hide();
  979. var $d = $curChatLog.find('.word-bread span');
  980. var text = "";
  981. if($d.length > 0){
  982. text = $d.text();
  983. service.replyAdd(text);
  984. }
  985. return false;
  986. })
  987. /**
  988. * 添加指导模板操作按钮事件
  989. */
  990. $logOper.on('touchstart', '.zdmb', function(){
  991. $logOper.hide();
  992. dialog({
  993. content: "是否确认将内容添加到指导模板?",
  994. okValue: "立即添加",
  995. ok: function(){
  996. openWebview('../../hzzd/html/edit_guidance.html',{action: "add",reference: 'zuyuanziliao', pageid:self.id, msg: imMsg});
  997. },
  998. cancelValue: "不了,谢谢",
  999. cancel: function(){}
  1000. }).showModal();
  1001. // return false;
  1002. })
  1003. /**
  1004. * 转发操作按钮事件
  1005. */
  1006. $('#plzf').on('touchstart', function(){
  1007. var msgs = [];
  1008. var text = "";
  1009. var $d;
  1010. var type;
  1011. $.each($('.chat-log.checked'), function(i, v) {
  1012. type = $(v).find('.word-bread').attr("data-type");
  1013. if(type=="1"){//文本
  1014. $d = $(v).find('.word-bread span');
  1015. text = $d.text();
  1016. }else {
  1017. if($(v).attr("data-type")=="12"){//视频
  1018. text = $(v).find(".c-msg dd").attr("data-content");
  1019. type = 12;
  1020. }else{
  1021. $d = $(v).find('.word-bread img');
  1022. text = $d.attr('src');
  1023. type = 2;
  1024. }
  1025. }
  1026. msgs.push({content: text, type: type});
  1027. });
  1028. toZf(msgs);
  1029. return false;
  1030. })
  1031. /**
  1032. * 跳转转发界面
  1033. * @param {Object} texts
  1034. */
  1035. function toZf(texts){
  1036. mui.openWindow({
  1037. url: "zhuanfa.html",
  1038. id: "zhuanfa.html",
  1039. extras: {
  1040. imMessages: texts
  1041. }
  1042. })
  1043. }
  1044. /**
  1045. * 复制
  1046. * @param {Object} content
  1047. * @param {Object} type
  1048. */
  1049. function copy(content, type){
  1050. if(plus.os.name == "Android"){
  1051. if(type == 1)
  1052. plus.android.invoke(AndroidClip, "setText", content);
  1053. else{
  1054. // ClipData clip = ClipData.newUri(AndroidMain.getContentResolver(), "URI", copyUri);
  1055. // plus.android.invoke(AndroidClip, "setPrimaryClip", clip);
  1056. }
  1057. } else {
  1058. var generalPasteboard = UIPasteboard.generalPasteboard();
  1059. // 设置/获取文本内容:
  1060. if(type == 1)
  1061. generalPasteboard.setValueforPasteboardType(content, "public.utf8-plain-text");
  1062. else
  1063. generalPasteboard.setDataforPasteboardType(content, "public.png");
  1064. // UIPasteboard.generalPasteboard().setData(fileData, forPasteboardType: "public.png")
  1065. }
  1066. }
  1067. /**
  1068. * 还原批量操作状态
  1069. */
  1070. function revertPl(){
  1071. if(inMoreOpera){
  1072. inMoreOpera = false;
  1073. $('.chat-log').removeClass('checkbox checked');
  1074. $('#input_div').removeClass('c-hide');
  1075. $('.footer-bar').addClass('c-hide');
  1076. $('#qun_detail').show();
  1077. $('#cancel').hide();
  1078. myScroll.refresh();
  1079. }
  1080. }
  1081. /**
  1082. * 取消按钮事件
  1083. */
  1084. $('#cancel').on('tap', function(){
  1085. revertPl();
  1086. })
  1087. var touchLogOper = false;
  1088. // $('.log-oper').on('touchstart', function(){
  1089. // touchLogOper = true;
  1090. // })
  1091. /**
  1092. * 点击任意地方 关闭操作菜单
  1093. */
  1094. $('body').on('touchstart', function(){
  1095. if($('.log-oper:visible').length){
  1096. $logOper.hide();
  1097. return false;
  1098. }
  1099. })
  1100. /**
  1101. * 显示发送按钮的事件
  1102. */
  1103. var valLen = 0;
  1104. var $ipt_content = $('#input_content');
  1105. $ipt_content.on('input', function(e){
  1106. showSendBtn($(this).text())
  1107. })
  1108. .on('tap', function(){
  1109. $(".tw-add-detail").hide();
  1110. $ipt_content.focus();
  1111. mui.later(scrollToEnd, 300);
  1112. })
  1113. function scrollToEnd(){
  1114. if(winHei-$('body').height() > 0){
  1115. myScroll.scrollToEnd(500);
  1116. $ipt_content.focus();
  1117. }
  1118. else {
  1119. mui.later(scrollToEnd, 100);
  1120. }
  1121. }
  1122. function showSendBtn(isShow){
  1123. if(isShow){
  1124. $('.tw-add').hide();
  1125. $('#reply').fadeIn('fast', 'swing');
  1126. } else if(valLen == 1 || isShow==false){
  1127. $('#reply').fadeOut('fast', 'swing', function(){
  1128. $('.tw-add').show();
  1129. });
  1130. }
  1131. valLen = isShow ? isShow.length : 0;
  1132. }
  1133. /*
  1134. * 发送照片
  1135. */
  1136. function clickGallery() {
  1137. plus.gallery.pick(function(path) {
  1138. var lastIdx = path.lastIndexOf("/"),
  1139. imgName = path;
  1140. if(lastIdx>-1) {
  1141. imgName = path.slice(lastIdx+1);
  1142. }
  1143. var locSrc= "_doc/chat/gallery/" + imgName;
  1144. plus.zip.compressImage({
  1145. src: path,
  1146. dst: locSrc,
  1147. quality: 20,
  1148. overwrite: true
  1149. }, function(e) {
  1150. console.log(e.target)
  1151. uploadMsg(2, "", locSrc, true, function(data){
  1152. uploadImg(data);
  1153. });
  1154. }, function(err) {
  1155. console.error("压缩失败:" + err.message);
  1156. });
  1157. }, function(err) {});
  1158. };
  1159. function uploadImg(data){
  1160. var task = plus.uploader.createUpload(server + "upload/chat?type="+data.content_type, {
  1161. method: "post"
  1162. }, function(t, sta) {
  1163. if(sta == 200) {
  1164. var msg = t.responseText;
  1165. var oImg = JSON.parse(msg);
  1166. if(oImg.status==200){
  1167. var imgUrl = oImg.urls;
  1168. var re = new RegExp("\\\\", "g");
  1169. imgUrl = imgUrl.replace(re, "/");
  1170. if(data.content_type==3){
  1171. var loc = JSON.parse(data.local_src);
  1172. data.content = JSON.stringify({path: imgUrl, times: loc.times});
  1173. } else {
  1174. if($("#contain").find("dl:last").attr("data-code").substring(0,3)=="loc"){//上传图片成功后,更新图片url
  1175. $("#contain").find("dl:last").find("dd img").attr("src",getImgUrl(imgUrl)).attr("data-src",getImgUrl(imgUrl));
  1176. }
  1177. data.content = imgUrl;
  1178. }
  1179. sendMsg(data);
  1180. } else {
  1181. mui.toast("发送失败,请重试!");
  1182. showResend(data);
  1183. }
  1184. } else {
  1185. mui.toast("发送失败,请重试!");
  1186. showResend(data);
  1187. }
  1188. });
  1189. if(data.content_type==3){
  1190. var loc = JSON.parse(data.local_src);
  1191. task.addFile(loc.path, {});
  1192. } else {
  1193. task.addFile(data.local_src, {});
  1194. }
  1195. task.start();
  1196. }
  1197. /*
  1198. * 拍照
  1199. */
  1200. function clickCamera() {
  1201. var cmr = plus.camera.getCamera();
  1202. var res = cmr.supportedImageResolutions[0];
  1203. var fmt = cmr.supportedImageFormats[0];
  1204. cmr.captureImage(function(path) {
  1205. plus.io.resolveLocalFileSystemURL(path, function(entry) {
  1206. var localUrl = entry.toLocalURL();
  1207. var lastIdx = localUrl.lastIndexOf("/"),
  1208. imgName = localUrl;
  1209. if(lastIdx>-1) {
  1210. imgName = localUrl.slice(lastIdx+1);
  1211. }
  1212. var locSrc= "_doc/chat/camera/" + imgName;
  1213. plus.zip.compressImage({
  1214. src: localUrl,
  1215. dst: locSrc,
  1216. quality: 20,
  1217. overwrite: true
  1218. }, function(e) {
  1219. uploadMsg(2, "", locSrc, true, function(data){
  1220. uploadImg(data);
  1221. });
  1222. }, function(err) {
  1223. console.log("压缩失败: " + err.message);
  1224. });
  1225. });
  1226. }, function(err) {
  1227. if(err.code==11 && err.message == "null") {
  1228. plus.nativeUI.toast("您尚未授权拍照权限,无法使用拍照功能。");
  1229. }
  1230. console.error("拍照失败:" + err.message);
  1231. }, {
  1232. index: 1
  1233. });
  1234. };
  1235. /**
  1236. * 更新信息事件
  1237. */
  1238. window.addEventListener("update", function() {
  1239. console.log("update");
  1240. getNewMsgs(false);
  1241. });
  1242. /**
  1243. * 后台返回应用时获取消息
  1244. */
  1245. document.addEventListener("resume", function() {
  1246. console.log("运行环境从后台切换到前台事件")
  1247. getNewMsgs(false);
  1248. connectSocket();
  1249. }, false);
  1250. //运行环境从前台切换到后台事件
  1251. document.addEventListener("pause", function() {
  1252. console.log("运行环境从前台切换到后台事件")
  1253. logoutSocketConnect();
  1254. }, false);
  1255. /**
  1256. * 还原转发状态
  1257. */
  1258. document.addEventListener("revertZf", function() {
  1259. $logOper.hide();
  1260. revertPl();
  1261. hideMenu();
  1262. prevImage.close();
  1263. // getNewMsgs();
  1264. });
  1265. function backToParent(){
  1266. // var old_back = mui.back;
  1267. mui.back = function() {
  1268. var wv = self.opener();
  1269. if(wv){
  1270. mui.fire(wv, "xiaoxiUpdate");
  1271. }
  1272. self.close();
  1273. // old_back();
  1274. }
  1275. }
  1276. function matchUrl(content){
  1277. var a = urlRegex.exec(content);
  1278. if(a){
  1279. var ah = '<a class="urlMatch" href="javascript:void(0)">'+ a[0] +'</a>';
  1280. var str = "";
  1281. var s = content.split(a[0]);
  1282. // var i = content.indexOf(a[0]);
  1283. for(var i=0; i<s.length; i++){
  1284. if(i==s.length-1)
  1285. str += s[i];
  1286. else
  1287. str += s[i] + ah;
  1288. }
  1289. return str;
  1290. }
  1291. return content;
  1292. }
  1293. $('body').on('tap', '.urlMatch', function(){
  1294. mui.openWindow("../../browser/html/browser.html", "browser", {
  1295. extras: {
  1296. url: $(this).html()
  1297. }
  1298. })
  1299. })
  1300. $('body')
  1301. //隐藏打开的附加功能
  1302. .on('touchstart', '#wrapper1', function(){
  1303. $('.tw-add-detail').hide();
  1304. $ipt_content.blur();
  1305. })
  1306. //点击健康教育文章连接
  1307. .on('tap', '.word-article', function(){
  1308. var type = $(this).attr('data-inner-type');
  1309. var code = $(this).attr('data-code');
  1310. if(type==1){
  1311. mui.openWindow('../../jkjl/html/health-record.html', 'health-record', {
  1312. extras: {
  1313. patientCode: code,
  1314. qyRelation: 0
  1315. }
  1316. });
  1317. }else if(type == 2){
  1318. mui.openWindow('../../hzzd/html/guidance_info.html', 'guidance_info', {
  1319. extras:{
  1320. guideId: code
  1321. }
  1322. })
  1323. } else{
  1324. //判断发送时间是否超过"2017-12-29 00:00:00",超过后发送的文章为新的文章
  1325. var sendTime = $(this).attr("data-time"),
  1326. d = new Date("2017-12-29 00:00:00"),
  1327. dTime = d.getTime();
  1328. if(parseInt(sendTime) < dTime){
  1329. mui.openWindow("../../jkjy/html/article.html", "article", {
  1330. extras: {
  1331. article: code
  1332. }
  1333. })
  1334. }else{
  1335. mui.openWindow("../../jkjy/html/article-info.html", "article", {
  1336. extras: {
  1337. articleId: code
  1338. }
  1339. })
  1340. }
  1341. }
  1342. })
  1343. //点击预约挂号查看详情
  1344. .on('tap', '.word-bread a[name="guahao"]', function(){
  1345. mui.openWindow("../../wdyy/html/detail-appointment.html", "detail-appointment", {
  1346. extras: {
  1347. dataId: $(this).attr('data-id')
  1348. }
  1349. })
  1350. })
  1351. //添加快捷回复
  1352. function kjhf(){
  1353. openWebview("../../kjhf/html/list.html");
  1354. }
  1355. window.addEventListener('fillText', function(e){
  1356. $(".tw-add-detail").hide();
  1357. var content = e.detail.content;
  1358. $("#input_content").show();
  1359. ui.boxMsgSound.style.display = 'none';
  1360. $(".yy-add").find('img:eq(0)').show().next().hide();
  1361. $("#input_content").text(content);
  1362. showSendBtn(true);
  1363. });
  1364. /**
  1365. * 显示重新发送按钮
  1366. * @param {Object} d 数据
  1367. */
  1368. function showResend(d){
  1369. $('#contain dl[data-code="'+ d.id +'"]').find('.c-msg').prepend("<i data-info='"+ JSON.stringify(d) +"' class='c-tips'></i>");
  1370. }
  1371. /**
  1372. * 创建聊天会话
  1373. */
  1374. var sessionId;
  1375. function createSession(type, callBack){
  1376. if(self.sessionId){
  1377. sessionId = self.sessionId;
  1378. $('#title').html(self.sessionName);
  1379. createTable(callBack);
  1380. } else {
  1381. if(type==2)
  1382. imClient.Sessions.createP2pSession(docInfo.code, self.otherCode, self.otherName,function(res){
  1383. if(res.status==200){
  1384. sessionId = res.data.id;
  1385. $('#title').html(res.data.name || self.otherName);
  1386. createTable(callBack);
  1387. } else {
  1388. alert("创建聊天会话失败!");
  1389. }
  1390. }, function(res){
  1391. alert("创建聊天会话失败!");
  1392. console.error("fail:"+JSON.stringify(res))
  1393. })
  1394. else if(type == 1)
  1395. createTable(callBack);
  1396. else if(type==3){
  1397. imClient.Sessions.createGroupSession(teamInfo.code, teamInfo.teamName, members,
  1398. function(res){
  1399. if(res.status == 200){
  1400. sessionId = res.data.id;
  1401. $('#title').html(res.data.name || teamInfo.teamName);
  1402. createTable(callBack);
  1403. } else
  1404. alert("创建聊天会话失败!");
  1405. }, function(res){
  1406. alert("创建聊天会话失败!");
  1407. console.error("fail:"+JSON.stringify(res))
  1408. })
  1409. }
  1410. }
  1411. }
  1412. var tableName = "";
  1413. var isCached = false;
  1414. /**
  1415. * 获取新消息
  1416. * @param {Object} isInit
  1417. */
  1418. function getNewMsgs(isInit){
  1419. if(isInit && self.msgId){
  1420. //带msgId定位参数的,
  1421. locationLog(self.msgId);
  1422. } else
  1423. getMsgs(1, pageSize, "", firstMsg? firstMsg.id : "", function(data){
  1424. if(data.length>0 && (!firstMsg || (firstMsg.timestamp<data[0].timestamp) ))
  1425. firstMsg = data[0];
  1426. getNewMsgHandle( data, isInit );
  1427. }, function(res){
  1428. console.error("e:"+JSON.stringify(res))
  1429. })
  1430. }
  1431. /**
  1432. * 从后台获取最前面的消息
  1433. *
  1434. */
  1435. function getFirstMsgs(){
  1436. getMsgs(1, pageSize, "", "", function(data){
  1437. if(data.length>0 && (!firstMsg || (firstMsg.timestamp<data[0].timestamp) ))
  1438. firstMsg = data[0];
  1439. getNewMsgHandle(data, true );
  1440. }, function(res){
  1441. console.error("e:"+JSON.stringify(res))
  1442. })
  1443. }
  1444. /**
  1445. * 获取消息
  1446. */
  1447. function getMsgs(page, size, startMsg, endMsg, sucHandle, errHandle, isoffset){
  1448. imClient.Sessions.getMessagesBySession(sessionId, docInfo.code, page || 1, size || paeSize, startMsg, endMsg,
  1449. function(res){
  1450. sucHandle( parseMsg(res) );
  1451. }, function(res){
  1452. mui.toast("获取消息记录失败!");
  1453. console.error("e:"+JSON.stringify(res))
  1454. }, "", isoffset || (endMsg? 1 : ""))
  1455. }
  1456. /**
  1457. * 创建表结构
  1458. */
  1459. function createTable(callBack){
  1460. tableName = "msgLog_"+ sessionId.replace(/-/g, "_") +"_"+ docInfo.code.replace(/-/g, "_");
  1461. /*sqlite.executeSql("DROP TABLE IF EXISTS "+tableName, [], function(){});
  1462. return;*/
  1463. sqlite.executeSql("create table if not exists "+ tableName +
  1464. " (id TEXT UNIQUE, sender_id TEXT, sender_name TEXT, content_type INTEGER, " +
  1465. " content TEXT, timestamp INTEGER, local_src BLOB, seq INTEGER PRIMARY KEY AUTOINCREMENT)", [],
  1466. function(tx, rs){
  1467. sqlite.executeSql("select * from "+tableName+" where id not like 'loc%' order by timestamp desc limit 0,1", [],
  1468. function(tx, rs){
  1469. isCached = rs.rows.length>0;
  1470. if(!isCached){
  1471. sqlite.executeSql("select * from "+tableName+" limit 0,1", [], function(tx, rs){
  1472. isCached = rs.rows.length>0;
  1473. callBack ? callBack() : "";
  1474. }, function(tx, rs){
  1475. alert("获取聊天缓存失败!");
  1476. })
  1477. } else {
  1478. firstMsg = rs.rows.item(0);
  1479. callBack ? callBack() : "";
  1480. }
  1481. }, function(tx, rs){
  1482. console.error(JSON.stringify(rs))
  1483. alert("获取聊天缓存失败!");
  1484. })
  1485. },
  1486. function(tx, rs){
  1487. console.error(tableName)
  1488. alert("创建缓存空间失败!");
  1489. })
  1490. }
  1491. var lastSeq = 0;
  1492. var lastTimestamp;
  1493. /**
  1494. * 获取缓存消息
  1495. * @param {Object} seq
  1496. * @param {Object} size
  1497. * @param {Object} callBack
  1498. * @param {Object} timestamp
  1499. * @param {Object} isNext
  1500. */
  1501. function getCacheMsg(seq, size, callBack, timestamp, isNext){
  1502. var p = [];
  1503. var sql = 'SELECT * FROM '+ tableName;
  1504. var where = [];
  1505. if(seq){
  1506. where.push(" seq<>? ");
  1507. p.push(seq);
  1508. }
  1509. if(timestamp){
  1510. where.push(" timestamp"+ (isNext? ">=" : "<") +"? ");
  1511. p.push(timestamp);
  1512. }
  1513. sql += where.length>0? " where "+ where.join(" and ") : "";
  1514. sql += " order by timestamp desc ";
  1515. sql += size? " limit 0,"+size : "";
  1516. sqlite.executeSql(sql, p, function(tx, rs){
  1517. var data = [];
  1518. var tmp;
  1519. for(var i=0; i<rs.rows.length; i++){
  1520. tmp = rs.rows.item(i);
  1521. data.push( tmp );
  1522. /*if(lastTimestamp>tmp.timestamp){
  1523. lastTimestamp = tmp.timestamp;
  1524. lastSeq = tmp.seq;
  1525. lastId = tmp.id.indexOf("loc")==0? lastId : tmp.id;
  1526. }*/
  1527. }
  1528. callBack(tx, data);
  1529. }, function(tx, errmsg){
  1530. mui.toast('获取缓存数据失败!');
  1531. console.log(JSON.stringify(errmsg))
  1532. })
  1533. }
  1534. /**
  1535. * 获取缓存消息
  1536. * @param {Object} startTime
  1537. * @param {Object} endTime
  1538. * @param {Object} callBack
  1539. */
  1540. function getCacheMsgByRange(startTime, endTime, callBack){
  1541. var p = [];
  1542. var sql = 'SELECT * FROM '+ tableName +' where timestamp>='+ startTime +' and timestamp<'+ endTime;
  1543. sql += " order by timestamp desc ";
  1544. sqlite.executeSql(sql, p, function(tx, rs){
  1545. var data = [];
  1546. var tmp;
  1547. for(var i=0; i<rs.rows.length; i++){
  1548. tmp = rs.rows.item(i);
  1549. data.push( tmp );
  1550. /*if(lastTimestamp>tmp.timestamp){
  1551. lastTimestamp = tmp.timestamp;
  1552. lastSeq = tmp.seq;
  1553. lastId = tmp.id.indexOf("loc")==0? lastId : tmp.id;
  1554. }*/
  1555. }
  1556. callBack(tx, data);
  1557. }, function(tx, errmsg){
  1558. mui.toast('获取缓存数据失败!');
  1559. console.log(JSON.stringify(errmsg))
  1560. })
  1561. }
  1562. /**
  1563. * 获取缓存消息
  1564. * @param {Object} id
  1565. * @param {Object} callBack
  1566. */
  1567. function getCacheMsgById(id, callBack){
  1568. var sql = 'SELECT * FROM '+ tableName + ' where id=?';
  1569. sqlite.executeSql(sql, [id], function(tx, rs){
  1570. var data = [];
  1571. for(var i=0; i<rs.rows.length; i++){
  1572. data.push( rs.rows.item(i) );
  1573. }
  1574. callBack(tx, data);
  1575. }, function(tx, errmsg){
  1576. mui.toast('获取缓存数据失败!');
  1577. console.log(JSON.stringify(errmsg))
  1578. })
  1579. }
  1580. /**
  1581. * 获取最后一条缓存消息
  1582. * @param {Object} callBack
  1583. * @param {Object} lastTimestamp
  1584. */
  1585. function getLastCacheMsg(callBack, lastTimestamp){
  1586. var sql = 'SELECT * FROM '+ tableName + ' where id not like "loc%" ';
  1587. sql += lastTimestamp? " and timestamp<"+lastTimestamp : "";
  1588. sql += " order by timestamp desc ";
  1589. sqlite.executeSql(sql, [], function(tx, rs){
  1590. var data = [];
  1591. for(var i=0; i<rs.rows.length; i++){
  1592. data.push( rs.rows.item(i) );
  1593. }
  1594. callBack(tx, data);
  1595. }, function(tx, errmsg){
  1596. mui.toast('获取缓存数据失败!');
  1597. console.log(JSON.stringify(errmsg))
  1598. })
  1599. }
  1600. /**
  1601. * 发送消息
  1602. * @param {Object} content
  1603. * @param {Object} type
  1604. * @param {Object} oldId
  1605. */
  1606. function sendMsg(d){
  1607. imClient.Sessions.sendMessage(sessionId, docInfo.code, docInfo.name, d.content, d.content_type,
  1608. function(data) {
  1609. console.log(JSON.stringify(data))
  1610. var msg = data.messages[0];
  1611. if( !firstMsg || firstMsg.timestamp<msg.timestamp )
  1612. firstMsg = msg;
  1613. setLastMsg(msg);
  1614. // updateCacheMsgById(d.id, msg.timestamp, msg.id, msg.content);
  1615. }, function(data){
  1616. if(data.status == 406){
  1617. mui.toast("观察者模式无法进行增删改操作");
  1618. }
  1619. showResend(d);
  1620. console.log("sendFail"+ JSON.stringify(data));
  1621. })
  1622. }
  1623. /**
  1624. * 将字符串转为对象
  1625. * @param {Object} data
  1626. */
  1627. function parseMsg(data){
  1628. var d = [];
  1629. for(var i=0; i<data.length; i++){
  1630. d.push(JSON.parse(data[i]));
  1631. }
  1632. return d;
  1633. }
  1634. /**
  1635. * 更新缓存数据
  1636. * @param {Object} oldId 旧id
  1637. * @param {Object} timestamp 更新时间
  1638. * @param {Object} newId 更新id
  1639. * @param {Object} content 内容
  1640. * @param {Object} localSrc 更新本地路径
  1641. */
  1642. function updateCacheMsgById(oldId, timestamp, newId, content, localSrc){
  1643. var sql = "update "+ tableName +" set ";
  1644. var u = [];
  1645. var p = [];
  1646. if(timestamp){
  1647. u.push(" timestamp=? ");
  1648. p.push(timestamp);
  1649. }
  1650. if(newId){
  1651. u.push(" id=? ");
  1652. p.push(newId);
  1653. }
  1654. if(localSrc){
  1655. u.push(" local_src=? ");
  1656. p.push(localSrc);
  1657. }
  1658. if(content){
  1659. u.push(" content=? ");
  1660. p.push(content);
  1661. }
  1662. sql += u.join(",")+ " where id=?";
  1663. p.push(oldId);
  1664. sqlite.executeSql( sql, p, function(tx, rs){
  1665. debugger
  1666. }, function(tx, msg){
  1667. alert("更新缓存失败!")
  1668. console.error(JSON.stringify(msg))
  1669. })
  1670. }
  1671. function imgLoad(img){
  1672. if(img.src.indexOf('data:')==0)
  1673. return;
  1674. var canvas = document.createElement('CANVAS'),
  1675. ctx = canvas.getContext('2d'),
  1676. newImg = new Image();
  1677. newImg.src = img.src;
  1678. canvas.height = newImg.height;
  1679. canvas.width = newImg.width;
  1680. ctx.drawImage(newImg, 0, 0);
  1681. var src = newImg.src;
  1682. var outputFormat = src.substring(src.lastIndexOf('.')+1);
  1683. outputFormat = outputFormat.toLowerCase()=="jpg"? "jpeg" : outputFormat;
  1684. var dataURL = canvas.toDataURL('image/' + outputFormat);
  1685. // updateCacheMsgById($(img).attr('data-code'), "", "", "", dataURL);
  1686. canvas = null;
  1687. }
  1688. /**
  1689. * 获取消息(下拉刷新)
  1690. */
  1691. function getMsgList(pageIndex, isClear, isPre) {
  1692. getMsgs(pageIndex, pageSize, "", "", function(data){
  1693. showMsg(data, isClear, isPre);
  1694. })
  1695. //下面代码缓存机制有问题
  1696. // getCacheMsg(lastSeq, pageSize, function(tx, list){
  1697. // if(list.length<pageSize){
  1698. // getMsgs(1, pageSize-list.length, lastId, "", function(data){
  1699. // if(data.length>0){
  1700. // addMsgToCache(data);
  1701. // }
  1702. // showMsg(list.concat(data), isClear, isPre);
  1703. // })
  1704. // } else {
  1705. // showMsg(list, isClear, isPre);
  1706. // }
  1707. // }, lastTimestamp);
  1708. }
  1709. function uploadMsgBase(type, content, locSrc, isNotSend, callBack){
  1710. var tim = new Date().getTime();
  1711. var id = "loc"+tim;
  1712. locSrc = type==3? JSON.stringify(locSrc): locSrc;
  1713. var d = [{
  1714. "sender_id": docInfo.code,"sender_name": docInfo.name,
  1715. "content_type": type, "content": content,
  1716. "timestamp": tim,"id": id, local_src: locSrc, beforeSend: true}]
  1717. showMsg(d, false, false, true);
  1718. // addMsgToCache(d, true);
  1719. isNotSend? "" : sendMsg(d[0]);
  1720. if (callBack) callBack(d[0]);
  1721. // return d[0];
  1722. }
  1723. //录像
  1724. function clickVideo(){
  1725. if(plus.os.name == "Android"){
  1726. plus.nativeUI.toast("请录制10秒左右的短视频,以防录制完成后无法发送",{duration:"long"});
  1727. var File = plus.android.importClass("java.io.File");
  1728. var MediaStore = plus.android.importClass("android.provider.MediaStore");
  1729. var Intent = plus.android.importClass("android.content.Intent");
  1730. var intent = new Intent("android.media.action.VIDEO_CAPTURE");
  1731. var outPutPath = plus.io.convertLocalFileSystemURL("http://localhost:13131/_doc/camera/test.mp4");
  1732. var Uri = plus.android.importClass("android.net.Uri");
  1733. var file = new File(outPutPath);
  1734. var outPutUri = Uri.fromFile(file);
  1735. intent.putExtra("android.intent.extra.videoQuality", 1);//0 最低质量, 1高质量
  1736. intent.putExtra("android.provider.MediaStore.EXTRA_OUTPUT", outPutUri);//录像输出位置
  1737. // intent.putExtra("android.intent.extra.durationLimit", 10);//控制录制时间单位秒
  1738. var main = plus.android.runtimeMainActivity();
  1739. main.startActivityForResult(intent,200);
  1740. main.onActivityResult = function(request, code, data) {
  1741. var context = main;
  1742. plus.android.importClass(data);
  1743. var contactData = data.getData();
  1744. var resolver = context.getContentResolver();
  1745. plus.android.importClass(resolver);
  1746. var cursor = resolver.query(contactData, null, null, null, null);
  1747. plus.android.importClass(cursor);
  1748. cursor.moveToFirst();
  1749. var column = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
  1750. //获取录制的视频路径
  1751. andriodVideoUrl = cursor.getString(column);
  1752. //解析视频文件的属性
  1753. plus.io.resolveLocalFileSystemURL(andriodVideoUrl,function( entry ) {
  1754. // 可通过entry对象操作test.html文件
  1755. entry.file( function(file){
  1756. console.log("size=="+file.size+" name=="+file.name);
  1757. var fileSize = (file.size/1024/1024).toFixed(2);//字节转换成M
  1758. fileSizeJudge(fileSize);//文件大小判断
  1759. } );
  1760. }, function ( e ) {
  1761. plus.nativeUI.toast( "Resolve file URL failed: " + e.message );
  1762. });
  1763. };
  1764. }
  1765. }
  1766. function bindEvents(){
  1767. //录制视频
  1768. $(".lz-video-img").click(function(){
  1769. plus.nativeUI.toast("请录制10秒左右的短视频,以防录制完成后无法发送",{duration:"long"});
  1770. $("#upload_input").click();
  1771. return false;
  1772. })
  1773. //立即发送
  1774. $("#lijifasong").on("tap", function(){
  1775. uploadVideo();
  1776. mui('#sheet1').popover('toggle');
  1777. return false;
  1778. });
  1779. //不再提醒
  1780. $("#buzaitixing").on("tap", function(){
  1781. plus.storage.setItem("isTiXingVideoFaSong","1");
  1782. uploadVideo();
  1783. mui('#sheet1').popover('toggle');
  1784. return false;
  1785. });
  1786. }
  1787. //ios录像回调事件
  1788. function videoFileChange(target) {
  1789. var fileSize = (target.files[0].size/1024/1024).toFixed(2);//字节转换成M
  1790. fileSizeJudge(fileSize);
  1791. }
  1792. //文件大小判断
  1793. function fileSizeJudge(fileSize){
  1794. if(parseInt(fileSize)>30){
  1795. dialog({
  1796. content:'对不起,视频超过30Mb,无法发送,请录制10秒左右的短视频',
  1797. okValue:'我知道了',
  1798. ok: function() {
  1799. return;
  1800. }
  1801. }).showModal();
  1802. }else{
  1803. if(networkStatus=="wifi" || (plus.storage.getItem("isTiXingVideoFaSong") && plus.storage.getItem("isTiXingVideoFaSong")=="1")){//wifi环境或用户点击移动网络弹框中的”不再提醒“按钮
  1804. uploadVideo();
  1805. }else{
  1806. $("#mui-content").html('您正在使用移动网络,继续发送将消耗'+fileSize+'Mb流量,是否继续发送?');
  1807. mui('#sheet1').popover('toggle');
  1808. }
  1809. }
  1810. }
  1811. //上传视频
  1812. function uploadVideo(){
  1813. plus.nativeUI.showWaiting();
  1814. if(plus.os.name == "Android"){//andriod上传视频
  1815. var task = plus.uploader.createUpload(server + "upload/chat?type=4", {method: "post"}, function(t, sta) {
  1816. if(t.responseText){
  1817. var msg = t.responseText;
  1818. var oImg = JSON.parse(msg);
  1819. if(oImg.status==200){
  1820. uploadMsg(12, oImg.urls);
  1821. }else if(oImg.status==-1){
  1822. mui.toast(oImg.msg);
  1823. }else{
  1824. mui.toast("发送失败,请重试!");
  1825. }
  1826. }else{
  1827. mui.toast("发送失败,请重试!");
  1828. }
  1829. plus.nativeUI.closeWaiting();
  1830. });
  1831. task.addFile(andriodVideoUrl, {});
  1832. task.start();
  1833. }else{//ios上传视频
  1834. var fd=new FormData();
  1835. fd.append('file',document.getElementById("upload_input").files[0]);
  1836. $.ajax(server+"/upload/chat?type=4", {
  1837. data: fd,
  1838. contentType: false,
  1839. cache: false,
  1840. processData: false,
  1841. type: 'post',
  1842. success: function(resData) {
  1843. if(resData.status==200){
  1844. uploadMsg(12, resData.urls);
  1845. }else if(resData.status==-1){
  1846. mui.toast(oImg.msg);
  1847. }else{
  1848. mui.toast("发送失败,请重试!");
  1849. }
  1850. plus.nativeUI.closeWaiting();
  1851. },
  1852. error:function (XMLHttpRequest, textStatus, errorThrown) {
  1853. console.log(XMLHttpRequest.status);
  1854. console.log(XMLHttpRequest.readyState);
  1855. console.log(textStatus)
  1856. }
  1857. });
  1858. }
  1859. }