package com.ym.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ym.im.entity.ChatRecord;
import com.ym.im.entity.MsgBody;
import com.ym.im.entity.Session;
import com.ym.im.entity.enums.ResultStatus;
import com.ym.im.entity.SessionInfo;
import com.ym.im.mapper.SessionListMapper;
import com.ym.im.service.ChatRecordService;
import com.ym.im.service.SessionListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: JJww
 * @Date:2020/10/21
 */
@Slf4j
@Service
public class SessionListServiceImpl extends ServiceImpl<SessionListMapper, Session> implements SessionListService {

    @Autowired
    private ChatRecordService chatRecordService;

    @Override
    public MsgBody<List<SessionInfo>> getSessionList(Long userId) {
        final List<SessionInfo> sessions = new ArrayList<>();
        baseMapper.selectList(new QueryWrapper<Session>().lambda().eq(Session::getUserId, userId)).forEach(session -> {
            final ChatRecord latestMsg = chatRecordService.getLatestMsg(userId, session.getMerchantId());
            final SessionInfo sessionModel = new SessionInfo().setLatestRecord(latestMsg.getMsgInfo()).setMsgType(latestMsg.getMsgType()).setRecordId(latestMsg.getId());
            BeanUtils.copyProperties(session, sessionModel);
            sessionModel.setModifyTime(latestMsg.getCreateTime());//最后一条信息创建时间为呼叫列表更新时间
            sessions.add(sessionModel);
        });
        return new MsgBody<List<SessionInfo>>().setCode(ResultStatus.SUCCESS.getCode()).setData(sessions);
    }
}
