package com.kingtom.shengtai.app.message.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.kingtom.kirin.app.system.utils.SystemUtils;
import com.kingtom.kirin.core.common.CommonConst;
import com.kingtom.kirin.core.common.base.service.impl.BaseServiceImpl;
import com.kingtom.kirin.core.common.utils.IDUtils;
import com.kingtom.shengtai.app.message.dao.IMsgReceiveDao;
import com.kingtom.shengtai.app.message.model.MsgReceive;
import com.kingtom.shengtai.app.message.service.IMsgReceiveService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.stereotype.Service;

import static com.kingtom.shengtai.app.message.model.table.MsgReceiveTableDef.MSG_RECEIVE;

/**
 * 消息接收记录表 服务层实现。
 *
 * @author wany
 * @since 2023-12-27
 */
@Service
public class MsgReceiveServiceImpl extends BaseServiceImpl<IMsgReceiveDao, MsgReceive> implements IMsgReceiveService{

    @Override
    public void create(String msgId, List<String> receiver){
        Date date = new Date();
        List<MsgReceive> receives = receiver.stream().map(e -> {
            MsgReceive receive = new MsgReceive();
            receive.setMsgId(msgId);
            receive.setReceiver(e);
            receive.setId(IDUtils.newUUID());
            receive.setReceiveState(CommonConst.BooleanEnum.False.getKey());
            receive.setReadState(CommonConst.BooleanEnum.False.getKey());
            receive.setGmtCreate(date);
            receive.setGmtModified(receive.getGmtCreate());
            receive.setSysId(SystemUtils.getCurrentSystemId());
            return receive;
        }).collect(Collectors.toList());
        mapper.insertBatch(receives);
    }

    @Override
    public void updateMsgRead(String userId, List<String> msgIds){
        QueryCondition condition = MSG_RECEIVE.RECEIVER.eq(userId).and(MSG_RECEIVE.MSG_ID.in(msgIds))
                .and(MSG_RECEIVE.READ_STATE.eq(CommonConst.BooleanEnum.False.getKey()));
        MsgReceive receive = new MsgReceive();
        receive.setReadState(CommonConst.BooleanEnum.True.getKey());
        receive.setReadTime(new Date());
        receive.setGmtModified(receive.getReadTime());
        mapper.updateByCondition(receive, condition);
    }

    @Override
    public Page<MsgReceive> page(String userId, Integer pageNum, Integer pageSize){
        QueryWrapper wrapper = QueryWrapper.create().from(MSG_RECEIVE).where(MSG_RECEIVE.RECEIVER.eq(userId))
                .orderBy(MSG_RECEIVE.GMT_CREATE, false);
        return mapper.paginateWithRelations(pageNum, pageSize, wrapper);
    }

}
