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.model.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()).setRecordId(latestMsg.getId());
            BeanUtils.copyProperties(session, sessionModel);
            sessions.add(sessionModel);
        });
        return new MsgBody<List<SessionInfo>>().setCode(ResultStatus.SUCCESS.getCode()).setData(sessions);
    }
}
