friendStore.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import httpRequest from '../api/httpRequest.js'
  2. import {TERMINAL_TYPE} from "../api/enums.js"
  3. export default {
  4. state: {
  5. friends: [],
  6. activeIndex: -1,
  7. timer: null
  8. },
  9. mutations: {
  10. initFriendStore(state) {
  11. httpRequest({
  12. url: '/friend/list',
  13. method: 'get'
  14. }).then((friends) => {
  15. this.commit("setFriends",friends);
  16. this.commit("refreshOnlineStatus");
  17. })
  18. },
  19. setFriends(state, friends) {
  20. state.friends = friends;
  21. },
  22. updateFriend(state,friend){
  23. state.friends.forEach((f,index)=>{
  24. if(f.id==friend.id){
  25. // 拷贝属性
  26. let online = state.friends[index].online;
  27. Object.assign(state.friends[index], friend);
  28. state.friends[index].online =online;
  29. }
  30. })
  31. },
  32. activeFriend(state, index) {
  33. state.activeIndex = index;
  34. },
  35. removeFriend(state, index) {
  36. state.friends.splice(index, 1);
  37. if(state.activeIndex >= state.friends.length){
  38. state.activeIndex = state.friends.length-1;
  39. }
  40. },
  41. addFriend(state, friend) {
  42. state.friends.push(friend);
  43. },
  44. refreshOnlineStatus(state){
  45. let userIds = [];
  46. if(state.friends.length ==0){
  47. return;
  48. }
  49. state.friends.forEach((f)=>{userIds.push(f.id)});
  50. httpRequest({
  51. url: '/user/terminal/online',
  52. method: 'get',
  53. params: {userIds: userIds.join(',')}
  54. }).then((onlineTerminals) => {
  55. this.commit("setOnlineStatus",onlineTerminals);
  56. })
  57. // 30s后重新拉取
  58. clearTimeout(state.timer);
  59. state.timer = setTimeout(()=>{
  60. this.commit("refreshOnlineStatus");
  61. },30000)
  62. },
  63. setOnlineStatus(state,onlineTerminals){
  64. state.friends.forEach((f)=>{
  65. let userTerminal = onlineTerminals.find((o)=> f.id==o.userId);
  66. if(userTerminal){
  67. f.online = true;
  68. f.onlineTerminals = userTerminal.terminals;
  69. f.onlineWeb = userTerminal.terminals.indexOf(TERMINAL_TYPE.WEB)>=0
  70. f.onlineApp = userTerminal.terminals.indexOf(TERMINAL_TYPE.APP)>=0
  71. }else{
  72. f.online = false;
  73. f.onlineTerminals = [];
  74. f.onlineWeb = false;
  75. f.onlineApp = false;
  76. }
  77. });
  78. let activeFriend = state.friends[state.activeIndex];
  79. state.friends.sort((f1,f2)=>{
  80. if(f1.online&&!f2.online){
  81. return -1;
  82. }
  83. if(f2.online&&!f1.online){
  84. return 1;
  85. }
  86. return 0;
  87. });
  88. console.log(state.friends)
  89. // 重新排序后,activeIndex指向的好友可能会变化,需要重新指定
  90. if(state.activeIndex >=0){
  91. state.friends.forEach((f,i)=>{
  92. if(f.id == activeFriend.id){
  93. state.activeIndex = i;
  94. }
  95. })
  96. }
  97. }
  98. }
  99. }