UtilService.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. angular.module('push')
  2. .factory('UtilService', function ($rootScope, $timeout, $http, ConfigService, $q) {
  3. var utilService = {};
  4. var toastflg = 0;
  5. //TODO 公共弹窗,提示信息用
  6. utilService.showMess = function (mess) {
  7. console.log(1);
  8. window.plugins.toast.show(mess, 'short', 'center', function (a) {
  9. }, function (b) {
  10. });
  11. // if (toastflg == 0) {
  12. // toastflg = 1;
  13. // console.log(2);
  14. // window.plugins.toast.show(mess, 'short', 'center', function (a) {
  15. // }, function (b) {
  16. // });
  17. // $timeout(function () {
  18. // toastflg = 0;
  19. // }, 200);
  20. // }
  21. };
  22. //Android:true,IOS:false
  23. utilService.checkPlatform = function () {
  24. return device.platform == "Android";
  25. };
  26. //格式化时间、时间戳
  27. utilService.formatDate = function () {
  28. var tempdate = new Date();
  29. return {
  30. timestamp: (Date.parse(tempdate) / 1000),
  31. formattime: tempdate.Format("yyyy-MM-dd hh:mm:ss"),
  32. formattime2: tempdate.Format("yyyy-MM-dd hh:mm:ss.S"),
  33. formattime3: tempdate.Format("yyyy年MM月dd日 hh:mm")
  34. };
  35. };
  36. //时间转时间戳
  37. utilService.reversalDate = function (str) {
  38. if (device.platform != "Android") {
  39. str = str.replace("-", "/");
  40. str = str.replace("-", "/");
  41. }
  42. var timestamp = Date.parse(new Date(str));
  43. timestamp = timestamp / 1000;
  44. return timestamp;
  45. };
  46. //时间戳转时间
  47. utilService.reversalTimestamp = function (str) {
  48. return new Date(parseInt(str) * 1000).Format("yyyy-MM-dd hh:mm:ss");
  49. };
  50. //yyyy年MM月dd日 转 yyyy-MM-dd
  51. utilService.formatTime = function (tempstr) {
  52. tempstr = tempstr.replace("年", "-");
  53. tempstr = tempstr.replace("月", "-");
  54. tempstr = tempstr.replace("日", "");
  55. return tempstr;
  56. };
  57. //获取当前日期{年,月,日,格式化日期,周}
  58. utilService.getNowDate = function () {
  59. //日期、星期初始化
  60. var week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
  61. //选中日期初始化
  62. var _date = new Date();
  63. var weekind = (_date.getDay() == 0) ? 6 : _date.getDay() - 1;
  64. var month = _date.getMonth() + 1;
  65. var day = _date.getDate();
  66. var tempn = _date.getFullYear() + "-";
  67. if (month < 10) {
  68. tempn = tempn + "0" + month + "-";
  69. } else {
  70. tempn = tempn + month + "-";
  71. }
  72. if (day < 10) {
  73. tempn = tempn + "0" + day;
  74. } else {
  75. tempn = tempn + day;
  76. }
  77. return {
  78. year: _date.getFullYear(),
  79. month: month,
  80. day: day,
  81. date: tempn,
  82. week: week[weekind]
  83. };
  84. };
  85. //时间比较 true:第一个时间更近 false:第二个时间更近
  86. utilService.compareDate = function (date1, date2) {
  87. var oDate1 = new Date(date1);
  88. var oDate2 = new Date(date2);
  89. return oDate1.getTime() > oDate2.getTime();
  90. };
  91. //格式化链接(提取链接中参数组成json)
  92. utilService.formatUrlToJson = function (url) {
  93. var temp1 = url.substring(url.lastIndexOf("?") + 1, url.length);
  94. var temp2 = temp1.replace(/=/g, "\":\"");
  95. var temp3 = "{\"" + temp2.replace(/&/g, "\",\"") + "\"}";
  96. return angular.fromJson(temp3);
  97. };
  98. //检测网络状态
  99. utilService.checkNetWork = function () {
  100. var networkState = navigator.connection.type;
  101. var states = {};
  102. states[Connection.UNKNOWN] = 'Unknown connection';
  103. states[Connection.ETHERNET] = 'Ethernet connection';
  104. states[Connection.WIFI] = 'WiFi connection';
  105. states[Connection.CELL_2G] = 'Cell 2G connection';
  106. states[Connection.CELL_3G] = 'Cell 3G connection';
  107. states[Connection.CELL_4G] = 'Cell 4G connection';
  108. states[Connection.CELL] = 'Cell generic connection';
  109. states[Connection.NONE] = 'No network connection';
  110. if (states[networkState] == 'WiFi connection') {
  111. return "WiFi";
  112. } else if (states[networkState] == 'No network connection') {
  113. return "None";
  114. } else {
  115. return "Other";
  116. }
  117. };
  118. var content = "";
  119. utilService.tempRep = function (type, str) {
  120. if (type == 0) {
  121. content = str.replace("\n", "<br>");
  122. if (content.indexOf("\n") != -1) {
  123. this.tempRep(0, content);
  124. }
  125. } else {
  126. content = str.replace("<br>", "\n");
  127. if (content.indexOf("<br>") != -1) {
  128. this.tempRep(1, content);
  129. }
  130. }
  131. };
  132. // 合并2个json
  133. utilService.concatJson = function (obj1, obj2) {
  134. var str1 = angular.toJson(obj1);
  135. str1 = str1.substr(0, str1.length - 1) + ",";
  136. var str2 = angular.toJson(obj2);
  137. str2 = str1 + str2.substr(1, str2.length);
  138. return angular.fromJson(str2);
  139. };
  140. //textarea中换行转<br>
  141. utilService.replaceEnterTag = function (str) {
  142. this.tempRep(0, str);
  143. return content;
  144. };
  145. //<br>转换行
  146. utilService.replaceHTMLTag = function (str) {
  147. this.tempRep(1, str);
  148. return content;
  149. };
  150. //检测6~20位数字字母组合密码
  151. utilService.checkPassword = function (str) {
  152. return (/^[0-9a-zA-Z]{6,20}$/.test(str));
  153. };
  154. //检查字符是否为空
  155. utilService.isDefined = function (str) {
  156. return (angular.isDefined(str) && str != null && str != "" && str != "null");
  157. };
  158. //检查手机号码
  159. utilService.isMobilePhone = function (str) {
  160. return ((/^[+0-9-()()]{7,18}$/.test(str)));
  161. // return ((/^1(3|4|5|7|8)\d{9}$/.test(str)));
  162. };
  163. //检查固定电话
  164. utilService.isTelePhone = function (tel) {
  165. return (/^0\d{2,3}-?\d{7,8}$/.test(tel));
  166. };
  167. //检测15/18位身份证号码
  168. utilService.isIdentityNumber = function (num) {
  169. return (/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/.test(num));
  170. };
  171. //检测邮箱
  172. utilService.isEmail = function (email) {
  173. return (/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(email));
  174. };
  175. //批量上传文件
  176. utilService.uploadFile = function (urls, filetype, mimeType) {
  177. //控制ajax请求异步变同步
  178. var deferred = $q.defer();
  179. var result = [];
  180. var upload = function (index) {
  181. if (index < urls.length) {
  182. var params = {};
  183. params.type = filetype;
  184. var options = new FileUploadOptions();
  185. options.mimeType = mimeType;
  186. options.fileKey = "file";
  187. options.fileName = urls[index].substr(urls[index].lastIndexOf('/') + 1);
  188. options.chunkedMode = false;
  189. options.params = params;
  190. var ft = new FileTransfer();
  191. // ft.upload(urls[index], ConfigService.server + "appUploadFile.action?", function win(r) {
  192. ft.upload(urls[index], ConfigService.server + "common/upload/attachment?", function win(r) {
  193. if (r.response == "null" || r.response == null || angular.isUndefined(r.response)) {
  194. deferred.reject();
  195. } else {
  196. var json = JSON.parse(r.response);
  197. result.push(json);
  198. upload(index + 1);
  199. }
  200. }, function fail(error) {
  201. console.log(error);
  202. result.push({photoName: "", originalName: ""});
  203. upload(index + 1);
  204. }, options);
  205. } else {
  206. deferred.resolve(result);
  207. }
  208. };
  209. upload(0);
  210. return deferred.promise;
  211. };
  212. //拍照、提取单张照片
  213. utilService.getPicture = function (srcType) {
  214. var deferred = $q.defer();
  215. var options = {
  216. quality: 50,
  217. destinationType: Camera.DestinationType.FILE_URI,
  218. sourceType: srcType, //0:相册 1:相机
  219. encodingType: Camera.EncodingType.JPEG,
  220. mediaType: Camera.MediaType.PICTURE,
  221. allowEdit: false,
  222. correctOrientation: true,
  223. saveToPhotoAlbum: true
  224. };
  225. navigator.camera.getPicture(function (imageData) {
  226. deferred.resolve(imageData);
  227. }, function (message) {
  228. deferred.reject(message);
  229. }, options);
  230. return deferred.promise;
  231. };
  232. //批量提取照片
  233. utilService.getPictureList = function (maxcount) {
  234. var deferred = $q.defer();
  235. window.imagePicker.getPictures(
  236. function (results) {
  237. deferred.resolve(results);
  238. }, function (error) {
  239. deferred.reject(error);
  240. }, {
  241. maximumImagesCount: maxcount,
  242. quality: 50
  243. }
  244. );
  245. return deferred.promise;
  246. };
  247. //http get请求
  248. utilService.urlget=function(url){
  249. return $http({
  250. method: "get",
  251. url: url
  252. });
  253. };
  254. //http get请求
  255. utilService.get = function (url, data) {
  256. return this._http(url, "get", data);
  257. };
  258. //http post请求
  259. utilService.post = function (url, data) {
  260. return this._http(url, "post", data);
  261. };
  262. utilService._http = function (url, method, data) {
  263. var json = {comefrom: ConfigService.comefrom, filterInputKey: 1, callback: "JSON_CALLBACK"};
  264. var jsondata = angular.merge(data, json);
  265. if (angular.equals(method, "get")) {
  266. return $http({
  267. method: "get",
  268. url: url,
  269. headers: {
  270. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  271. },
  272. params: jsondata,
  273. // timeout: 15000
  274. });
  275. } else if (angular.equals(method, "post")) {
  276. return $http({
  277. method: "post",
  278. url: url,
  279. headers: {
  280. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  281. },
  282. // timeout: 15000,
  283. transformRequest: function (jsondata) {
  284. /** * The workhorse; converts an object to x-www-form-urlencoded serialization. * @param {Object} obj * @return {String} */
  285. var param = function (obj) {
  286. var query = '';
  287. var name, value;
  288. for (name in obj) {
  289. value = obj[name];
  290. query += name + '=' + value + '&';
  291. }
  292. query = query.substr(0, query.length - 1);
  293. // console.log(url + query);
  294. // query = encodeURIComponent(query);
  295. return query.length ? query.substr(0, query.length - 1) : query;
  296. };
  297. return angular.isObject(jsondata) && String(jsondata) !== '[object File]' ? param(jsondata) : jsondata;
  298. },
  299. data: jsondata
  300. });
  301. }
  302. };
  303. //http get请求(IM服务器)
  304. utilService.imget = function (url, data,key) {
  305. return this._imhttp(url, "get", data,key);
  306. };
  307. // utilService.keyget=function(url,data,key){
  308. // return this._keyhttp(url,'get',data,key);
  309. // }
  310. //http post请求(IM服务器)
  311. utilService.impost = function (url, data) {
  312. return this._imhttp(url, "post", data);
  313. };
  314. utilService.getparams = function (url, method, data) {
  315. //发起请求
  316. return $http({
  317. method: get,
  318. url: url,
  319. headers: {
  320. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  321. },
  322. params: data,
  323. });
  324. };
  325. utilService._imhttp = function (url, method, data,keys) {
  326. //服务地址后拼接参数
  327. var jsondata = '';
  328. for (var key in data) {
  329. jsondata += '/' + data[key];
  330. }
  331. if(keys){
  332. jsondata +='?=key'+keys;
  333. }
  334. //发起请求
  335. return $http({
  336. method: method,
  337. url: url + jsondata,
  338. headers: {
  339. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  340. },
  341. // cache:true,
  342. // ifModified :true ,
  343. params: {},
  344. // timeout: 20000
  345. });
  346. };
  347. utilService.getparams = function (url, params) {
  348. // var jsondata = '';
  349. // angular.forEach(params,function (res,key){
  350. // if(!jsondata){
  351. // jsondata='?'+key+'='+res;
  352. // }else {
  353. // jsondata +='&'+key+'='+res;
  354. // }
  355. //
  356. // })
  357. return $http({
  358. method: 'get',
  359. url: url,
  360. headers: {
  361. 'Content-Type': 'application/json; charset=UTF-8'
  362. },
  363. params: params,
  364. // timeout: 20000
  365. });
  366. };
  367. // utilService._keyhttp = function (url, method, data,keys) {
  368. // //服务地址后拼接参数
  369. // var jsondata = '';
  370. // for (var key in data) {
  371. // jsondata += '/' + data[key];
  372. // }
  373. // if(keys){
  374. // jsondata+='?key='+keys;
  375. // }
  376. // //发起请求
  377. // return $http({
  378. // method: method,
  379. // url: url + jsondata,
  380. // headers: {
  381. // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  382. // },
  383. // params: {},
  384. // timeout: 20000
  385. // });
  386. // };
  387. // 请求使用data
  388. utilService.imbodyhttp = function (url, data) {
  389. //发起请求
  390. return $http({
  391. method: "POST",
  392. url: url,
  393. dataType: 'json',
  394. headers: {
  395. 'Content-Type': 'application/json; charset=UTF-8'
  396. },
  397. params: {},
  398. data: data,
  399. });
  400. };
  401. // 请求使用data
  402. //上传
  403. utilService.Uploadhttp = function (url, data) {
  404. //发起请求
  405. return $http({
  406. method: "POST",
  407. url: url,
  408. data: data,
  409. headers: {'Content-Type': undefined},
  410. transformRequest: angular.identity,
  411. });
  412. };
  413. // 文件流下载
  414. utilService.downloadhttp = function (url, data) {
  415. //发起请求
  416. return $http({
  417. method: "POST",
  418. url: url,
  419. dataType: 'json',
  420. responseType: 'arraybuffer',
  421. headers: {
  422. 'Content-Type': 'application/json; charset=UTF-8'
  423. },
  424. params: {},
  425. data: data,
  426. // timeout: 15000
  427. });
  428. };
  429. // 文件流下载
  430. utilService.getdownload = function (url, data) {
  431. //发起请求
  432. return $http({
  433. method: "get",
  434. url: url,
  435. dataType: 'json',
  436. responseType: 'arraybuffer',
  437. headers: {
  438. 'Content-Type': 'application/json; charset=UTF-8'
  439. },
  440. params: {},
  441. data: data,
  442. });
  443. };
  444. return utilService;
  445. });