chatRoom.js 54 KB

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