queue.js 20 KB

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