package com.ym.im.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ym.im.entity.ChatRecord;
import com.ym.im.entity.MsgBody;
import com.ym.im.entity.PullChatRecord;
import com.ym.im.entity.base.ResultStatus;
import com.ym.im.mapper.ChatRecordMapper;
import com.ym.im.service.ChatRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 聊天记录 服务实现类
 * </p>
 *
 * @author 陈俊雄
 * @since 2019-05-28
 */
@Service
public class ChatRecordServiceImpl implements ChatRecordService {

    @Autowired
    private ChatRecordMapper chatRecordMapper;

    @Override
    public int insert(ChatRecord chatRecord) {
        return chatRecordMapper.insert(chatRecord, remainder(chatRecord.getUserId()));
    }

    @Override
    public int insertSelective(ChatRecord chatRecord) {
        return chatRecordMapper.insertSelective(chatRecord, remainder(chatRecord.getUserId()));
    }

    @Override
    public int updateById(ChatRecord chatRecord) {
        return chatRecordMapper.updateById(chatRecord, remainder(chatRecord.getUserId()));
    }

    @Override
    public int updateByIdSelective(ChatRecord chatRecord) {
        return chatRecordMapper.updateByIdSelective(chatRecord, remainder(chatRecord.getUserId()));
    }

    @Override
    public int updateReceiveTime(ChatRecord chatRecord) {
        return chatRecordMapper.updateReceiveTime(chatRecord, remainder(chatRecord.getUserId()));
    }

    @Override
    public ChatRecord selectById(Long id, Long userId) {
        return chatRecordMapper.selectById(id, remainder(userId));
    }

    @Override
    public MsgBody<PullChatRecord> getChatRecord(PullChatRecord pull) {
        PageHelper.startPage(pull.getPageNum(), pull.getPageSize(), pull.getOrderBy() + " " + pull.getSorting());
        final List<ChatRecord> chatRecords = chatRecordMapper.getChatRecord(pull, remainder(pull.getUserId()));
        final PageInfo<ChatRecord> pageInfo = new PageInfo<>(chatRecords);
        pull.setChatRecords(chatRecords);
        pull.setPages(pageInfo.getPages());
        pull.setTotal(pageInfo.getTotal());
        return new MsgBody<PullChatRecord>().setStatus(ResultStatus.SUCCESS.getCode()).setData(pull);
    }

    @Override
    public MsgBody<List<ChatRecord>> updateReceiveTime(List<ChatRecord> chats) {
        chatRecordMapper.updateBatchReceiveTimeById(chats, remainder(chats.get(0).getUserId()));
        return new MsgBody<List<ChatRecord>>().setStatus(ResultStatus.SUCCESS.getCode()).setData(chats);

    }

    /**
     * 使用userId取聊天记录表数量余数
     *
     * @param userId 用户Id
     * @return 余数
     */
    private int remainder(long userId) {
        return (int) (userId % NUMBER_OF_TABLE);
    }
}
