queue.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /**
  2. *
  3. * @author maxd
  4. * @date 2019.8.1
  5. */
  6. import configdata from './config'
  7. import cache from './cache'
  8. // #ifdef APP-PLUS
  9. import permision from "../js_sdk/wa-permission/permission.js"
  10. // #endif
  11. function getHost(name) {
  12. const webConfig = cache.get('web_config')
  13. if (webConfig && webConfig[name]) {
  14. return webConfig[name]
  15. }
  16. return configdata[name]
  17. }
  18. module.exports = {
  19. //微信的appId
  20. getWxAppid() {
  21. return 'wxd0bec3a917085e78'
  22. },
  23. //全局邀请码
  24. getInvitation() {
  25. return uni.getStorageSync("publicRelation")
  26. },
  27. //获取APP下载地址
  28. getAppDownUrl() {
  29. return uni.getStorageSync("appurl")
  30. },
  31. //全局域名 部分html中需要单独替换 需要修改config中的网络请求域名
  32. publicYuMing() {
  33. return configdata.h5Url
  34. },
  35. // 登录判断
  36. toLogin(type) {
  37. let url = '/pages/public/loginV2'
  38. switch (type) {
  39. case 'navigateTo':
  40. uni.navigateTo({
  41. url
  42. })
  43. break
  44. default:
  45. uni.reLaunch({
  46. url
  47. })
  48. }
  49. },
  50. logout() {
  51. this.remove("token");
  52. this.remove("userId");
  53. this.remove("mobile");
  54. this.remove("openid");
  55. this.remove("nickName");
  56. this.remove("relation");
  57. this.remove("image_url");
  58. this.remove("relation_id");
  59. this.remove("isInvitation");
  60. this.remove("userType");
  61. this.remove("member");
  62. this.remove('companyId')
  63. this.remove('avatar')
  64. this.remove('age')
  65. this.remove('companyName')
  66. this.remove('companyStatus')
  67. this.remove('isVip')
  68. this.remove('vipMsgNum')
  69. this.remove('vipMsgPrice')
  70. this.remove('vipDueTimes')
  71. this.remove('msgNum')
  72. this.remove('msgPrice')
  73. this.remove('invitationCode')
  74. this.remove('inviterCode')
  75. this.remove('hadShowPoster')
  76. },
  77. loginClear() {
  78. this.remove("token");
  79. this.remove("userId");
  80. this.remove("mobile");
  81. this.remove("nickName");
  82. this.remove("image_url");
  83. this.remove("relation_id");
  84. this.remove("isInvitation");
  85. this.remove("member");
  86. },
  87. showLoading(title) {
  88. uni.showLoading({
  89. title: title
  90. });
  91. },
  92. hideLoading() {
  93. uni.hideLoading();
  94. },
  95. showToast(title) {
  96. uni.showToast({
  97. title: title,
  98. mask: false,
  99. duration: 2000,
  100. icon: "none"
  101. });
  102. },
  103. getChatSearchKeys: function(key) {
  104. let list = uni.getStorageSync("chatSearchKeys");
  105. let keys = key.replace(/\s*/g, "")
  106. let over = false
  107. for (var i = 0; i < keys.length; i++) {
  108. // console.error(keys[i])
  109. if (list.indexOf(keys[i]) != -1) {
  110. over = true;
  111. // return over;
  112. }
  113. }
  114. return over;
  115. },
  116. setJson: function(key, value) {
  117. let jsonString = JSON.stringify(value);
  118. try {
  119. uni.setStorageSync(key, jsonString);
  120. } catch (e) {
  121. // error
  122. }
  123. },
  124. setData: function(key, value) {
  125. try {
  126. uni.setStorageSync(key, value);
  127. } catch (e) {
  128. // error
  129. }
  130. },
  131. getData: function(key) {
  132. try {
  133. const value = uni.getStorageSync(key);
  134. if (value) {
  135. return value;
  136. }
  137. } catch (e) {
  138. // error
  139. }
  140. },
  141. getJson: function(key) {
  142. try {
  143. const value = uni.getStorageSync(key);
  144. if (value) {
  145. return JSON.parse(value);
  146. }
  147. } catch (e) {
  148. // error
  149. }
  150. },
  151. clear: function() {
  152. uni.clearStorage();
  153. },
  154. get: function(key) { //获取队列里面全部的数据
  155. let data = this.getJson(key);
  156. if (data instanceof Array) {
  157. return data;
  158. }
  159. return [];
  160. },
  161. insert: function(param) { //队列插入数据
  162. param.capacityNum = param.capacityNum || 100; //队列容量 默认队列中超过100条数据,自动删除尾部
  163. let data = this.getJson(param.key);
  164. if (data instanceof Array) {
  165. if (data.length > param.capacityNum) {
  166. let total = data.length - param.capacityNum;
  167. for (let i = 0; i < total; i++) {
  168. data.pop();
  169. }
  170. }
  171. data.unshift(param.value);
  172. } else {
  173. data = [];
  174. data.push(param.value);
  175. }
  176. this.setJson(param.key, data);
  177. },
  178. removeItem: function(key, itemIds) { //提供itemIds数组 批量删除队列中的某项数据
  179. let data = this.getJson(key);
  180. if (data instanceof Array) {
  181. for (let i = 0; i < itemIds.length; i++) {
  182. for (let p = 0; p < data.length; p++) {
  183. if (itemIds[i] === data[p].itemid) {
  184. data.splice(p, 1);
  185. break;
  186. }
  187. }
  188. }
  189. this.setJson(key, data);
  190. }
  191. },
  192. isExist: function(key, itemId) { //检测某条数据在队列中是否存在
  193. let data = this.getJson(key);
  194. if (data instanceof Array) {
  195. for (let p = 0; p < data.length; p++) {
  196. if (itemId === data[p].itemid) {
  197. return true;
  198. }
  199. }
  200. }
  201. return false;
  202. },
  203. isExistPdd: function(key, itemId) { //检测某条数据在队列中是否存在
  204. let data = this.getJson(key);
  205. if (data instanceof Array) {
  206. for (let p = 0; p < data.length; p++) {
  207. if (itemId === data[p].goodsId) {
  208. return true;
  209. }
  210. }
  211. }
  212. return false;
  213. },
  214. isExistJd: function(key, itemId) { //检测某条数据在队列中是否存在
  215. let data = this.getJson(key);
  216. if (data instanceof Array) {
  217. for (let p = 0; p < data.length; p++) {
  218. if (itemId === data[p].skuId) {
  219. return true;
  220. }
  221. }
  222. }
  223. return false;
  224. },
  225. remove: function(key) { //删除某条队列
  226. try {
  227. uni.removeStorageSync(key);
  228. //localStorage.removeItem(key)
  229. } catch (e) {
  230. // error
  231. }
  232. },
  233. getCount: function(key) { //获取队列中全部数据数量
  234. let data = this.getJson(key);
  235. if (data instanceof Array) {
  236. return data.length;
  237. }
  238. return 0;
  239. },
  240. uploadFile: function(path, callback) {
  241. const host = getHost('APIHOST1')
  242. const uploadTask = uni.uploadFile({ // 上传接口
  243. url: host + '/alioss/upload', //真实的接口地址
  244. filePath: path,
  245. name: 'file',
  246. success: (uploadFileRes) => {
  247. let content = JSON.parse(uploadFileRes.data).data;
  248. uni.hideLoading();
  249. callback(content)
  250. },
  251. fail: (err) => {
  252. callback(false)
  253. console.log(err)
  254. }
  255. });
  256. uploadTask.onProgressUpdate((res) => {
  257. uni.showLoading({
  258. title: '上传进度' + res.progress + '%',
  259. })
  260. if (res.progress >= 100) {
  261. uni.hideLoading()
  262. }
  263. })
  264. },
  265. /**
  266. * 上传文件
  267. * @param {Object} params 参数
  268. * url:服务器地址
  269. * path:文件本地地址
  270. * name:文件名称
  271. * formData:上传参数
  272. * @param {Object} callback
  273. */
  274. uploadFiles: function(params, callback) {
  275. let url = params.url ? params.url : ''
  276. let filePath = params.path ? params.path : ''
  277. let name = params.name ? params.name : ''
  278. let formData = params.data ? params.data : {}
  279. const host = getHost('APIHOST')
  280. const uploadTask = uni.uploadFile({ // 上传接口
  281. url: `${host}${url}`, //真实的接口地址
  282. filePath,
  283. name,
  284. formData,
  285. header: {
  286. token: uni.getStorageSync('token')
  287. },
  288. timeout: params?.timeout ? params.timeout : 60000,
  289. success: (uploadFileRes) => {
  290. let content = JSON.parse(uploadFileRes.data)
  291. uni.hideLoading();
  292. callback(content)
  293. },
  294. fail: (err) => {
  295. callback(false)
  296. console.log(err)
  297. }
  298. });
  299. if (params?.hideUploadTask) {
  300. return
  301. }
  302. uploadTask.onProgressUpdate((res) => {
  303. uni.showLoading({
  304. title: '上传进度' + res.progress + '%',
  305. })
  306. if (res.progress >= 100) {
  307. uni.hideLoading()
  308. }
  309. })
  310. },
  311. array_column: function(arr, column_key, index_key = null) {
  312. if (index_key === null) {
  313. return arr.map(item => item[column_key]);
  314. }
  315. return arr.reduce((result, item) => {
  316. result[item[index_key]] = item[column_key];
  317. return result;
  318. }, {});
  319. },
  320. isCurrentMonth: function(date) {
  321. const now = new Date();
  322. return now.getFullYear() === date.getFullYear() &&
  323. now.getMonth() === date.getMonth();
  324. },
  325. getHighestEducation: function(educations) {
  326. // 定义学历等级映射(从低到高)
  327. const educationLevels = {
  328. '小学': 1,
  329. '初中': 2,
  330. '高中': 3,
  331. '中专': 4,
  332. '大专': 5,
  333. '本科': 6,
  334. '硕士': 7,
  335. '博士': 8,
  336. '博士后': 9
  337. };
  338. let highestEducation = null;
  339. let highestLevel = -1;
  340. educations.forEach(edu => {
  341. const level = educationLevels[edu.degree] || 0;
  342. if (level > highestLevel) {
  343. highestLevel = level;
  344. highestEducation = edu.degree;
  345. }
  346. });
  347. return highestEducation;
  348. },
  349. //职业状态
  350. resumesStatus() {
  351. return [{
  352. value: '0',
  353. text: '离职-随时到岗',
  354. recommended: true
  355. },
  356. {
  357. value: '1',
  358. text: '在职-月内到岗',
  359. recommended: true
  360. },
  361. {
  362. value: '2',
  363. text: '在职-考虑机会',
  364. recommended: false
  365. },
  366. {
  367. value: '3',
  368. text: '在职-暂不考虑',
  369. recommended: false
  370. },
  371. {
  372. value: '4',
  373. text: '实习',
  374. recommended: false
  375. }
  376. ]
  377. },
  378. appConfirm: function(content = '请确认您的操作?', callback, title = '操作提示', button = ["继续", "取消"]) {
  379. // #ifndef APP-PLUS
  380. uni.showModal({
  381. title: title,
  382. content: content,
  383. success: function(res) {
  384. if (res.confirm) {
  385. callback(true)
  386. } else
  387. callback(false)
  388. }
  389. });
  390. return
  391. //#endif
  392. // #ifdef APP-PLUS
  393. plus.nativeUI.confirm(content, function(e) {
  394. if (e.index == 0)
  395. callback(true)
  396. else
  397. callback(false)
  398. }, title, button);
  399. //#endif
  400. },
  401. isDateExpired: function(targetDate) {
  402. const currentTimestamp = new Date().getTime();
  403. const targetTimestamp = new Date(targetDate).getTime();
  404. const rest = targetTimestamp < currentTimestamp
  405. if (rest)
  406. return [true, 0]
  407. // 计算毫秒差
  408. const diffInMs = targetTimestamp - currentTimestamp;
  409. // 转换为小时(向上取整确保显示完整小时)
  410. const hours = Math.ceil(diffInMs / (1000 * 60 * 60));
  411. return [rest, hours > 0 ? hours : 0]; // 返回非负值
  412. },
  413. convert12to24: function(time12h) {
  414. // 使用正则表达式匹配12小时制格式
  415. const regex = /^(0?[1-9]|1[0-2]):([0-5]\d)\s?(AM|PM)$/i;
  416. const match = time12h.match(regex);
  417. if (!match) {
  418. throw new Error('无效的时间格式,请使用如 "2:00 PM" 或 "02:00 PM" 的格式');
  419. }
  420. let hour = parseInt(match[1], 10);
  421. const minute = match[2];
  422. const period = match[3].toUpperCase();
  423. // 处理AM/PM转换逻辑
  424. if (period === 'PM' && hour !== 12) {
  425. hour += 12;
  426. } else if (period === 'AM' && hour === 12) {
  427. hour = 0;
  428. }
  429. // 格式化为两位数
  430. const hour24 = hour.toString().padStart(2, '0');
  431. return `${hour24}:${minute}`;
  432. },
  433. changeTabbar: function(res) {
  434. setTimeout(() => {
  435. if (res == 1) {
  436. uni.setTabBarItem({
  437. index: 0,
  438. text: '首页',
  439. iconPath: "/static/tabbar/Home.png",
  440. selectedIconPath: "/static/tabbar/Iconly_Bold_Home.png",
  441. })
  442. uni.setTabBarItem({
  443. index: 1,
  444. text: '急聘',
  445. pagePath: "/pages/index/game/gameList",
  446. iconPath: "/static/tabbar/jipin.png",
  447. selectedIconPath: "/static/tabbar/ACjipin.png",
  448. })
  449. } else {
  450. uni.setTabBarItem({
  451. index: 0,
  452. text: '牛人',
  453. iconPath: "/static/tabbar/niu.png",
  454. selectedIconPath: "/static/tabbar/niu2.png",
  455. })
  456. uni.setTabBarItem({
  457. index: 1,
  458. pagePath: "/pages/talentSearch/index",
  459. iconPath: "/static/tabbar/Hrsearch.png",
  460. selectedIconPath: "/static/tabbar/ACsearch.png",
  461. text: "搜索"
  462. })
  463. }
  464. // 可以在这里添加 tabbar 更新后的后续操作
  465. console.log('tabbar 更新完成');
  466. }, 100);
  467. },
  468. // 核心年龄计算函数
  469. calculateAgeFromBirthday: function(birthday) {
  470. const birthDate = new Date(birthday);
  471. const currentDate = new Date();
  472. // 验证日期有效性
  473. if (isNaN(birthDate.getTime())) {
  474. throw new Error('无效的生日日期');
  475. }
  476. if (birthDate > currentDate) {
  477. throw new Error('生日日期不能晚于当前日期');
  478. }
  479. let years = currentDate.getFullYear() - birthDate.getFullYear();
  480. let months = currentDate.getMonth() - birthDate.getMonth();
  481. let days = currentDate.getDate() - birthDate.getDate();
  482. // 处理天数负数情况
  483. if (days < 0) {
  484. months--;
  485. // 获取上个月的天数
  486. const lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0);
  487. days += lastMonth.getDate();
  488. }
  489. // 处理月份负数情况
  490. if (months < 0) {
  491. years--;
  492. months += 12;
  493. }
  494. return years;
  495. },
  496. // 筛选求职列表
  497. getFilterData: function(key = 'filter') {
  498. const condition = {
  499. education: '', //学历
  500. experience: '', //经验
  501. industry: '', //行业
  502. salaryRange: '', //薪资
  503. companyPeople: '' //公司规模
  504. }
  505. //获取选中的筛选条件
  506. if (uni.getStorageSync(key) && (uni.getStorageSync(key)).length > 0) {
  507. let filter = uni.getStorageSync(key)
  508. filter.map(item => {
  509. let arr = []
  510. item.list.map(ite => {
  511. if (ite.value != '不限') {
  512. arr.push(ite.value)
  513. }
  514. })
  515. switch (item.name) {
  516. case '学历要求':
  517. condition.education = arr.join(',')
  518. break;
  519. case '薪资范围(单选)':
  520. condition.salaryRange = arr.join(',')
  521. break;
  522. case '经验要求':
  523. condition.experience = arr.join(',')
  524. break;
  525. case '公司规模':
  526. condition.companyPeople = arr.join(',')
  527. break;
  528. case '行业':
  529. condition.industry = arr.join(',')
  530. break;
  531. }
  532. })
  533. // console.log(filter)
  534. }
  535. return condition
  536. },
  537. //APP获取手机权限鉴权
  538. // APP获取手机权限鉴权(优化版,兼容全权限+多系统)
  539. async checkPermission(permission, tip, that, perpop = 'permission') {
  540. // 权限映射配置
  541. let permisionID = '';
  542. let permisionIosID = '';
  543. return new Promise(async (resolve) => {
  544. // #ifdef H5
  545. resolve(true);
  546. return;
  547. // #endif
  548. const appAuthorizeSetting = uni.getAppAuthorizeSetting()
  549. if (permission == 'location') {
  550. permisionID = 'android.permission.ACCESS_FINE_LOCATION';
  551. permisionIosID = 'location';
  552. if (appAuthorizeSetting.locationAuthorized == 'authorized') {
  553. resolve(true);
  554. return
  555. }
  556. }
  557. if (permission == 'camera') {
  558. permisionID = 'android.permission.CAMERA,android.permission.READ_EXTERNAL_STORAGE';
  559. permisionIosID = 'camera,photoLibrary';
  560. if (appAuthorizeSetting.cameraAuthorized == 'authorized') {
  561. resolve(true);
  562. return
  563. }
  564. }
  565. if (permission == 'microphone') {
  566. permisionID = 'android.permission.RECORD_AUDIO';
  567. permisionIosID = 'record';
  568. if (appAuthorizeSetting.microphoneAuthorized == 'authorized') {
  569. resolve(true);
  570. return
  571. }
  572. }
  573. // 特殊处理:相机权限在非iOS平台显示自定义弹窗
  574. if (uni.getSystemInfoSync().platform != 'ios') {
  575. switch (perpop) {
  576. case 'permission':
  577. that.$refs.permission.open();
  578. break
  579. case 'microphonePermission':
  580. that.$refs.microphonePermission.open();
  581. break
  582. case 'locationPermission':
  583. that.$refs.locationPermission.open();
  584. break
  585. default:
  586. console.warn('未知权限类型:', perpop);
  587. }
  588. }
  589. // Android 平台处理
  590. if (uni.getSystemInfoSync().platform === 'android') {
  591. if (permisionID == '') {
  592. resolve(true);
  593. return;
  594. }
  595. try {
  596. const result = await permision.requestAndroidPermission(permisionID);
  597. console.log(result);
  598. switch (perpop) {
  599. case 'permission':
  600. that.$refs.permission.close();
  601. break
  602. case 'microphonePermission':
  603. that.$refs.microphonePermission.close();
  604. break
  605. case 'locationPermission':
  606. that.$refs.locationPermission.close();
  607. break
  608. default:
  609. console.warn('未知权限类型:', perpop);
  610. }
  611. if (result == 1) {
  612. console.log("已获得授权");
  613. resolve(true);
  614. } else if (result == 0) {
  615. console.log("未获得授权");
  616. resolve(false);
  617. } else {
  618. console.log("权限被拒绝");
  619. // 显示确认对话框
  620. this.appConfirm("权限被拒绝," + tip, function(res) {
  621. if (res) {
  622. uni.openAppAuthorizeSetting();
  623. }
  624. resolve(false);
  625. });
  626. }
  627. } catch (error) {
  628. console.error("权限请求失败:", error);
  629. resolve(false);
  630. }
  631. }
  632. // iOS 平台处理
  633. else {
  634. if (permisionIosID == '') {
  635. resolve(true);
  636. return;
  637. }
  638. const iosPermissions = permisionIosID.split(',');
  639. let allGranted = 0;
  640. for (let i = 0; i < iosPermissions.length; i++) {
  641. const currentPermission = iosPermissions[i];
  642. allGranted = permision.judgeIosPermission(currentPermission);
  643. console.log('权限状态码:', allGranted)
  644. }
  645. if (allGranted == 0) {
  646. console.log('第一次授权')
  647. resolve(true);
  648. } else if (allGranted == 3) {
  649. console.log('已授权')
  650. resolve(true);
  651. } else {
  652. this.appConfirm("权限被拒绝," + tip, function(res) {
  653. if (res) {
  654. uni.openAppAuthorizeSetting();
  655. }
  656. resolve(false);
  657. });
  658. }
  659. }
  660. });
  661. },
  662. appShare(scene, that) {
  663. uni.share({
  664. provider: "weixin", //分享服务提供商(即weixin|qq|sinaweibo)
  665. scene: scene, //场景,可取值参考下面说明。
  666. type: 0, //分享形式 0:图文 1:纯文字 2:纯图片 3:音乐 4:视频 5:小程序
  667. summary: '亿职赞APP新上线,欢迎前来体验',
  668. href: configdata.h5Url + '/pages/index/download',
  669. imageUrl: configdata.h5Url + '/40x40.png',
  670. success: function(res) {
  671. that.shows = false; //成功后关闭底部弹框
  672. },
  673. fail: (err) => {
  674. this.showToast('分享失败')
  675. that.shows = false;
  676. }
  677. });
  678. },
  679. connectSocket() {
  680. let that = this
  681. let userId = this.getData('userId');
  682. const wsHost = getHost('WSHOST1')
  683. if (!userId)
  684. return;
  685. uni.closeSocket()
  686. uni.connectSocket({
  687. url: wsHost + '' + userId,
  688. data() {
  689. return {
  690. msg: 'Hello'
  691. }
  692. },
  693. header: {
  694. 'content-type': 'application/json'
  695. },
  696. method: 'GET',
  697. success(res) {
  698. // 这里是接口调用成功的回调,不是连接成功的回调,请注意
  699. console.log('连接成功', res)
  700. that.onSocketMsg();
  701. },
  702. fail(err) {
  703. console.log('连接失败', res)
  704. // 这里是接口调用失败的回调,不是连接失败的回调,请注意
  705. }
  706. })
  707. },
  708. onSocketMsg() {
  709. let that = this
  710. uni.onSocketMessage((res) => {
  711. if (res.data === 'HeartBeat') return // 忽略心跳包
  712. let msg
  713. try {
  714. msg = JSON.parse(res.data)
  715. } catch (e) {
  716. // console.log('消息不是JSON格式:', res.data)
  717. return
  718. }
  719. if (msg.type === 'kickOut') {
  720. uni.showModal({
  721. title: '提示',
  722. content: msg.content,
  723. showCancel: false,
  724. success() {
  725. that.logout();
  726. // #ifdef H5
  727. uni.reLaunch({
  728. url: '/pages/public/loginphone?type=1'
  729. })
  730. // #endif
  731. // #ifndef H5
  732. uni.reLaunch({
  733. url: '/pages/public/loginV2'
  734. })
  735. // #endif
  736. }
  737. })
  738. }
  739. })
  740. },
  741. sendImMessage(userId, content, messageType, chatConversationId, recordId) {
  742. let data = {
  743. userId,
  744. content,
  745. messageType,
  746. chatConversationId
  747. }
  748. if (recordId) {
  749. data = {
  750. ...data,
  751. recordId
  752. }
  753. }
  754. data = JSON.stringify(data);
  755. return new Promise(async (resolve, reject) => {
  756. uni.sendSocketMessage({
  757. data: data,
  758. success(res) {
  759. resolve(res)
  760. },
  761. fail(err) {
  762. reject(err);
  763. }
  764. })
  765. })
  766. },
  767. /**
  768. * 深合并两个对象:将前一个对象的数据合并到后一个对象(支持嵌套对象)
  769. * @param {Object} sourceObj - 源对象(提供数据的对象,前一个对象)
  770. * @param {Object} targetObj - 目标对象(被合并的对象,后一个对象)
  771. * @returns {Object} 合并后的目标对象
  772. */
  773. deepMergeObject(sourceObj, targetObj) {
  774. // 1. 参数校验
  775. const isValidObj = (obj) => obj !== null && typeof obj === 'object' && !Array.isArray(obj);
  776. if (!isValidObj(sourceObj)) return isValidObj(targetObj) ? targetObj : {};
  777. if (!isValidObj(targetObj)) return JSON.parse(JSON.stringify(sourceObj)); // 简单深拷贝源对象
  778. // 2. 遍历源对象属性
  779. Object.keys(sourceObj).forEach((key) => {
  780. const sourceValue = sourceObj[key];
  781. const targetValue = targetObj[key];
  782. // 3. 处理嵌套对象(递归合并)
  783. if (isValidObj(sourceValue) && isValidObj(targetValue)) {
  784. deepMergeObject(sourceValue, targetValue); // 递归处理嵌套对象
  785. return; // 嵌套对象处理完毕,跳过后续逻辑
  786. }
  787. // 4. 非嵌套对象,按照原规则处理
  788. if (!(key in targetObj) || targetValue === null || targetValue === undefined) {
  789. targetObj[key] = sourceValue;
  790. }
  791. });
  792. return targetObj;
  793. }
  794. };