message_mail_box.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. package service
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. quitl "app.yhyue.com/moapp/jybase/common"
  11. "app.yhyue.com/moapp/jybase/date"
  12. "app.yhyue.com/moapp/jybase/encrypt"
  13. util "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/entity"
  14. IC "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/init"
  15. "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/messagecenter"
  16. "github.com/gogf/gf/v2/util/gconv"
  17. )
  18. type MessaggeService struct{}
  19. // 未读消息查询
  20. func (b MessaggeService) Count(newUserId, userType, entUserId int64, isClean bool) (count int, last map[string]interface{}, err error) {
  21. log.Printf("用户id:%d,userType:%d,entUserId:%d,isClean:%v", newUserId, userType, entUserId, isClean)
  22. v := make([]interface{}, 0)
  23. sqlStr := ""
  24. if userType == 1 {
  25. //查询缓存里边是否有数据
  26. pc_a, err := util.GetData(userType, entUserId)
  27. if err == nil && pc_a != nil {
  28. // 缓存有值
  29. if !isClean {
  30. return pc_a.Count, pc_a.Data, err
  31. }
  32. }
  33. sqlStr = fmt.Sprintf("select count(b.id) from %s a "+
  34. "LEFT JOIN %s b ON a.id=b.own_id "+
  35. "where b.type=5 "+
  36. "AND a.customer_service_id=%d "+
  37. "AND b.iswithdraw = 0 "+
  38. "AND b.isread=0 "+
  39. "AND own_type = 1 "+
  40. "order by create_time", util.SOCIALIZE_CHAT_SESSION, util.SOCIALIZE_MESSAGE_MAILBOX, entUserId)
  41. } else {
  42. pc_a, err := util.GetData(userType, newUserId)
  43. if err == nil && pc_a != nil {
  44. if !isClean {
  45. return pc_a.Count, pc_a.Data, err
  46. }
  47. }
  48. sqlStr = fmt.Sprintf("select count(b.id) from %s b "+
  49. "where b.send_user_id != %d "+
  50. "AND b.own_id=%d "+
  51. "AND b.iswithdraw = 0 "+
  52. "AND b.isread=0 "+
  53. "AND own_type = 2 "+
  54. "order by create_time", util.SOCIALIZE_MESSAGE_MAILBOX, newUserId, newUserId)
  55. }
  56. log.Println(sqlStr, v)
  57. rs := IC.BaseMysql.CountBySql(sqlStr, v...)
  58. log.Println(rs)
  59. count = int(rs)
  60. //最后一条信息查询
  61. sqlStr = fmt.Sprintf("SELECT c.* FROM %s b "+
  62. "LEFT join %s c on b.messag_id=c.id "+
  63. "WHERE b.send_user_id != %d "+
  64. "AND b.own_id = %d "+
  65. "AND b.iswithdraw = 0 "+
  66. "AND b.isread=0 "+
  67. "AND own_type = 2 "+
  68. "ORDER BY create_time DESC "+
  69. "LIMIT 0,1", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE,
  70. newUserId, newUserId)
  71. lastData := IC.BaseMysql.SelectBySql(sqlStr)
  72. if len(*lastData) > 0 {
  73. last = (*lastData)[0]
  74. if userType == 1 {
  75. util.SetData(userType, entUserId, map[string]interface{}{"data": last, "count": count}, IC.SurvivalTime)
  76. } else {
  77. util.SetData(userType, newUserId, map[string]interface{}{"data": last, "count": count}, IC.SurvivalTime)
  78. }
  79. } else {
  80. if userType == 1 {
  81. util.SetData(userType, entUserId, map[string]interface{}{"data": map[string]interface{}{}, "count": count}, IC.SurvivalTime)
  82. } else {
  83. util.SetData(userType, newUserId, map[string]interface{}{"data": map[string]interface{}{}, "count": count}, IC.SurvivalTime)
  84. }
  85. }
  86. return
  87. }
  88. // 用户列表查询
  89. func (b MessaggeService) UserList(in *messagecenter.UserReq) (data *[]map[string]interface{}, count int64, err error) {
  90. sqlStr := ""
  91. tm := time.Now()
  92. if in.UserType == 2 {
  93. //用户最后一次信息查询
  94. userSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM socialize_message_mailbox c "+
  95. "WHERE c.own_id = %d "+
  96. "AND c.iswithdraw = 0 "+
  97. "AND c.type = 2 "+
  98. "AND c.own_type = 2 "+
  99. "GROUP BY ( CASE WHEN c.send_user_id > c.receive_user_id "+
  100. "THEN CONCAT( c.send_user_id, c.receive_user_id ) "+
  101. "WHEN c.send_user_id < c.receive_user_id "+
  102. "THEN CONCAT( c.receive_user_id, c.send_user_id ) END ) ", in.NewUserId,
  103. )
  104. data = IC.BaseMysql.SelectBySql(userSql)
  105. userMessageId := util.Inhandle(data)
  106. //客服最后一次信息查询
  107. customerSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM %s c "+
  108. "LEFT JOIN %s d ON IF ( c.send_user_type = 1, d.id = c.send_user_id, d.id = c.receive_user_id ) "+
  109. "WHERE c.own_id = %d "+
  110. "AND c.iswithdraw = 0 "+
  111. "AND ( c.type = 4 OR c.type = 5 or c.type=6 or c.type=7 ) "+
  112. "AND c.own_type = 2 "+
  113. "AND d.user_id=c.own_id "+
  114. "GROUP BY d.ent_id ", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.NewUserId)
  115. data = IC.BaseMysql.SelectBySql(customerSql)
  116. customerMessageId := util.Inhandle(data)
  117. //用户的列表
  118. sqlStr = fmt.Sprintf("SELECT "+
  119. "( CASE WHEN SUBSTR( b.nickname, 1, 3 ) = 'JY_' THEN CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) WHEN b.nickname = '' or b.nickname is null THEN CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) ELSE b.nickname END )"+
  120. "AS name, b.id, e.title, b.headimg, e.type, e.link, e.content, 2 AS userType, a.create_time, a.type AS itemType, "+
  121. "( SELECT count( h.id ) FROM %s h "+
  122. "WHERE h.type = 2 "+
  123. "AND h.own_id = %d "+
  124. "AND h.own_type = 2 "+
  125. "AND h.send_user_id=b.id "+
  126. "AND h.isread = 0 AND h.iswithdraw = 0 ) AS number FROM %s a "+
  127. "LEFT JOIN %s b ON b.id = a.receive_user_id or b.id = a.send_user_id "+
  128. "LEFT JOIN %s e ON e.id = a.messag_id "+
  129. "WHERE a.id IN ( %s ) AND b.id != %d "+
  130. "UNION ALL "+
  131. "SELECT f.nickname AS name, b.ent_id AS id, e.title,f.headimage AS headimg, e.type, e.link, e.content, 1 AS userType, a.create_time, a.type AS itemType, "+
  132. "( SELECT count( h.id ) FROM %s h WHERE ( h.type = 4 OR h.type = 5 ) AND h.own_id = %d AND h.own_type = 2 AND h.send_user_type = 1 AND h.receive_user_id = %d AND h.isread = 0 ) AS number "+
  133. "FROM %s a "+
  134. "LEFT JOIN %s b ON IF ( a.send_user_type = 1, a.send_user_id, a.receive_user_id ) = b.id "+
  135. "LEFT JOIN %s e ON e.id = a.messag_id "+
  136. "LEFT join %s f on f.ent_id=b.ent_id "+
  137. "WHERE a.id IN ( %s ) "+
  138. "ORDER BY create_time DESC",
  139. util.SOCIALIZE_MESSAGE_MAILBOX,
  140. in.NewUserId,
  141. util.SOCIALIZE_MESSAGE_MAILBOX,
  142. util.BASE_USER,
  143. util.SOCIALIZE_MESSAGE,
  144. userMessageId,
  145. in.NewUserId,
  146. util.SOCIALIZE_MESSAGE_MAILBOX,
  147. in.NewUserId,
  148. in.NewUserId,
  149. util.SOCIALIZE_MESSAGE_MAILBOX,
  150. util.SOCIALIZE_CHAT_SESSION,
  151. util.SOCIALIZE_MESSAGE,
  152. util.SOCIALIZE_TENANT_ROBOT,
  153. customerMessageId)
  154. } else {
  155. idSql := fmt.Sprintf(" (a.customer_service_id = %d OR a.customer_service_id = 0) ", in.EntUserId)
  156. if in.IsArtificial == 1 {
  157. idSql = fmt.Sprintf(" a.customer_service_id = %d ", in.EntUserId)
  158. } else if in.IsArtificial == 2 {
  159. idSql = " a.customer_service_id = 0 "
  160. }
  161. if in.StartTime != "" {
  162. idSql += " AND DATE_FORMAT(a.update_time,'%Y-%m-%d') >= '" + in.StartTime + "' "
  163. }
  164. if in.EndTime != "" {
  165. idSql += "AND DATE_FORMAT(a.update_time,'%Y-%m-%d') <= '" + in.EndTime + "' "
  166. }
  167. if in.Phone != "" {
  168. idSql += " AND b.phone like '%" + in.Phone + "%'"
  169. }
  170. if in.FiltrationId != "" {
  171. var ids []string
  172. for _, v := range strings.Split(in.FiltrationId, ",") {
  173. ids = append(ids, encrypt.SE.Decode4Hex(v))
  174. }
  175. idSql += fmt.Sprintf(" AND b.id not in (%s)", strings.Join(ids, ","))
  176. }
  177. if in.Page <= 0 {
  178. in.Page = 1
  179. }
  180. if in.Size <= 0 || in.Size > 100 {
  181. in.Size = 50
  182. }
  183. sqlStr = fmt.Sprintf(`SELECT(
  184. CASE
  185. WHEN SUBSTR( b.nickname, 1, 3 ) = 'JY_' THEN
  186. CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) )
  187. WHEN b.nickname = ''
  188. OR b.nickname IS NULL THEN
  189. CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) ELSE b.nickname
  190. END
  191. ) AS name,
  192. b.id,
  193. e.title,
  194. b.headimg,
  195. e.type,
  196. e.link,
  197. e.content,
  198. a.update_time as create_time,
  199. (
  200. SELECT
  201. count( h.id )
  202. FROM
  203. %s h
  204. LEFT JOIN %s i ON h.own_id = i.id
  205. WHERE
  206. h.own_type = 1
  207. AND i.ent_id = a.ent_id
  208. AND i.user_id = a.user_id
  209. AND h.isread = 0
  210. AND h.iswithdraw = 0
  211. AND i.customer_service_id = %d
  212. ) AS number
  213. FROM
  214. %s a
  215. INNER JOIN %s b ON a.ent_id = %d and %s
  216. AND a.user_id = b.id
  217. LEFT JOIN %s e ON e.id = a.message_id
  218. ORDER BY
  219. a.update_time DESC`, util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.EntUserId, util.User_message_list, util.BASE_USER, in.EntId, idSql, util.SOCIALIZE_MESSAGE)
  220. }
  221. dataSize := []map[string]interface{}{}
  222. if sqlStr != "" {
  223. log.Println("查询列表sql:", sqlStr)
  224. data = IC.BaseMysql.SelectBySql(sqlStr)
  225. if data != nil && len(*data) > 0 {
  226. count = quitl.Int64All(len(*data))
  227. log.Println("查询列表耗时2:", time.Since(tm), count)
  228. if in.UserType != 2 {
  229. if in.Page*in.Size >= count {
  230. dataSize = (*data)[(in.Page-1)*in.Size:]
  231. } else {
  232. dataSize = (*data)[(in.Page-1)*in.Size : in.Page*in.Size]
  233. }
  234. return &dataSize, count, err
  235. }
  236. }
  237. }
  238. return
  239. }
  240. // 客服会话列表
  241. func (b MessaggeService) ConversationList(in *messagecenter.ConversationReq) (data *[]map[string]interface{}, count int64, err error) {
  242. sqlStr := ""
  243. tm := time.Now()
  244. if in.UserType == 1 && in.FiltrationId != "" {
  245. var ids []string
  246. for _, v := range strings.Split(in.FiltrationId, ",") {
  247. ids = append(ids, encrypt.SE.Decode4Hex(v))
  248. }
  249. idSql := fmt.Sprintf("a.customer_service_id = %d AND b.id in (%s) ", in.EntUserId, strings.Join(ids, ","))
  250. sqlStr = fmt.Sprintf(`SELECT(
  251. CASE
  252. WHEN SUBSTR( b.nickname, 1, 3 ) = 'JY_' THEN
  253. CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) )
  254. WHEN b.nickname = ''
  255. OR b.nickname IS NULL THEN
  256. CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) ELSE b.nickname
  257. END
  258. ) AS name,
  259. b.id,
  260. e.title,
  261. b.headimg,
  262. e.type,
  263. e.link,
  264. e.content,
  265. a.update_time as create_time,
  266. (
  267. SELECT
  268. count( h.id )
  269. FROM
  270. %s h
  271. LEFT JOIN %s i ON h.own_id = i.id
  272. WHERE
  273. h.own_type = 1
  274. AND i.ent_id = a.ent_id
  275. AND i.user_id = a.user_id
  276. AND h.isread = 0
  277. AND h.iswithdraw = 0
  278. AND i.customer_service_id = %d
  279. ) AS number
  280. FROM
  281. %s a
  282. INNER JOIN %s b ON %s
  283. AND a.user_id = b.id
  284. LEFT JOIN %s e ON e.id = a.message_id`,
  285. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.EntUserId, util.User_message_list, util.BASE_USER, idSql, util.SOCIALIZE_MESSAGE)
  286. }
  287. if sqlStr != "" {
  288. log.Println("查询列表sql:", sqlStr)
  289. data = IC.BaseMysql.SelectBySql(sqlStr)
  290. log.Println("查询耗时2:", time.Since(tm), count)
  291. }
  292. return
  293. }
  294. // 消息保存
  295. func (b MessaggeService) SaveMessage(in *messagecenter.MessageEntity) (fool bool, errorMsg string, content string, messageId, nowInt int64) {
  296. //先插入信息表
  297. //判断会话标识是否属于本人
  298. var customer_service_id, userid, entid, message_id int64
  299. nowForm := time.Now().Local()
  300. create_time := nowForm.Format(util.Date_Full_Layout)
  301. if in.ItemType != 2 {
  302. userId := int64(0)
  303. sessionId := int64(0)
  304. switch in.ItemType {
  305. case 4, 5, 8:
  306. if in.OwnType == 1 {
  307. sessionId = in.ReceiveId
  308. userId = in.NewUserId
  309. } else {
  310. sessionId = in.SendId
  311. userId = in.ReceiveId
  312. if in.ItemType == 4 || in.ItemType == 8 {
  313. userId = in.NewUserId
  314. }
  315. }
  316. break
  317. case 6:
  318. if in.OwnType == 1 {
  319. sessionId = in.ReceiveId
  320. userId = in.NewUserId
  321. } else if in.OwnType == 2 {
  322. sessionId = in.SendId
  323. userId = in.ReceiveId
  324. } else {
  325. sessionId = in.ReceiveId
  326. userId = in.NewUserId
  327. }
  328. break
  329. }
  330. //查找会话信息
  331. chatJson := IC.BaseMysql.FindOne(util.SOCIALIZE_CHAT_SESSION, map[string]interface{}{"id": sessionId}, "user_id,ent_id,customer_service_id", "")
  332. if chatJson == nil {
  333. return false, "会话标识不存在", "", 0, nowForm.Unix()
  334. } else {
  335. if userId != quitl.Int64All((*chatJson)["user_id"]) {
  336. return false, "会话标识不属于此用户", "", 0, nowForm.Unix()
  337. }
  338. }
  339. customer_service_id = quitl.Int64All((*chatJson)["customer_service_id"])
  340. entid = quitl.Int64All((*chatJson)["ent_id"])
  341. userid = userId
  342. }
  343. fool = IC.BaseMysql.ExecTx("聊天信息保存", func(tx *sql.Tx) bool {
  344. //先插入信息表
  345. userType := int64(1)
  346. userId := int64(0)
  347. message := map[string]interface{}{
  348. "appid": in.Appid,
  349. "title": in.Title,
  350. "content": in.Content,
  351. "item": in.Item,
  352. "type": in.Type,
  353. "link": in.Link,
  354. "create_time": create_time,
  355. "create_person": in.SendId,
  356. }
  357. data := map[string]interface{}{
  358. "item": in.Item,
  359. "type": in.Type,
  360. "create_time": create_time,
  361. "content": in.Content,
  362. }
  363. ok := IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
  364. receiveOk := int64(0)
  365. messageId, message_id = ok, ok
  366. data["id"] = ok
  367. //在插入邮箱表socialize_message_mailbox
  368. messageMailBox := map[string]interface{}{
  369. "appid": in.Appid,
  370. "messag_id": ok,
  371. "type": in.ItemType,
  372. "create_time": nowForm.Format(util.Date_Full_Layout),
  373. "isread": 0,
  374. "send_isdel": 0,
  375. "receive_isdel": 0,
  376. "iswithdraw": 0,
  377. }
  378. //系统信息处理
  379. if in.ItemType == 6 {
  380. messageMailBox = map[string]interface{}{
  381. "appid": in.Appid,
  382. "messag_id": ok,
  383. "type": in.ItemType,
  384. "create_time": nowForm.Format(util.Date_Full_Layout),
  385. "read_time": nowForm.Format(util.Date_Full_Layout),
  386. "isread": 1,
  387. "send_isdel": 0,
  388. "receive_isdel": 0,
  389. "iswithdraw": 0,
  390. }
  391. if in.OwnType == 1 {
  392. //用户接受系统信息
  393. messageMailBox["own_type"] = 2
  394. messageMailBox["send_user_type"] = 1
  395. messageMailBox["receive_user_type"] = 2
  396. messageMailBox["own_id"] = in.NewUserId
  397. messageMailBox["send_user_id"] = in.ReceiveId
  398. messageMailBox["receive_user_id"] = in.NewUserId
  399. } else if in.OwnType == 2 {
  400. //客服接受系统信息
  401. messageMailBox["own_type"] = 1
  402. messageMailBox["send_user_type"] = 2
  403. messageMailBox["receive_user_type"] = 1
  404. messageMailBox["own_id"] = in.SendId
  405. messageMailBox["send_user_id"] = in.ReceiveId
  406. messageMailBox["receive_user_id"] = in.SendId
  407. } else {
  408. //客服接受系统信息
  409. messageMailBox["own_type"] = 1
  410. messageMailBox["send_user_type"] = 2
  411. messageMailBox["receive_user_type"] = 1
  412. messageMailBox["own_id"] = in.ReceiveId
  413. messageMailBox["send_user_id"] = in.NewUserId
  414. messageMailBox["receive_user_id"] = in.ReceiveId
  415. }
  416. receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  417. return ok > 1 && receiveOk > 1
  418. }
  419. if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
  420. //客服或者机器人聊天
  421. if in.OwnType == 1 {
  422. // (用户发送)客服接受
  423. messageMailBox["own_type"] = 1
  424. messageMailBox["send_user_type"] = 2
  425. messageMailBox["receive_user_type"] = 1
  426. messageMailBox["own_id"] = in.ReceiveId
  427. messageMailBox["send_user_id"] = in.NewUserId
  428. messageMailBox["receive_user_id"] = in.ReceiveId
  429. userType = 1
  430. userId = in.ReceiveId
  431. } else {
  432. //客服发送(用户接收信息)
  433. messageMailBox["own_type"] = 2
  434. messageMailBox["send_user_type"] = 1
  435. messageMailBox["receive_user_type"] = 2
  436. messageMailBox["own_id"] = in.ReceiveId
  437. messageMailBox["send_user_id"] = in.SendId
  438. messageMailBox["receive_user_id"] = in.ReceiveId
  439. userId = in.ReceiveId
  440. if in.ItemType == 4 || in.ItemType == 8 {
  441. messageMailBox["receive_user_id"] = in.NewUserId
  442. userId = in.NewUserId
  443. messageMailBox["own_id"] = in.NewUserId
  444. messageMailBox["isread"] = 1
  445. messageMailBox["read_time"] = nowForm.Format(util.Date_Full_Layout)
  446. }
  447. userType = 2
  448. }
  449. } else {
  450. messageMailBox["own_type"] = 2
  451. messageMailBox["send_user_type"] = 2
  452. messageMailBox["receive_user_type"] = 2
  453. messageMailBox["own_id"] = in.ReceiveId
  454. messageMailBox["send_user_id"] = in.NewUserId
  455. messageMailBox["receive_user_id"] = in.ReceiveId
  456. userType = 2
  457. userId = in.ReceiveId
  458. }
  459. receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  460. messageMailBox = map[string]interface{}{
  461. "appid": in.Appid,
  462. "messag_id": ok,
  463. "type": in.ItemType,
  464. "create_time": nowForm.Format(util.Date_Full_Layout),
  465. "read_time": nowForm.Format(util.Date_Full_Layout),
  466. "isread": 1,
  467. "send_isdel": 0,
  468. "receive_isdel": 0,
  469. "iswithdraw": 0,
  470. }
  471. if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
  472. //客服或者机器人聊天
  473. if in.OwnType == 1 {
  474. //用户发送(用户接受)
  475. messageMailBox["own_type"] = 2
  476. messageMailBox["send_user_type"] = 2
  477. messageMailBox["receive_user_type"] = 1
  478. messageMailBox["own_id"] = in.NewUserId
  479. messageMailBox["send_user_id"] = in.NewUserId
  480. messageMailBox["receive_user_id"] = in.ReceiveId
  481. } else {
  482. //客服发送信息(用户接受)
  483. messageMailBox["own_type"] = 1
  484. messageMailBox["send_user_type"] = 1
  485. messageMailBox["receive_user_type"] = 2
  486. messageMailBox["own_id"] = in.SendId
  487. messageMailBox["send_user_id"] = in.SendId
  488. messageMailBox["receive_user_id"] = in.ReceiveId
  489. if in.ItemType == 4 || in.ItemType == 8 {
  490. messageMailBox["receive_user_id"] = in.NewUserId
  491. }
  492. }
  493. } else {
  494. messageMailBox["own_type"] = 2
  495. messageMailBox["send_user_type"] = 2
  496. messageMailBox["receive_user_type"] = 2
  497. messageMailBox["own_id"] = in.NewUserId
  498. messageMailBox["send_user_id"] = in.NewUserId
  499. messageMailBox["receive_user_id"] = in.ReceiveId
  500. }
  501. receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  502. if ok > 1 && receiveOk > 1 {
  503. pc_a, err := util.GetData(userType, userId)
  504. count := 1
  505. if err == nil && pc_a != nil {
  506. count += pc_a.Count
  507. }
  508. util.SetData(userType, userId, map[string]interface{}{"data": data, "count": count}, IC.SurvivalTime)
  509. }
  510. return ok > 1 && receiveOk > 1
  511. })
  512. if fool && in.ItemType != 2 && in.ItemType != 3 {
  513. go UserSynchronousList(customer_service_id, userid, entid, message_id, create_time)
  514. }
  515. return fool, "", in.Content, messageId, nowForm.Unix()
  516. }
  517. var rwLock = new(sync.RWMutex)
  518. // 客服 用户聊天消息列表同步
  519. func UserSynchronousList(customerServiceId, userId, entId, messageId int64, createTime string) {
  520. log.Printf("同步最后消息参数customerServiceId:%d,userId:%d,entId%d,messageId:%d", customerServiceId, userId, entId, messageId)
  521. rwLock.Lock()
  522. defer rwLock.Unlock()
  523. if IC.BaseMysql.Count(util.User_message_list, map[string]interface{}{"user_id": userId, "ent_id": entId}) > 0 {
  524. upData := map[string]interface{}{
  525. "message_id": messageId,
  526. "update_time": createTime,
  527. }
  528. //判断是否机器人聊天
  529. if customerServiceId > 0 && IC.BaseMysql.Count(util.User_message_list, map[string]interface{}{"user_id": userId, "ent_id": entId, "customer_service_id": 0}) > 0 {
  530. //将机器人列表更新成用户
  531. upData["customer_service_id"] = customerServiceId
  532. //转人工 机器人聊天类型修改
  533. upData["type"] = 1
  534. }
  535. //已于人工客服联系过 只同步最后消息
  536. IC.BaseMysql.Update(util.User_message_list, map[string]interface{}{"user_id": userId, "ent_id": entId}, upData)
  537. return
  538. }
  539. //不存在消息列表 创建
  540. IC.BaseMysql.Insert(util.User_message_list, map[string]interface{}{
  541. "ent_id": entId,
  542. "user_id": userId,
  543. "message_id": messageId,
  544. "update_time": createTime,
  545. "customer_service_id": customerServiceId,
  546. "type": quitl.If(customerServiceId == 0, 0, 1),
  547. })
  548. }
  549. // 历史信息查询
  550. func (b MessaggeService) FindMessage(in *messagecenter.MessageReq) *[]map[string]interface{} {
  551. sqlStr := ""
  552. lastStr := ""
  553. positionStr := ""
  554. if in.LastId > 0 {
  555. if in.Sort == "asc" {
  556. lastStr = fmt.Sprintf("AND a.messag_id > %d ", in.LastId)
  557. } else {
  558. lastStr = fmt.Sprintf("AND a.messag_id < %d ", in.LastId)
  559. }
  560. }
  561. switch in.MsgType {
  562. case 2: //点对点聊天
  563. sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,b.* ,if(a.own_id = a.send_user_id,1,2) as fool "+
  564. "FROM %s a "+
  565. "LEFT JOIN %s b on a.messag_id=b.id "+
  566. "LEFT JOIN %s c on c.id=a.send_user_id "+
  567. "LEFT JOIN %s d on d.id=a.receive_user_id "+
  568. "where a.own_id= %d and a.iswithdraw = 0"+
  569. "AND ((a.send_user_id= %d AND a.receive_user_id= %d) or (a.send_user_id= %d AND a.receive_user_id= %d)) "+
  570. "AND a.type=2 %s "+
  571. "ORDER BY a.create_time desc,a.id asc "+
  572. "limit 0 , %d ",
  573. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.BASE_USER, util.BASE_USER,
  574. in.NewUserId, in.NewUserId, in.SendId, in.SendId, in.NewUserId, lastStr, in.PageSize)
  575. break
  576. case 3: //群聊天
  577. sqlStr = fmt.Sprintf("SELECT a.messag_id AS messageId,b.*,"+
  578. "IF ( a.own_id = a.send_user_id, 1, 2 ) AS fool,"+
  579. "IF ( a.own_id = a.send_user_id, 0, a.send_user_id ) AS send_position_id,"+
  580. "a.send_user_type,a.type AS itemType FROM %s a "+
  581. "LEFT JOIN %s b ON a.messag_id = b.id "+
  582. "WHERE a.own_type = 1 AND a.own_id = %d "+
  583. "AND chat_group_id = %d AND a.type IN ( 3, 6 ) "+
  584. "ORDER BY a.create_time desc,a.id DESC "+
  585. "LIMIT 0, %d",
  586. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, in.SendId,
  587. in.ChatGroupId, in.PageSize)
  588. case 4, 5, 6, 7: //客服聊天
  589. //查询用户所有的职位id
  590. sqlPosition := fmt.Sprintf("SELECT b.id FROM %s a LEFT JOIN %s b ON a.id = b.user_id "+
  591. "WHERE a.phone = (SELECT a.phone FROM %s a LEFT JOIN %s b ON a.id = b.user_id "+
  592. "WHERE b.id = %d)",
  593. util.BASE_USER, util.BASE_POSITION, util.BASE_USER, util.BASE_POSITION, in.NewUserId)
  594. positionArr := IC.BaseMysql.SelectBySql(sqlPosition)
  595. for k, val := range *positionArr {
  596. if k < len(*positionArr)-1 {
  597. positionStr += quitl.ObjToString(val["id"]) + ","
  598. } else {
  599. positionStr += quitl.ObjToString(val["id"])
  600. }
  601. }
  602. if in.UserType == 1 {
  603. //客服聊天记录查看
  604. sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,b.*, IF ( a.own_id = a.send_user_id, 1, 2 ) AS fool, a.send_user_type, a.type AS itemType, '' AS robotName, '' AS robotImg, c.customer_service_name AS setName , c.user_id "+
  605. "FROM %s a "+
  606. "LEFT JOIN %s b ON a.messag_id = b.id "+
  607. "LEFT JOIN %s c ON a.own_type = 1 AND a.own_id=c.id "+
  608. "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
  609. "AND (a.type = 5 or a.type=4 or a.type=6 or a.type=7 or a.type=8 ) "+
  610. "AND c.ent_id = %d "+
  611. "AND c.user_id in (%s) %s "+
  612. "ORDER BY a.create_time desc ,a.id asc "+
  613. "limit 0 , %d ",
  614. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION,
  615. in.EntId, positionStr, lastStr, in.PageSize)
  616. } else {
  617. //用户聊天记录查看
  618. sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,e.appraise as appraise, b.*, IF ( a.own_id = a.send_user_id, 1, 2 ) AS fool , a.send_user_type, a.type as itemType, d.nickname as robotName, d.headimage as robotImg, c.customer_service_name as setName "+
  619. "FROM %s a "+
  620. "LEFT JOIN %s b ON a.messag_id = b.id "+
  621. "LEFT JOIN %s c ON IF ( a.send_user_type = 1, a.send_user_id, a.receive_user_id ) = c.id AND c.ent_id = %d AND c.user_id = %d "+
  622. "LEFT JOIN %s d on c.ent_id=d.ent_id "+
  623. "WHERE a.own_type = 2 "+
  624. "AND a.own_id in (%s) "+
  625. "AND c.ent_id = %d "+
  626. "AND c.user_id in (%s) "+
  627. "AND ( a.type = 4 OR a.type = 5 or a.type=6 or a.type=7) %s "+
  628. "ORDER BY a.create_time desc ,a.id asc "+
  629. "limit 0 , %d ",
  630. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, in.SendId, in.NewUserId, util.SOCIALIZE_TENANT_ROBOT,
  631. positionStr, in.SendId, positionStr, lastStr, in.PageSize)
  632. }
  633. break
  634. }
  635. log.Println(sqlStr)
  636. data := IC.BaseMysql.SelectBySql(sqlStr)
  637. //查询非自己发送消息得发送人名字
  638. //自己头像处理
  639. if in.UserType == 2 {
  640. userData := IC.BaseMysql.FindOne(util.BASE_USER, map[string]interface{}{"id": in.NewUserId}, "headimg", "")
  641. if userData != nil {
  642. for key := range *data {
  643. (*data)[key]["ownImg"] = (*userData)["headimg"]
  644. }
  645. }
  646. }
  647. if in.MsgType == 3 && data != nil && len(*data) > 0 {
  648. _, _, positionData := EntPerson(in.EntId, true)
  649. for _, v := range *data {
  650. positionId := quitl.IntAll(v["send_user_id"])
  651. if positionId != 0 {
  652. v["userName"] = positionData[positionId]
  653. }
  654. }
  655. }
  656. go func() {
  657. updateMap := map[string]interface{}{}
  658. if len(*data) > 0 && data != nil {
  659. //if true {
  660. //未读信息修改
  661. switch in.MsgType {
  662. case 2: //点对点聊天
  663. updateMap = map[string]interface{}{
  664. "own_type": 2,
  665. "own_id": in.NewUserId,
  666. "send_user_id": in.SendId,
  667. "type": 2,
  668. "isread": 0,
  669. }
  670. IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"isread": 1, "read_time": time.Now().Local().Format(util.Date_Full_Layout)})
  671. break
  672. case 3: //群聊天
  673. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  674. "WHERE a.own_type = 1 "+
  675. "AND a.type IN (3,6) "+
  676. "AND a.isread = 0 "+
  677. "AND a.own_id = %d AND a.chat_group_id = %d",
  678. util.SOCIALIZE_MESSAGE_MAILBOX, in.SendId, in.ChatGroupId)
  679. case 4, 5: //UserType 2用户1客服
  680. sqlStr := ""
  681. if in.UserType == 1 {
  682. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  683. "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
  684. "AND a.type IN ( 4,5,6,7) "+
  685. "AND a.isread = 0 "+
  686. "AND a.own_id IN ( SELECT b.id FROM %s b WHERE b.customer_service_id=%d AND b.user_id in (%s) )",
  687. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.EntUserId, positionStr)
  688. } else {
  689. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  690. "WHERE a.own_type = 2 and a.iswithdraw = 0 "+
  691. "AND a.type IN ( 4,5,6,7 ) "+
  692. "AND a.isread = 0 "+
  693. "AND a.own_id in (%s) ", util.SOCIALIZE_MESSAGE_MAILBOX, positionStr)
  694. }
  695. IC.BaseMysql.UpdateOrDeleteBySql(sqlStr)
  696. break
  697. }
  698. //redis缓存处理
  699. //b.Count(in.NewUserId, in.UserType, in.EntUserId, true)
  700. }
  701. }()
  702. return data
  703. }
  704. // 创建会话
  705. func (b MessaggeService) CreateChatSession(in *messagecenter.ChatSessionReq) (fool bool, sessionId int64) {
  706. fool = IC.BaseMysql.ExecTx("会话新建", func(tx *sql.Tx) bool {
  707. customerserviceName := in.CustomerserviceName
  708. if in.CustomerServiceId != 0 {
  709. sqlStr := fmt.Sprintf("select customer_service_name from %s "+
  710. "where ent_id= %d "+
  711. "AND customer_service_id= %d ",
  712. util.SOCIALIZE_CHAT_SESSION, in.EntId, in.CustomerServiceId)
  713. customerList := IC.BaseMysql.SelectBySql(sqlStr)
  714. if len(*customerList) > 0 {
  715. customerserviceName = quitl.InterfaceToStr((*customerList)[0]["customer_service_name"])
  716. }
  717. }
  718. //查询企业是否存在
  719. count := IC.BaseMysql.Count(util.SOCIALIZE_TENANT_ROBOT, map[string]interface{}{
  720. "ent_id": in.EntId,
  721. })
  722. if count < 1 {
  723. return false
  724. }
  725. chatMession := map[string]interface{}{
  726. "handle_status": 0,
  727. "start_time": time.Now().Local().Format(util.Date_Full_Layout),
  728. "appid": in.AppId,
  729. "ent_id": in.EntId,
  730. "customer_service_id": in.CustomerServiceId,
  731. "user_id": in.UserId,
  732. "customer_service_name": customerserviceName,
  733. }
  734. sessionId = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_CHAT_SESSION, chatMession)
  735. return sessionId > 0
  736. })
  737. return
  738. }
  739. // 结束会话
  740. func (b MessaggeService) CloseChatSession(in *messagecenter.CloseSessionReq) bool {
  741. fool := IC.BaseMysql.ExecTx("关闭会话", func(tx *sql.Tx) bool {
  742. updateMap := map[string]interface{}{
  743. "id": in.SessionId,
  744. }
  745. fool := IC.BaseMysql.Update(util.SOCIALIZE_CHAT_SESSION, updateMap, map[string]interface{}{"start_time": time.Now().Local().Format(util.Date_Full_Layout)})
  746. return fool
  747. })
  748. return fool
  749. }
  750. // 创建会话并保存信息
  751. func (b *MessaggeService) SaveAutoReplyMsg(userType, entId, entUserId, userId int64, content, appId, nowFormat string) (bool, int64) {
  752. var customer_service_id, userid, entid, message_id int64
  753. messageId := int64(0)
  754. ok1 := IC.BaseMysql.ExecTx("保存自动回复消息", func(tx *sql.Tx) bool {
  755. entUserName := ""
  756. if entUserId > 0 {
  757. list := IC.BaseMysql.SelectBySql(`select ? from socialize_tenant_seat where appid=? AND ent_id=? AND customer_service_id=?`, util.SOCIALIZE_CHAT_SESSION, appId, entId, entUserId)
  758. if list != nil && len(*list) > 0 {
  759. entUserName, _ = (*list)[0]["customer_service_name"].(string)
  760. }
  761. }
  762. messageId = IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message (appid,content,item,type,create_time,create_person) values (?,?,?,?,?,?)`, appId, content, 8, 1, nowFormat, "admin")
  763. sessionId := IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_chat_session (appid,type,ent_id,customer_service_id,customer_service_name,user_id,start_time,end_time) values (?,?,?,?,?,?,?,?)`, appId, 1, entId, entUserId, entUserName, userId, nowFormat, nowFormat)
  764. ok := false
  765. if userType == 0 {
  766. ok1 := IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time,isread,read_time) values (?,?,?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, sessionId, 1, nowFormat, 1, nowFormat) > 0
  767. ok2 := IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time) values (?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, userId, 2, nowFormat) > 0
  768. ok = ok1 && ok2
  769. } else if userType == 1 {
  770. ok = IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time,isread,read_time) values (?,?,?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, sessionId, 1, nowFormat, 1, nowFormat) > 0
  771. } else if userType == 2 {
  772. ok = IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time) values (?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, userId, 2, nowFormat) > 0
  773. }
  774. message_id = messageId
  775. return messageId > 0 && sessionId > 0 && ok
  776. })
  777. if ok1 {
  778. customer_service_id = entUserId
  779. userid = userId
  780. entid = entId
  781. go UserSynchronousList(customer_service_id, userid, entid, message_id, nowFormat)
  782. }
  783. return ok1, messageId
  784. }
  785. // 修改未读状态
  786. func (b MessaggeService) UpdateReadById(in *messagecenter.ReadStateReq) bool {
  787. fool := IC.BaseMysql.ExecTx("已读状态修改", func(tx *sql.Tx) bool {
  788. updateMap := map[string]interface{}{
  789. "messag_id": in.MessageId,
  790. "isread": 0,
  791. }
  792. fool := IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"read_time": time.Now().Local().Format(util.Date_Full_Layout), "isread": 1})
  793. if fool {
  794. //查询此条信息拥有者
  795. data := IC.BaseMysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, "receive_user_type", "")
  796. if data != nil {
  797. userType := int64(1)
  798. userId := int64(0)
  799. if (*data)["receive_user_type"] == 2 {
  800. userType = 2
  801. userId = in.EntUserId
  802. } else {
  803. userType = 1
  804. userId = in.NewUserId
  805. }
  806. pc_a, err := util.GetData(userType, userId)
  807. if fool {
  808. if err == nil && pc_a != nil {
  809. //id一致
  810. if in.MessageId == pc_a.Data["id"] {
  811. util.SetData(userType, userId, map[string]interface{}{"data": map[string]interface{}{}, "count": pc_a.Count - 1}, IC.SurvivalTime)
  812. } else {
  813. util.SetData(userType, userId, map[string]interface{}{"data": data, "count": pc_a.Count - 1}, IC.SurvivalTime)
  814. }
  815. }
  816. }
  817. }
  818. }
  819. return fool
  820. })
  821. return fool
  822. }
  823. // WithdrawMessage 撤回消息
  824. func (b MessaggeService) WithdrawMessage(in *messagecenter.ReadWithdrawReq) bool {
  825. messageId := encrypt.SE.Decode4Hex(in.MessageId)
  826. newUserId, entUserId := NewEndId(quitl.Int64All(messageId), in.UserType)
  827. msg := IC.BaseMysql.FindOne(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId}, "create_time", "")
  828. if msg == nil || len(*msg) <= 0 {
  829. log.Println("查询消息id失败")
  830. return false
  831. }
  832. createTime, _ := time.Parse(util.Date_Full_Layout, quitl.InterfaceToStr((*msg)["create_time"]))
  833. if createTime.Unix()+60*2 < time.Now().Unix() {
  834. log.Println("消息已超过2分钟,撤回失败")
  835. return false
  836. }
  837. nowForm := time.Now().Local()
  838. m := IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX,
  839. map[string]interface{}{"messag_id": messageId}, map[string]interface{}{"iswithdraw": 1, "withdraw_time": nowForm.Format(util.Date_Full_Layout)})
  840. if m {
  841. //消息撤回 更新对方私信
  842. in.UserType = quitl.Int64All(quitl.If(in.UserType == 1, 2, 1))
  843. b.Count(newUserId, in.UserType, entUserId, true)
  844. }
  845. return m
  846. }
  847. // AppraiseMessage 消息评价
  848. func (b MessaggeService) AppraiseMessage(in *messagecenter.AppraiseReq) error {
  849. messageId := encrypt.SE.Decode4Hex(in.MessageId)
  850. //查询此条消息是否是当前用户的
  851. if IC.BaseMysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{
  852. "messag_id": messageId,
  853. "receive_user_id": in.NewUserId,
  854. "receive_user_type": 2,
  855. "type": 8,
  856. }) == 0 {
  857. return fmt.Errorf("未查询到信息")
  858. }
  859. if IC.BaseMysql.Count(util.SOCIALIZE_APPRAISE, map[string]interface{}{
  860. "appid": in.Appid,
  861. "messag_id": messageId,
  862. }) > 0 {
  863. return fmt.Errorf("请勿重复评价")
  864. }
  865. //插入评价
  866. if IC.BaseMysql.Insert(util.SOCIALIZE_APPRAISE, map[string]interface{}{
  867. "appid": in.Appid,
  868. "messag_id": messageId,
  869. "create_time": time.Now().Local().Format(util.Date_Full_Layout),
  870. "appraise": in.Appraise,
  871. }) > 0 {
  872. return nil
  873. }
  874. return fmt.Errorf("评价消息异常")
  875. }
  876. // NewEndId 消息撤回 获取对方userid
  877. func NewEndId(messageId, iType int64) (newUserId, entUserId int64) {
  878. data := IC.BaseMysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{"messag_id": messageId, "own_type": iType}, "", "")
  879. if data != nil && len(*data) > 0 {
  880. if iType == 1 { //客服撤回消息 获取客服id与用户id
  881. entUserId = quitl.Int64All((*data)["send_user_id"])
  882. newUserId = quitl.Int64All((*data)["receive_user_id"])
  883. } else {
  884. //用户撤回消息 获取客服id与用户id
  885. newUserId = quitl.Int64All((*data)["send_user_id"])
  886. entUserId = quitl.Int64All((*data)["receive_user_id"])
  887. }
  888. }
  889. return
  890. }
  891. // 聊天
  892. // 包含 1v1 ,群聊,群发
  893. /*
  894. 入参 appid,title,content,sendid,link,item,messagetype,receiverIds,groupIds
  895. */
  896. func (this *MessaggeService) Chat(in *messagecenter.MessageSaveReq) bool {
  897. return IC.BaseMysql.ExecTx("消息存储", func(tx *sql.Tx) bool {
  898. nowTime := time.Now().Format(date.Date_Full_Layout)
  899. isGroup := len(in.GroupIds) > 0
  900. isOneToOne := len(in.ReceiverIds) > 0
  901. createperson := strconv.Itoa(int(in.SendId))
  902. messageId := MessageAdd(tx, in.Appid, in.Title, in.Content, createperson, in.Link, in.Item, in.MessageType)
  903. //是否客服介入
  904. isCustomerServiceAccess := 0
  905. //群聊
  906. if isGroup {
  907. fieids := []string{"appid", "messag_id", "type", "send_user_id", "send_user_type", "receive_user_id", "receive_user_type", "own_type", "own_id", "create_time", "chat_group_id", "isread"}
  908. for _, v := range in.GroupIds {
  909. args := []interface{}{}
  910. summaryArgs := []interface{}{}
  911. args = append(args, in.Appid, messageId, in.Type, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, v, 1)
  912. groupUser := GetUserByGroupId(tx, v, in.SendId)
  913. for _, vv := range groupUser {
  914. log.Println("获取到群组下员工:", vv)
  915. args = append(args, in.Appid, messageId, in.Type, in.SendId, 2, vv, 2, 2, vv, nowTime, v, 0)
  916. }
  917. summaryArgs = append(summaryArgs, in.SendId, nil, nil, v, messageId, nil, isCustomerServiceAccess, nowTime)
  918. MessageMailBoxAdd(tx, fieids, args)
  919. //最后一次聊天
  920. SocializeSummaryAdd(tx, summaryArgs)
  921. //更新未读消息
  922. GroupUserUnReadUpdate(tx, groupUser)
  923. }
  924. }
  925. //1v1
  926. if isOneToOne {
  927. fieids := []string{"appid", "messag_id", "type", "send_user_id", "send_user_type", "receive_user_id", "receive_user_type", "own_type", "own_id", "create_time", "isread"}
  928. args := []interface{}{}
  929. summaryArgs := []interface{}{}
  930. args = append(args, in.Appid, messageId, in.Type, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, 1)
  931. for _, v := range in.ReceiverIds {
  932. args = append(args, in.Appid, messageId, in.Type, in.SendId, 2, v, 2, 2, v, nowTime, 0)
  933. //发送方,未读消息应该是0
  934. summaryArgs = append(summaryArgs, in.SendId, v, nil, nil, messageId, 0, isCustomerServiceAccess, nowTime)
  935. //接收方,未读消息应该是1
  936. summaryArgs = append(summaryArgs, v, in.SendId, nil, nil, messageId, 1, isCustomerServiceAccess, nowTime)
  937. }
  938. MessageMailBoxAdd(tx, fieids, args)
  939. //最后一次聊天
  940. SocializeSummaryAdd(tx, summaryArgs)
  941. }
  942. return true
  943. })
  944. }
  945. // 消息存储
  946. func MessageAdd(tx *sql.Tx, appid, title, content, createperson, link string, item, messageType int64) int64 {
  947. nowTime := time.Now()
  948. message := map[string]interface{}{
  949. "appid": appid,
  950. "title": title,
  951. "content": content,
  952. "item": item,
  953. "type": messageType,
  954. "link": link,
  955. "create_time": nowTime.Format(date.Date_Full_Layout),
  956. "create_person": createperson, //系统消息时,创建人是群聊id或接收人id
  957. }
  958. return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
  959. }
  960. // 消息信息箱存储
  961. // types 2:点对点 3:群消息
  962. func MessageMailBoxAdd(tx *sql.Tx, fieids []string, args []interface{}) (int64, int64) {
  963. length, lastId := IC.BaseMysql.InsertBatchByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, fieids, args)
  964. log.Println("MessageMailBoxAdd length:", length, "MessageMailBoxAdd lastId:", lastId)
  965. return length, lastId
  966. }
  967. // 获取除发送人以外的群成员
  968. func GetUserByGroupId(tx *sql.Tx, groupId, sendId int64) []int64 {
  969. arr := []int64{}
  970. data := IC.BaseMysql.SelectBySqlByTx(tx, "select position_id from "+util.SOCIALIZE_CHAT_GROUP_PERSON+" where status = 1 and chat_group_id = ? AND position_id != ? ", groupId, sendId)
  971. log.Println("~~~~", data)
  972. if data == nil || len(*data) <= 0 {
  973. return arr
  974. }
  975. for _, v := range *data {
  976. position_id := quitl.Int64All(v["position_id"])
  977. if position_id == 0 {
  978. continue
  979. }
  980. arr = append(arr, position_id)
  981. }
  982. return arr
  983. }
  984. //最后一次聊天存储
  985. func SocializeSummaryAdd(tx *sql.Tx, args []interface{}) (int64, int64) {
  986. fieids := []string{"my_position_id", "your_position_id", "ent_id", "chat_group_id", "message_id", "unread", "customer_service_access", "timestamp"}
  987. length, lastId := IC.BaseMysql.InsertBatchByTx(tx, util.SOCIALIZE_SUMMARY, fieids, args)
  988. log.Println("SocializeSummaryAdd length:", length, "SocializeSummaryAdd lastId:", lastId)
  989. return length, lastId
  990. }
  991. //群组人员未读消息更新
  992. func GroupUserUnReadUpdate(tx *sql.Tx, ids []int64) bool {
  993. whs := []string{}
  994. for i := 0; i < len(ids); i++ {
  995. whs = append(whs, "?")
  996. }
  997. wh := strings.Join(whs, ",")
  998. interfaces := gconv.Interfaces(ids)
  999. count := IC.BaseMysql.UpdateOrDeleteBySql(`UPDATE `+util.SOCIALIZE_CHAT_GROUP_PERSON+` SET unread = unread + 1 WHERE id in (`+wh+`)`, interfaces...)
  1000. if count > 0 {
  1001. return true
  1002. }
  1003. return true
  1004. }