chatRoom.js 54 KB

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