xf-chatRoom.js 69 KB

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