沈丘营商办后台前端项目
346149741
2024-06-18 9fb6a0ff49c2af567be2e3adaf93c4c301b3f102
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import axios from "axios";
import WebSockBase from "./websockBase";
import { getToken } from "@/utils/auth";
export enum useType {
  HTML,
  WEB,
  APP,
  LCON, //长连接
}
 
interface TypeSessionObj {
  toUserId: string; //消息接收者id
  userId: string; //消息发送者id
  id: string; //会话id
  [name: string]: string;
}
 
export class WebSockCode extends WebSockBase {
  url: string; //请求地址
  userId: string;
  scrollLing: boolean; //分页节流
  private session = {} as TypeSessionObj;
 
  public get sessionObj(): TypeSessionObj {
    return this.session;
  }
  public set sessionObj(value: TypeSessionObj) {
    // console.log("value=========>", value);
    this.session = value;
  }
 
  public mountMsg = (val: any) => {};
 
  public get msgFnc(): (val: any) => void {
    return this.mountMsg;
  }
  public set msgFnc(value: (val: any) => void) {
    this.mountMsg = value;
  }
  msgDome: HTMLElement | null;
  msgDomeName: string;
  pageNum: number;
  pageSize: number;
  total: number;
 
  constructor(url: string, _usertype: useType, _userId: string, msgDomeName?: string) {
    super();
    this.url = url;
    this.userId = _userId;
    this.pageNum = 1;
    this.pageSize = 15;
    this.total = 0;
    this.msgDome = null;
    this.msgDomeName = msgDomeName || "msgScroll";
    this.scrollLing = true;
  }
 
  /**
   * 拼接sock地址
   */
  public jointUrl = (_lcon = false) => {
    return `${this.url}/websocket/${this.userId}/${!_lcon ? this.sessionObj.userId : "0"}`;
  };
 
  /**
   * 创建长连接
   */
  public settingLong = () => {
    this.createdWebSock(this.jointUrl(true));
    return this.webSock;
  };
 
  /**
   * 获取消息记录
   * @param data
   * @returns
   */
  public getMessages = (type = 0) => {
    return new Promise<any>(async (resolve, reject) => {
      axios({
        url: `http://${this.url}/chat/info/list`,
        method: "get",
        params: {
          toUserId: this.sessionObj.toUserId,
          fromUserId: this.sessionObj.userId,
          pageNum: type == 0 ? this.pageNum : 1,
          pageSize: type == 0 ? this.pageSize : 1,
        },
      })
        .then((res) => {
          if (res.data.code == 200) {
            this.total = res.data.total;
            resolve(res.data.rows);
          } else {
            reject(res.data.msg);
          }
        })
        .catch((e) => {
          reject(e);
        });
    });
  };
 
  /**
   * 获取会话列表
   * @param data
   */
  public getSessions = () => {
    let url = `http://${this.url}/chat/session/myList?toUserId=${this.userId}`;
    return new Promise<any>(async (resolve, reject) => {
      axios
        .get(url)
        .then((res: any) => {
          if (res.data.code == 200) {
            resolve(res.data.rows);
          } else {
            reject(res.data.msg);
          }
        })
        .catch((e) => {
          reject(e);
        });
    });
  };
 
  /**
   * 新增会话
   * @param data
   */
  public addSession = (data: any) => {
    let url = `http://${this.url}/chat/session/add`;
    return new Promise<any>(async (resolve, reject) => {
      axios
        .post(url, data, { headers: { Authorization: "Bearer " + getToken() } })
        .then((res: any) => {
          if (res.data.code == 200) {
            resolve(res.data.data);
          } else {
            reject(res.data.msg);
          }
        })
        .catch((e) => {
          reject(e);
        });
    });
  };
 
  /**
   * 移除会话
   * @param e
   */
  public removeSession = (e: string | number) => {
    let url = `http://${this.url}/chat/session/${e}`;
    return new Promise<any>(async (resolve, reject) => {
      axios
        .delete(url)
        .then((res: any) => {
          if (res.data.code == 200) {
            resolve(res.data.data);
          } else {
            reject(res.data.msg);
          }
        })
        .catch((e) => {
          reject(e);
        });
    });
  };
 
  /**
   * 加载会话详情
   * @returns
   */
  public getSessionInfo = () => {
    let url = `http://${this.url}/chat/session/${this.sessionObj.id}`;
    return new Promise<any>(async (resolve, reject) => {
      axios
        .get(url)
        .then((res: any) => {
          let data = res.data.data;
          resolve(data);
        })
        .catch(() => {
          reject();
        });
    });
  };
 
  /**
   * 创建临时连接
   * @returns
   */
  public CreateTempConnection = () => {
    return new Promise<TypeSessionObj>(async (resolve, reject) => {
      let str = localStorage.getItem("temp");
      if (str) {
        resolve(JSON.parse(str));
      } else {
        axios({
          url: `http://${this.url}/chat/session/addWeb`,
        })
          .then((res: any) => {
            // "data": {
            //   "id": 23,
            //   "userId": 20230421100001,
            //   "toUserId": 2,
            //   "sessionName": "圣商珠宝客服",
            //   "unReadCount": 0,
            //   "delFlag": 0
            // }
            if (res.data.code == 200) {
              let data = res.data.data;
              localStorage.setItem("temp", JSON.stringify(data));
              resolve(data);
            } else {
              reject(res.data);
            }
          })
          .catch((e) => {
            reject(e);
          });
      }
    });
  };
 
  /**
   * 滚动到底部
   */
  public toScrollBottom = () => {
    if (!this.msgDome) {
      this.msgDome = document.getElementById(this.msgDomeName);
    }
    nextTick(() => {
      if (this.msgDome) {
        let scrollHeight = this.msgDome.scrollHeight;
        this.msgDome.scrollTop = scrollHeight;
      }
    });
  };
 
  private scrollHeight = 0; //当前滚动高度
  private scrollTop = 0; //滚动据顶高度
  /**
   * 挂载滚动加载方法
   */
  public mountNextPage = (fnc: (val?: any) => Promise<void>) => {
    if (!this.msgDome) {
      this.msgDome = document.getElementById(this.msgDomeName);
    }
    if (this.msgDome) {
      this.scrollHeight = this.msgDome.scrollHeight;
      nextTick(() => {
        setTimeout(() => {
          this.msgDome!.onscroll = (event: any) => {
            if (this.scrollLing) {
              this.scrollTop = event.target.scrollTop;
              if (this.scrollTop == 0) {
                this.scrollLing = false;
                this.pageNum += 1;
                if (fnc) {
                  fnc()
                    .then(() => {
                      this.scrollToCenter();
                    })
                    .catch(() => {
                      this.scrollLing = false;
                    });
                }
              }
            }
          };
        }, 200);
      });
    }
  };
 
  /**
   * 加载完成后滚动至加载前的位置
   */
  private scrollToCenter = () => {
    setTimeout(() => {
      let _scrollHeight = this.msgDome!.scrollHeight;
      this.msgDome!.scrollTo(0, _scrollHeight - this.scrollHeight - 100);
      this.scrollHeight = _scrollHeight;
      this.scrollLing = true;
    }, 100);
  };
 
  /**
   * 发送消息
   * @param content 消息内容
   */
  public send = (content: string | ArrayBufferLike | Blob | ArrayBufferView) => {
    return new Promise<any>((resolve, reject) => {
      if (this.isConnect()) {
        this.webSock?.send(content);
        let msgObj = {
          content: content,
          createTime: new Date().toLocaleString(),
          fromUserId: this.sessionObj.toUserId,
          toUserId: this.sessionObj.userId,
        };
        resolve(msgObj);
      } else {
        reject("连接异常");
      }
    });
  };
}