common.js 13 KB

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