common.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import {checkLogin} from '@/api/user'
  2. import { getCourseDomain } from '@/api/common.js'
  3. import { getConfigByKey } from '@/api/course.js'
  4. import dayjs from 'dayjs'
  5. let TOKEN_KEYAuto = 'AppTokenmini_MYCourse'
  6. var isEmpty =function(obj) {
  7. if (typeof obj == "undefined" || obj == null || obj == "") {
  8. return true;
  9. } else {
  10. return false;
  11. }
  12. }
  13. var checkToken= function() {
  14. var token = uni.getStorageSync('AppToken');
  15. if (token==null||token==undefined||token=="" ) {
  16. return false;
  17. }
  18. return true;
  19. }
  20. var isLogin= function() {
  21. return new Promise((resolve, reject) => {
  22. checkLogin().then(
  23. res => {
  24. if(res.code==200){
  25. resolve(true);
  26. }else{
  27. resolve(false);
  28. }
  29. },
  30. rej => { }
  31. );
  32. });
  33. }
  34. var isLoginCourseAuto = function() {
  35. return new Promise((resolve, reject) => {
  36. let token = uni.getStorageSync(TOKEN_KEYAuto);
  37. if (token==null||token==undefined||token=="" ) {
  38. resolve(false);
  39. } else {
  40. resolve(true);
  41. }
  42. });
  43. }
  44. var loginOut= function() {
  45. uni.setStorageSync('AppToken',null);
  46. uni.setStorageSync('userInfo',null);
  47. }
  48. var checkLoginState= function() {
  49. var token = uni.getStorageSync('AppToken');
  50. if (token ) {
  51. return true
  52. } else {
  53. return false
  54. }
  55. }
  56. var getDictLabelName= function(key,dictValue) {
  57. if(dictValue==null){
  58. return "";
  59. }
  60. var dicts = uni.getStorageSync('dicts');
  61. dicts=JSON.parse(dicts);
  62. var dict=dicts[key]
  63. var name="";
  64. dict.forEach(function(item, index, array) {
  65. if(dictValue.toString()==item.dictValue.toString())
  66. {
  67. name=item.dictLabel
  68. }
  69. });
  70. return name;
  71. }
  72. var getDict= function(key) {
  73. var dicts = uni.getStorageSync('dicts');
  74. dicts=JSON.parse(dicts);
  75. var dict=dicts[key]
  76. return dict;
  77. }
  78. var photosToArr= function(photoUrl) {
  79. var photos=[];
  80. if(photoUrl!=null&&photoUrl!=''){
  81. photos=photoUrl.split(',');
  82. }
  83. return photos
  84. }
  85. var dateFormat=function dateFormat(fmt, date) {
  86. let ret;
  87. const opt = {
  88. "Y+": date.getFullYear().toString(), // 年
  89. "m+": (date.getMonth() + 1).toString(), // 月
  90. "d+": date.getDate().toString(), // 日
  91. "H+": date.getHours().toString(), // 时
  92. "M+": date.getMinutes().toString(), // 分
  93. "S+": date.getSeconds().toString() // 秒
  94. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  95. };
  96. for (let k in opt) {
  97. ret = new RegExp("(" + k + ")").exec(fmt);
  98. if (ret) {
  99. fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  100. };
  101. };
  102. return fmt;
  103. }
  104. var getProvider = service => {
  105. return new Promise((resolve, reject) => {
  106. // 获取当前环境的服务商
  107. uni.getProvider({
  108. service: service || 'oauth',
  109. success: function (res) {
  110. // 此处可以排除h5
  111. if (res.provider) {
  112. resolve(res.provider[0])
  113. }
  114. },
  115. fail() {
  116. reject('获取环境服务商失败')
  117. },
  118. })
  119. }).catch(error => {
  120. console.log('167', error)
  121. })
  122. }
  123. var handleTree=function handleTree(data, id, parentId, rootId) {
  124. id = id || 'id'
  125. parentId = parentId || 'parentId'
  126. rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0
  127. //对源数据深度克隆
  128. const cloneData = JSON.parse(JSON.stringify(data))
  129. //循环所有项
  130. const treeData = cloneData.filter(father => {
  131. let branchArr = cloneData.filter(child => {
  132. //返回每一项的子级数组
  133. return father[id] === child[parentId]
  134. });
  135. branchArr.length > 0 ? father.child = branchArr : '';
  136. //返回第一层
  137. return father[parentId] === rootId;
  138. });
  139. return treeData != '' ? treeData : data;
  140. }
  141. var parsePhone=function parsePhone(mobile) {
  142. var str = mobile.substr(0,3)+"****"+mobile.substr(7);
  143. return str;
  144. }
  145. var parseIdCard=function parseIdCard(idCard) {
  146. var str = idCard.substr(0,4)+"****"+idCard.substr(8);
  147. return str;
  148. }
  149. //格式为"1990-01-01"
  150. var getAge=function getAge(strBirthday){
  151. var returnAge,
  152. strBirthdayArr=strBirthday.split("-"),
  153. birthYear = strBirthdayArr[0],
  154. birthMonth = strBirthdayArr[1],
  155. birthDay = strBirthdayArr[2],
  156. d = new Date(),
  157. nowYear = d.getFullYear(),
  158. nowMonth = d.getMonth() + 1,
  159. nowDay = d.getDate();
  160. if(nowYear == birthYear){
  161. returnAge = 0;//同年 则为0周岁
  162. }
  163. else{
  164. var ageDiff = nowYear - birthYear ; //年之差
  165. if(ageDiff > 0){
  166. if(nowMonth == birthMonth) {
  167. var dayDiff = nowDay - birthDay;//日之差
  168. if(dayDiff < 0) {
  169. returnAge = ageDiff - 1;
  170. }else {
  171. returnAge = ageDiff;
  172. }
  173. }else {
  174. var monthDiff = nowMonth - birthMonth;//月之差
  175. if(monthDiff < 0) {
  176. returnAge = ageDiff - 1;
  177. }
  178. else {
  179. returnAge = ageDiff ;
  180. }
  181. }
  182. }else {
  183. returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
  184. }
  185. }
  186. return returnAge;//返回周岁年龄
  187. }
  188. var clearHisSearch= function() {
  189. var searchList=[];
  190. uni.setStorageSync("hisSearch",JSON.stringify(searchList));
  191. }
  192. var getHisSearch= function() {
  193. var search = uni.getStorageSync('hisSearch');
  194. if(search!=null&&search!=undefined&&search!=""){
  195. var search=JSON.parse(search);
  196. return search;
  197. }
  198. else{
  199. var data=[];
  200. return data;
  201. }
  202. }
  203. var addHisSearch= function(searchVal) {
  204. var search = uni.getStorageSync('hisSearch');
  205. var searchList=[];
  206. if(search!=null&&search!=undefined&&search!=""){
  207. searchList=JSON.parse(search);
  208. }
  209. searchList.push(searchVal);
  210. //去复
  211. const uniqueArr = [...new Set(searchList)];
  212. uni.setStorageSync("hisSearch",JSON.stringify(uniqueArr));
  213. }
  214. var parseTime= function(num){//时间戳数据处理
  215. let date = new Date(num*1000);
  216. //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  217. let y = date.getFullYear();
  218. let MM = date.getMonth() + 1;
  219. MM = MM < 10 ? ('0' + MM) : MM;//月补0
  220. let d = date.getDate();
  221. d = d < 10 ? ('0' + d) : d;//天补0
  222. let h = date.getHours();
  223. h = h < 10 ? ('0' + h) : h;//小时补0
  224. let m = date.getMinutes();
  225. m = m < 10 ? ('0' + m) : m;//分钟补0
  226. let s = date.getSeconds();
  227. s = s < 10 ? ('0' + s) : s;//秒补0
  228. return y + '-' + MM + '-' + d + ' ' + h + ':' + m+ ':' + s;
  229. }
  230. // var setData= function(obj){
  231. // let that = this;
  232. // let keys = [];
  233. // let val,data;
  234. // Object.keys(obj).forEach(function(key){
  235. // keys = key.split('.');
  236. // val = obj[key];
  237. // data = that.$data;
  238. // keys.forEach(function(key2,index){
  239. // if(index+1 == keys.length){
  240. // that.$set(data,key2,val);
  241. // }else{
  242. // if(!data[key2]){
  243. // that.$set(data,key2,{});
  244. // }
  245. // }
  246. // data = data[key2];
  247. // })
  248. // });
  249. // }
  250. var setData= function(obj){
  251. let that = this;
  252. const handleData = (tepData, tepKey, afterKey) => {
  253. var tepData2 = tepData;
  254. tepKey = tepKey.split('.');
  255. tepKey.forEach(item => {
  256. if (tepData[item] === null || tepData[item] === undefined) {
  257. let reg = /^[0-9]+$/;
  258. tepData[item] = reg.test(afterKey) ? [] : {};
  259. tepData2 = tepData[item];
  260. } else {
  261. tepData2 = tepData[item];
  262. }
  263. });
  264. return tepData2;
  265. };
  266. const isFn = function(value) {
  267. return typeof value == 'function' || false;
  268. };
  269. Object.keys(obj).forEach(function(key) {
  270. let val = obj[key];
  271. key = key.replace(/\]/g, '').replace(/\[/g, '.');
  272. let front, after;
  273. let index_after = key.lastIndexOf('.');
  274. if (index_after != -1) {
  275. after = key.slice(index_after + 1);
  276. front = handleData(that, key.slice(0, index_after), after);
  277. } else {
  278. after = key;
  279. front = that;
  280. }
  281. if (front.$data && front.$data[after] === undefined) {
  282. Object.defineProperty(front, after, {
  283. get() {
  284. return front.$data[after];
  285. },
  286. set(newValue) {
  287. front.$data[after] = newValue;
  288. that.hasOwnProperty("$forceUpdate") && that.$forceUpdate();
  289. },
  290. enumerable: true,
  291. configurable: true
  292. });
  293. front[after] = val;
  294. } else {
  295. that.$set(front, after, val);
  296. }
  297. });
  298. }
  299. const urlToObj = function(url) {
  300. let obj = {}
  301. let str = url.slice(url.indexOf('?') + 1)
  302. let arr = str.split('&')
  303. for (let j = arr.length, i = 0; i < j; i++) {
  304. let arr_temp = arr[i].split('=')
  305. obj[arr_temp[0]] = arr_temp[1]
  306. }
  307. return obj
  308. }
  309. var checkCompanyUserLoginState= function() {
  310. var token = uni.getStorageSync('CompanyUserToken');
  311. if (token ) {
  312. return true
  313. } else {
  314. return false
  315. }
  316. }
  317. /**
  318. * 格式化时间
  319. * @param {Object} 时间字符串
  320. */
  321. var formatDate=function(dateStr) {
  322. let date = dayjs(dateStr,'YYYY-MM-DD HH:mm:ss');
  323. let today = dayjs();
  324. let formatStr = "";
  325. if (date.year() != today.year()) {
  326. formatDate = date.format('YYYY-MM-DD HH:mm');
  327. }
  328. else if (date.month() === today.month()) {
  329. switch (date.date() - today.date()) {
  330. case 0:
  331. formatDate = date.format('今天 HH:mm');
  332. break;
  333. case -1:
  334. formatDate = date.format('昨天 HH:mm');
  335. break;
  336. case 1:
  337. formatDate = date.format('明天 HH:mm');
  338. break;
  339. default:
  340. formatDate = date.format('MM-DD HH:mm');
  341. break;
  342. }
  343. }
  344. else if (date.month() - today.month() === 0 && date.date() === 1) {
  345. formatDate = date.format('明天 HH:mm');
  346. }
  347. else {
  348. formatDate = date.format('MM-DD HH:mm');
  349. }
  350. return formatDate;
  351. }
  352. /**
  353. * 随机字符串
  354. *
  355. */
  356. var generateRandomString=function(length){
  357. let result = '';
  358. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  359. const charactersLength = characters.length;
  360. for (let i = 0; i < length; i++) {
  361. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  362. }
  363. return result;
  364. }
  365. var getDomain = function(data) {
  366. return new Promise((resolve, reject) => {
  367. getCourseDomain(data).then(
  368. res => {
  369. if(res.code==200){
  370. uni.setStorageSync('projectCode',data.projectCode)
  371. uni.setStorageSync('addressUrl_'+data.projectCode,res.addressUrl)
  372. uni.setStorageSync('requestImagesPath',res.imgpath)
  373. uni.setStorageSync('sendType',res.sendType)
  374. resolve(res);
  375. }else{
  376. uni.showToast({
  377. title: res.msg,
  378. icon: 'error'
  379. })
  380. }
  381. },
  382. rej => { }
  383. );
  384. });
  385. }
  386. var getConfigKey = function() {
  387. return new Promise((resolve, reject) => {
  388. getConfigByKey({key: 'course.config'}).then(res => {
  389. if (res.code == 200) {
  390. let data = JSON.parse(res.data)
  391. uni.setStorageSync('weixinOauth',data.userCourseAuthDomain)
  392. resolve(data.userCourseAuthDomain)
  393. }
  394. }).catch(error => {
  395. reject(error)
  396. });
  397. });
  398. }
  399. var isLoginCourse=function(){
  400. return new Promise((resolve, reject) => {
  401. let token = uni.getStorageSync('TOKEN_WEXIN');
  402. if (token==null||token==undefined||token=="" ) {
  403. resolve(false);
  404. } else {
  405. resolve(true);
  406. }
  407. });
  408. }
  409. module.exports = {
  410. formatDate:formatDate,
  411. isEmpty : isEmpty,
  412. checkLoginState : checkLoginState,
  413. getDictLabelName:getDictLabelName,
  414. photosToArr:photosToArr,
  415. dateFormat:dateFormat,
  416. getProvider:getProvider,
  417. isLogin:isLogin,
  418. checkToken:checkToken,
  419. loginOut:loginOut,
  420. handleTree:handleTree,
  421. parsePhone:parsePhone,
  422. getAge:getAge,
  423. parseIdCard:parseIdCard,
  424. getDict:getDict,
  425. addHisSearch:addHisSearch,
  426. clearHisSearch:clearHisSearch,
  427. getHisSearch:getHisSearch,
  428. parseTime:parseTime,
  429. setData:setData,
  430. urlToObj:urlToObj,
  431. checkCompanyUserLoginState:checkCompanyUserLoginState,
  432. isLoginCourseAuto:isLoginCourseAuto,
  433. isLoginCourse:isLoginCourse,
  434. generateRandomString:generateRandomString,
  435. getDomain:getDomain,
  436. getConfigKey: getConfigKey,
  437. TOKEN_KEYAuto: TOKEN_KEYAuto
  438. };