package service import ( quitl "app.yhyue.com/moapp/jybase/common" "app.yhyue.com/moapp/jybase/encrypt" util "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/entity" "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/messagecenter" "database/sql" "fmt" "log" "time" ) type MessaggeService struct{} // 未读消息查询 func (b MessaggeService) Count(newUserId, userType, entUserId int64, isClean bool) (count int, last map[string]interface{}, err error) { log.Printf("用户id:%d,userType:%d,entUserId:%d,isClean:%v", newUserId, userType, entUserId, isClean) v := make([]interface{}, 0) sqlStr := "" if userType == 1 { //查询缓存里边是否有数据 pc_a, err := util.GetData(userType, entUserId) if err == nil && pc_a != nil { // 缓存有值 if !isClean { return pc_a.Count, pc_a.Data, err } } sqlStr = fmt.Sprintf("select count(b.id) from %s a "+ "LEFT JOIN %s b ON a.id=b.own_id "+ "where b.type=5 "+ "AND a.customer_service_id=%d "+ "AND b.iswithdraw = 0 "+ "AND b.isread=0 "+ "AND own_type = 1 "+ "order by create_time", util.SOCIALIZE_CHAT_SESSION, util.SOCIALIZE_MESSAGE_MAILBOX, entUserId) } else { pc_a, err := util.GetData(userType, newUserId) if err == nil && pc_a != nil { if !isClean { return pc_a.Count, pc_a.Data, err } } sqlStr = fmt.Sprintf("select count(b.id) from %s b "+ "where b.send_user_id != %d "+ "AND b.own_id=%d "+ "AND b.iswithdraw = 0 "+ "AND b.isread=0 "+ "AND own_type = 2 "+ "order by create_time", util.SOCIALIZE_MESSAGE_MAILBOX, newUserId, newUserId) } log.Println(sqlStr, v) rs := util.Mysql.CountBySql(sqlStr, v...) log.Println(rs) count = int(rs) //最后一条信息查询 sqlStr = fmt.Sprintf("SELECT c.* FROM %s b "+ "LEFT join %s c on b.messag_id=c.id "+ "WHERE b.send_user_id != %d "+ "AND b.own_id = %d "+ "AND b.iswithdraw = 0 "+ "AND b.isread=0 "+ "AND own_type = 2 "+ "ORDER BY create_time DESC "+ "LIMIT 0,1", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, newUserId, newUserId) lastData := util.Mysql.SelectBySql(sqlStr) if len(*lastData) > 0 { last = (*lastData)[0] if userType == 1 { util.SetData(userType, entUserId, map[string]interface{}{"data": last, "count": count}, util.SurvivalTime) } else { util.SetData(userType, newUserId, map[string]interface{}{"data": last, "count": count}, util.SurvivalTime) } } else { if userType == 1 { util.SetData(userType, entUserId, map[string]interface{}{"data": map[string]interface{}{}, "count": count}, util.SurvivalTime) } else { util.SetData(userType, newUserId, map[string]interface{}{"data": map[string]interface{}{}, "count": count}, util.SurvivalTime) } } return } // 用户列表查询 func (b MessaggeService) UserList(in *messagecenter.UserReq) (data *[]map[string]interface{}, count int64, err error) { sqlStr := "" tm := time.Now() if in.UserType == 2 { //用户最后一次信息查询 userSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM socialize_message_mailbox c "+ "WHERE c.own_id = %d "+ "AND c.iswithdraw = 0 "+ "AND c.type = 2 "+ "AND c.own_type = 2 "+ "GROUP BY ( CASE WHEN c.send_user_id > c.receive_user_id "+ "THEN CONCAT( c.send_user_id, c.receive_user_id ) "+ "WHEN c.send_user_id < c.receive_user_id "+ "THEN CONCAT( c.receive_user_id, c.send_user_id ) END ) ", in.NewUserId, ) data = util.Mysql.SelectBySql(userSql) userMessageId := util.Inhandle(data) //客服最后一次信息查询 customerSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM %s c "+ "LEFT JOIN %s d ON IF ( c.send_user_type = 1, d.id = c.send_user_id, d.id = c.receive_user_id ) "+ "WHERE c.own_id = %d "+ "AND c.iswithdraw = 0 "+ "AND ( c.type = 4 OR c.type = 5 or c.type=6 or c.type=7 ) "+ "AND c.own_type = 2 "+ "AND d.user_id=c.own_id "+ "GROUP BY d.ent_id ", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.NewUserId) data = util.Mysql.SelectBySql(customerSql) customerMessageId := util.Inhandle(data) //用户的列表 sqlStr = fmt.Sprintf("SELECT "+ "( 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 )"+ "AS name, b.id, e.title, b.headimg, e.type, e.link, e.content, 2 AS userType, a.create_time, a.type AS itemType, "+ "( SELECT count( h.id ) FROM %s h "+ "WHERE h.type = 2 "+ "AND h.own_id = %d "+ "AND h.own_type = 2 "+ "AND h.send_user_id=b.id "+ "AND h.isread = 0 AND h.iswithdraw = 0 ) AS number FROM %s a "+ "LEFT JOIN %s b ON b.id = a.receive_user_id or b.id = a.send_user_id "+ "LEFT JOIN %s e ON e.id = a.messag_id "+ "WHERE a.id IN ( %s ) AND b.id != %d "+ "UNION ALL "+ "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, "+ "( 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 "+ "FROM %s a "+ "LEFT JOIN %s b ON IF ( a.send_user_type = 1, a.send_user_id, a.receive_user_id ) = b.id "+ "LEFT JOIN %s e ON e.id = a.messag_id "+ "LEFT join %s f on f.ent_id=b.ent_id "+ "WHERE a.id IN ( %s ) "+ "ORDER BY create_time DESC", util.SOCIALIZE_MESSAGE_MAILBOX, in.NewUserId, util.SOCIALIZE_MESSAGE_MAILBOX, util.BASE_USER, util.SOCIALIZE_MESSAGE, userMessageId, in.NewUserId, util.SOCIALIZE_MESSAGE_MAILBOX, in.NewUserId, in.NewUserId, util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_TENANT_ROBOT, customerMessageId) } else { phoneSql := "" if in.Phone != "" { phoneSql = "AND b.phone like '%" + in.Phone + "%'" } startTimeSql := "" if in.StartTime != "" { startTimeSql = "AND DATE_FORMAT(c.create_time,'%Y-%m-%d') >= '" + in.StartTime + "' " } idSql := fmt.Sprintf("(SELECT COUNT(e.id) FROM socialize_chat_session e WHERE e.customer_service_id > 0 AND e.user_id = d.user_id ) =0 or d.customer_service_id=%d ", in.EntUserId) if in.IsArtificial == 1 { idSql = fmt.Sprintf("d.customer_service_id = %d ", in.EntUserId) } else if in.IsArtificial == 2 { idSql = "(SELECT COUNT(e.id) FROM socialize_chat_session e WHERE e.customer_service_id > 0 AND e.user_id = d.user_id ) =0 " } endTimeSql := "" if in.EndTime != "" { endTimeSql = "AND DATE_FORMAT(c.create_time,'%Y-%m-%d') <= '" + in.EndTime + "' " } if in.Page <= 0 { in.Page = 1 } if in.Size <= 0 || in.Size > 100 { in.Size = 50 } userSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM %s c "+ "LEFT JOIN %s d ON c.own_type=1 AND c.own_id=d.id "+ "LEFT JOIN %s b ON if (c.send_user_type=1 ,c.receive_user_id,c.send_user_id)=b.id "+ "WHERE c.own_type = 1 "+ "AND c.iswithdraw = 0 "+ "AND (%s) "+ "AND ( c.type = 4 OR c.type = 5 or c.type=6 or c.type=7 ) "+ " %s %s %s "+ "GROUP BY ( CASE WHEN c.send_user_type =2 THEN CONCAT( c.send_user_id ) WHEN c.send_user_type =1 THEN CONCAT( c.receive_user_id ) END ) ", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, util.BASE_USER, idSql, startTimeSql, endTimeSql, phoneSql) countSql := fmt.Sprintf("SELECT * FROM (%s) as data order by messageId desc ", userSql) countData := util.Mysql.SelectBySql(countSql) log.Println("查询最新消息数量sql:", countSql) if countData != nil && len(*countData) > 0 { log.Printf("查询耗时1:%d;查询数量:%d", time.Since(tm), count) count = quitl.Int64All(len(*countData)) var d []map[string]interface{} if in.Page*in.Size >= count { d = (*countData)[(in.Page-1)*in.Size:] } else { d = (*countData)[(in.Page-1)*in.Size : in.Page*in.Size] } customerMessageId := util.Inhandle(&d) //客服的用户列表 sqlStr = fmt.Sprintf("SELECT "+ "( 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 )"+ " AS name, b.id, e.title, b.headimg, e.type, e.link, e.content, a.create_time, "+ "( SELECT count( h.id ) FROM %s h "+ "LEFT JOIN %s i ON h.own_type = 1 AND h.own_id = i.id "+ "WHERE h.own_type = 1 "+ "AND i.ent_id=f.ent_id "+ "AND i.user_id=f.user_id "+ "AND h.isread = 0 "+ "AND h.iswithdraw = 0 "+ "AND i.customer_service_id= %d) AS number "+ "FROM %s a "+ "LEFT JOIN %s b ON if (a.send_user_type=1 ,a.receive_user_id,a.send_user_id)=b.id "+ "LEFT JOIN %s e ON e.id = a.messag_id "+ "LEFT JOIN %s f ON a.own_type=1 AND a.own_id=f.id "+ "WHERE a.id IN ( %s) %s ORDER BY a.create_time DESC", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.EntUserId, util.SOCIALIZE_MESSAGE_MAILBOX, util.BASE_USER, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, customerMessageId, phoneSql) } } if sqlStr != "" { log.Println("查询列表sql:", sqlStr) data = util.Mysql.SelectBySql(sqlStr) log.Println("查询耗时2:", time.Since(tm), count) if in.UserType == 2 && data != nil && len(*data) > 0 { count = quitl.Int64All(len(*data)) } } return } // 消息保存 func (b MessaggeService) SaveMessage(in *messagecenter.MessageEntity) (fool bool, errorMsg string, content string, messageId, nowInt int64) { //先插入信息表 //判断会话标识是否属于本人 nowForm := time.Now().Local() if in.ItemType != 2 { userId := int64(0) sessionId := int64(0) switch in.ItemType { case 4, 5, 8: if in.OwnType == 1 { sessionId = in.ReceiveId userId = in.NewUserId } else { sessionId = in.SendId userId = in.ReceiveId if in.ItemType == 4 || in.ItemType == 8 { userId = in.NewUserId } } break case 6: if in.OwnType == 1 { sessionId = in.ReceiveId userId = in.NewUserId } else if in.OwnType == 2 { sessionId = in.SendId userId = in.ReceiveId } else { sessionId = in.ReceiveId userId = in.NewUserId } break } //查找会话信息 chatJson := util.Mysql.FindOne(util.SOCIALIZE_CHAT_SESSION, map[string]interface{}{"id": sessionId}, "user_id", "") if chatJson == nil { return false, "会话标识不存在", "", 0, nowForm.Unix() } else { if userId != quitl.Int64All((*chatJson)["user_id"]) { return false, "会话标识不属于此用户", "", 0, nowForm.Unix() } } } fool = util.Mysql.ExecTx("聊天信息保存", func(tx *sql.Tx) bool { //先插入信息表 create_time := nowForm.Format(util.Date_Full_Layout) userType := int64(1) userId := int64(0) message := map[string]interface{}{ "appid": in.Appid, "title": in.Title, "content": in.Content, "item": in.Item, "type": in.Type, "link": in.Link, "create_time": create_time, "create_person": in.SendId, } data := map[string]interface{}{ "item": in.Item, "type": in.Type, "create_time": create_time, "content": in.Content, } ok := util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message) receiveOk := int64(0) messageId = ok data["id"] = ok //在插入邮箱表socialize_message_mailbox messageMailBox := map[string]interface{}{ "appid": in.Appid, "messag_id": ok, "type": in.ItemType, "create_time": nowForm.Format(util.Date_Full_Layout), "isread": 0, "send_isdel": 0, "receive_isdel": 0, "iswithdraw": 0, } //系统信息处理 if in.ItemType == 6 { messageMailBox = map[string]interface{}{ "appid": in.Appid, "messag_id": ok, "type": in.ItemType, "create_time": nowForm.Format(util.Date_Full_Layout), "read_time": nowForm.Format(util.Date_Full_Layout), "isread": 1, "send_isdel": 0, "receive_isdel": 0, "iswithdraw": 0, } if in.OwnType == 1 { //用户接受系统信息 messageMailBox["own_type"] = 2 messageMailBox["send_user_type"] = 1 messageMailBox["receive_user_type"] = 2 messageMailBox["own_id"] = in.NewUserId messageMailBox["send_user_id"] = in.ReceiveId messageMailBox["receive_user_id"] = in.NewUserId } else if in.OwnType == 2 { //客服接受系统信息 messageMailBox["own_type"] = 1 messageMailBox["send_user_type"] = 2 messageMailBox["receive_user_type"] = 1 messageMailBox["own_id"] = in.SendId messageMailBox["send_user_id"] = in.ReceiveId messageMailBox["receive_user_id"] = in.SendId } else { //客服接受系统信息 messageMailBox["own_type"] = 1 messageMailBox["send_user_type"] = 2 messageMailBox["receive_user_type"] = 1 messageMailBox["own_id"] = in.ReceiveId messageMailBox["send_user_id"] = in.NewUserId messageMailBox["receive_user_id"] = in.ReceiveId } receiveOk = util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox) return ok > 1 && receiveOk > 1 } if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 { //客服或者机器人聊天 if in.OwnType == 1 { // (用户发送)客服接受 messageMailBox["own_type"] = 1 messageMailBox["send_user_type"] = 2 messageMailBox["receive_user_type"] = 1 messageMailBox["own_id"] = in.ReceiveId messageMailBox["send_user_id"] = in.NewUserId messageMailBox["receive_user_id"] = in.ReceiveId userType = 1 userId = in.ReceiveId } else { //客服发送(用户接收信息) messageMailBox["own_type"] = 2 messageMailBox["send_user_type"] = 1 messageMailBox["receive_user_type"] = 2 messageMailBox["own_id"] = in.ReceiveId messageMailBox["send_user_id"] = in.SendId messageMailBox["receive_user_id"] = in.ReceiveId userId = in.ReceiveId if in.ItemType == 4 || in.ItemType == 8 { messageMailBox["receive_user_id"] = in.NewUserId userId = in.NewUserId messageMailBox["own_id"] = in.NewUserId messageMailBox["isread"] = 1 messageMailBox["read_time"] = nowForm.Format(util.Date_Full_Layout) } userType = 2 } } else { messageMailBox["own_type"] = 2 messageMailBox["send_user_type"] = 2 messageMailBox["receive_user_type"] = 2 messageMailBox["own_id"] = in.ReceiveId messageMailBox["send_user_id"] = in.NewUserId messageMailBox["receive_user_id"] = in.ReceiveId userType = 2 userId = in.ReceiveId } receiveOk = util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox) messageMailBox = map[string]interface{}{ "appid": in.Appid, "messag_id": ok, "type": in.ItemType, "create_time": nowForm.Format(util.Date_Full_Layout), "read_time": nowForm.Format(util.Date_Full_Layout), "isread": 1, "send_isdel": 0, "receive_isdel": 0, "iswithdraw": 0, } if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 { //客服或者机器人聊天 if in.OwnType == 1 { //用户发送(用户接受) messageMailBox["own_type"] = 2 messageMailBox["send_user_type"] = 2 messageMailBox["receive_user_type"] = 1 messageMailBox["own_id"] = in.NewUserId messageMailBox["send_user_id"] = in.NewUserId messageMailBox["receive_user_id"] = in.ReceiveId } else { //客服发送信息(用户接受) messageMailBox["own_type"] = 1 messageMailBox["send_user_type"] = 1 messageMailBox["receive_user_type"] = 2 messageMailBox["own_id"] = in.SendId messageMailBox["send_user_id"] = in.SendId messageMailBox["receive_user_id"] = in.ReceiveId if in.ItemType == 4 || in.ItemType == 8 { messageMailBox["receive_user_id"] = in.NewUserId } } } else { messageMailBox["own_type"] = 2 messageMailBox["send_user_type"] = 2 messageMailBox["receive_user_type"] = 2 messageMailBox["own_id"] = in.NewUserId messageMailBox["send_user_id"] = in.NewUserId messageMailBox["receive_user_id"] = in.ReceiveId } receiveOk = util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox) if ok > 1 && receiveOk > 1 { pc_a, err := util.GetData(userType, userId) count := 1 if err == nil && pc_a != nil { count += pc_a.Count } util.SetData(userType, userId, map[string]interface{}{"data": data, "count": count}, util.SurvivalTime) } return ok > 1 && receiveOk > 1 }) return fool, "", in.Content, messageId, nowForm.Unix() } // 历史信息查询 func (b MessaggeService) FindMessage(in *messagecenter.MessageReq) *[]map[string]interface{} { sqlStr := "" lastStr := "" if in.LastId > 0 { if in.Sort == "asc" { lastStr = fmt.Sprintf("AND a.messag_id > %d ", in.LastId) } else { lastStr = fmt.Sprintf("AND a.messag_id < %d ", in.LastId) } } switch in.MsgType { case 2: //点对点聊天 sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,b.* ,if(a.own_id = a.send_user_id,1,2) as fool "+ "FROM %s a "+ "LEFT JOIN %s b on a.messag_id=b.id "+ "LEFT JOIN %s c on c.id=a.send_user_id "+ "LEFT JOIN %s d on d.id=a.receive_user_id "+ "where a.own_id= %d and a.iswithdraw = 0"+ "AND ((a.send_user_id= %d AND a.receive_user_id= %d) or (a.send_user_id= %d AND a.receive_user_id= %d)) "+ "AND a.type=2 %s "+ "ORDER BY a.create_time desc ,a.id asc "+ "limit 0 , %d ", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.BASE_USER, util.BASE_USER, in.NewUserId, in.NewUserId, in.SendId, in.SendId, in.NewUserId, lastStr, in.PageSize) break case 4, 5, 6, 7: //客服聊天 if in.UserType == 1 { //客服聊天记录查看 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 "+ "FROM %s a "+ "LEFT JOIN %s b ON a.messag_id = b.id "+ "LEFT JOIN %s c ON a.own_type = 1 AND a.own_id=c.id "+ "WHERE a.own_type = 1 and a.iswithdraw = 0 "+ "AND (a.type = 5 or a.type=4 or a.type=6 or a.type=7 or a.type=8 ) "+ "AND c.ent_id = %d "+ "AND c.user_id = %d %s "+ "ORDER BY a.create_time desc ,a.id asc "+ "limit 0 , %d ", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, in.EntId, in.SendId, lastStr, in.PageSize) } else { //用户聊天记录查看 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 "+ "FROM %s a "+ "LEFT JOIN %s b ON a.messag_id = b.id "+ "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 "+ "LEFT JOIN %s d on c.ent_id=d.ent_id "+ "LEFT JOIN %s e on e.messag_id=b.id "+ "WHERE a.own_type = 2 and a.iswithdraw = 0 "+ "AND a.own_id = %d "+ "AND c.ent_id = %d "+ "AND c.user_id = %d "+ "AND ( a.type = 4 OR a.type = 5 or a.type=6 or a.type=7 or a.type=8) %s "+ "ORDER BY a.create_time desc ,a.id asc "+ "limit 0 , %d ", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, in.SendId, in.NewUserId, util.SOCIALIZE_TENANT_ROBOT, util.SOCIALIZE_APPRAISE, in.NewUserId, in.SendId, in.NewUserId, lastStr, in.PageSize) } break } log.Println(sqlStr) data := util.Mysql.SelectBySql(sqlStr) //自己头像处理 if in.UserType == 2 { userData := util.Mysql.FindOne(util.BASE_USER, map[string]interface{}{"id": in.NewUserId}, "headimg", "") if userData != nil { for key := range *data { (*data)[key]["ownImg"] = (*userData)["headimg"] } } } go func() { updateMap := map[string]interface{}{} if len(*data) > 0 && data != nil { //if true { //未读信息修改 switch in.MsgType { case 2: //点对点聊天 updateMap = map[string]interface{}{ "own_type": 2, "own_id": in.NewUserId, "type": 2, "isread": 0, } util.Mysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"isread": 1, "read_time": time.Now().Local().Format(util.Date_Full_Layout)}) break case 4, 5: sqlStr := "" if in.UserType == 1 { sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+ "WHERE a.own_type = 1 and a.iswithdraw = 0 "+ "AND a.type IN ( 4,5,6,7) "+ "AND a.isread = 0 "+ "AND a.own_id IN ( SELECT b.id FROM %s b WHERE b.customer_service_id=%d AND b.user_id=%d )", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.EntUserId, in.SendId) } else { sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+ "WHERE a.own_type = 2 and a.iswithdraw = 0 "+ "AND a.type IN ( 4,5,6,7 ) "+ "AND a.isread = 0 "+ "AND a.own_id =%d ", util.SOCIALIZE_MESSAGE_MAILBOX, in.NewUserId) } util.Mysql.UpdateOrDeleteBySql(sqlStr) break } //redis缓存处理 b.Count(in.NewUserId, in.UserType, in.EntUserId, true) } }() return data } // 创建会话 func (b MessaggeService) CreateChatSession(in *messagecenter.ChatSessionReq) (fool bool, sessionId int64) { fool = util.Mysql.ExecTx("会话新建", func(tx *sql.Tx) bool { customerserviceName := in.CustomerserviceName if in.CustomerServiceId != 0 { sqlStr := fmt.Sprintf("select customer_service_name from %s "+ "where ent_id= %d "+ "AND customer_service_id= %d ", util.SOCIALIZE_CHAT_SESSION, in.EntId, in.CustomerServiceId) customerList := util.Mysql.SelectBySql(sqlStr) if len(*customerList) > 0 { customerserviceName = quitl.InterfaceToStr((*customerList)[0]["customer_service_name"]) } } //查询企业是否存在 count := util.Mysql.Count(util.SOCIALIZE_TENANT_ROBOT, map[string]interface{}{ "ent_id": in.EntId, }) if count < 1 { return false } chatMession := map[string]interface{}{ "handle_status": 0, "start_time": time.Now().Local().Format(util.Date_Full_Layout), "appid": in.AppId, "ent_id": in.EntId, "customer_service_id": in.CustomerServiceId, "user_id": in.UserId, "customer_service_name": customerserviceName, } sessionId = util.Mysql.InsertByTx(tx, util.SOCIALIZE_CHAT_SESSION, chatMession) return sessionId > 0 }) return } // 结束会话 func (b MessaggeService) CloseChatSession(in *messagecenter.CloseSessionReq) bool { fool := util.Mysql.ExecTx("关闭会话", func(tx *sql.Tx) bool { updateMap := map[string]interface{}{ "id": in.SessionId, } fool := util.Mysql.Update(util.SOCIALIZE_CHAT_SESSION, updateMap, map[string]interface{}{"start_time": time.Now().Local().Format(util.Date_Full_Layout)}) return fool }) return fool } // 创建会话并保存信息 func (b *MessaggeService) SaveAutoReplyMsg(userType, entId, entUserId, userId int64, content, appId, nowFormat string) (bool, int64) { messageId := int64(0) return util.Mysql.ExecTx("保存自动回复消息", func(tx *sql.Tx) bool { entUserName := "" if entUserId > 0 { list := util.Mysql.SelectBySql(`select ? from socialize_tenant_seat where appid=? AND ent_id=? AND customer_service_id=?`, util.SOCIALIZE_CHAT_SESSION, appId, entId, entUserId) if list != nil && len(*list) > 0 { entUserName, _ = (*list)[0]["customer_service_name"].(string) } } messageId = util.Mysql.InsertBySqlByTx(tx, `insert into socialize_message (appid,content,item,type,create_time,create_person) values (?,?,?,?,?,?)`, appId, content, 8, 1, nowFormat, "admin") sessionId := util.Mysql.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) ok := false if userType == 0 { ok1 := util.Mysql.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 ok2 := util.Mysql.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 ok = ok1 && ok2 } else if userType == 1 { ok = util.Mysql.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 } else if userType == 2 { ok = util.Mysql.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 } return messageId > 0 && sessionId > 0 && ok }), messageId } // 修改未读状态 func (b MessaggeService) UpdateReadById(in *messagecenter.ReadStateReq) bool { updateMap := map[string]interface{}{ "messag_id": in.MessageId, "isread": 0, } if util.Mysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap) > 0 { fool := util.Mysql.ExecTx("已读状态修改", func(tx *sql.Tx) bool { fool := util.Mysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"read_time": time.Now().Local().Format(util.Date_Full_Layout), "isread": 1}) if fool { //查询此条信息拥有者 data := util.Mysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, "receive_user_type", "") if data != nil { userType := int64(1) userId := int64(0) if (*data)["receive_user_type"] == 2 { userType = 2 userId = in.EntUserId } else { userType = 1 userId = in.NewUserId } pc_a, err := util.GetData(userType, userId) if fool { if err == nil && pc_a != nil { if pc_a.Count >= 1 { //id一致 if in.MessageId == pc_a.Data["id"] { util.SetData(userType, userId, map[string]interface{}{"data": map[string]interface{}{}, "count": pc_a.Count - 1}, util.SurvivalTime) } else { util.SetData(userType, userId, map[string]interface{}{"data": data, "count": pc_a.Count - 1}, util.SurvivalTime) } } } } } } return fool }) return fool } return true } // WithdrawMessage 撤回消息 func (b MessaggeService) WithdrawMessage(in *messagecenter.ReadWithdrawReq) bool { messageId := encrypt.SE.Decode4Hex(in.MessageId) newUserId, entUserId := NewEndId(quitl.Int64All(messageId), in.UserType) msg := util.Mysql.FindOne(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId}, "create_time", "") if msg == nil || len(*msg) <= 0 { log.Println("查询消息id失败") return false } createTime, _ := time.Parse(util.Date_Full_Layout, quitl.InterfaceToStr((*msg)["create_time"])) if createTime.Unix()+60*2 < time.Now().Unix() { log.Println("消息已超过2分钟,撤回失败") return false } nowForm := time.Now().Local() m := util.Mysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{"messag_id": messageId}, map[string]interface{}{"iswithdraw": 1, "withdraw_time": nowForm.Format(util.Date_Full_Layout)}) if m { //消息撤回 更新对方私信 in.UserType = quitl.Int64All(quitl.If(in.UserType == 1, 2, 1)) b.Count(newUserId, in.UserType, entUserId, true) } return m } // AppraiseMessage 消息评价 func (b MessaggeService) AppraiseMessage(in *messagecenter.AppraiseReq) error { messageId := encrypt.SE.Decode4Hex(in.MessageId) //查询此条消息是否是当前用户的 if util.Mysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{ "messag_id": messageId, "receive_user_id": in.NewUserId, "receive_user_type": 2, "type": 8, }) == 0 { return fmt.Errorf("未查询到信息") } if util.Mysql.Count(util.SOCIALIZE_APPRAISE, map[string]interface{}{ "appid": in.Appid, "messag_id": messageId, }) > 0 { return fmt.Errorf("请勿重复评价") } //插入评价 if util.Mysql.Insert(util.SOCIALIZE_APPRAISE, map[string]interface{}{ "appid": in.Appid, "messag_id": messageId, "create_time": time.Now().Local().Format(util.Date_Full_Layout), "appraise": in.Appraise, }) > 0 { return nil } return fmt.Errorf("评价消息异常") } // NewEndId 消息撤回 获取对方userid func NewEndId(messageId, iType int64) (newUserId, entUserId int64) { data := util.Mysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{"messag_id": messageId, "own_type": iType}, "", "") if data != nil && len(*data) > 0 { if iType == 1 { //客服撤回消息 获取客服id与用户id entUserId = quitl.Int64All((*data)["send_user_id"]) newUserId = quitl.Int64All((*data)["receive_user_id"]) } else { //用户撤回消息 获取客服id与用户id newUserId = quitl.Int64All((*data)["send_user_id"]) entUserId = quitl.Int64All((*data)["receive_user_id"]) } } return }