package net.tccn.redim.impl;

import net.tccn.bbs.base.BaseService;
import net.tccn.bbs.user.UserDetail;
import net.tccn.redim.entity.MsgRecord;
import net.tccn.redim.info.MsgInfo;
import net.tccn.redim.service.ImMsgService;
import org.redkale.net.http.RestService;
import org.redkale.service.RetResult;
import org.redkale.source.FilterNode;
import org.redkale.util.ResourceType;

import java.util.List;

/**
 * @author: liangxianyou at 2018/8/12 13:10.
 */
@ResourceType(ImMsgService.class)
@RestService(name = "immsg", automapping = true, comment = "聊天记录管理")
public class ImMsgServiceImpl extends BaseService implements ImMsgService {

    /**
     * 消息入库
     *
     * @param msg
     */
    @Override
    public RetResult insert(MsgRecord... msg) {
        dataSource.insertAsync(msg);
        return RetResult.success();
    }

    /**
     * 消息修改
     *
     * @param msg
     */
    @Override
    public RetResult update(MsgRecord... msg) {
        dataSource.updateAsync(msg);
        return RetResult.success();
    }

    /**
     * 历史消息
     *
     * @return
     */
    @Override
    public RetResult list() {
        return null;
    }

    /**
     * 创建消息体
     *
     * @param msg
     */
    @Override
    public RetResult<MsgInfo> createMsgInfo(MsgRecord msg) {
        MsgInfo info = new MsgInfo();
        int fromuserid = msg.getFromuserid();

        UserDetail userDetail;
        if (fromuserid > 0) {
            userDetail = dataSource.find(UserDetail.class, fromuserid);
            info.setUsername(userDetail.getUsername());
            info.setAvatar(userDetail.getAvatar());
            info.setType("friend");
        } else {
            info.setUsername("游客");
            info.setAvatar("/res/images/avatar/12.jpg");
            info.setType("friend");
        }

        info.setId(msg.getFromuserid());
        info.setContent(msg.getContent());
        info.setCid(msg.getMsgid());
        info.setMine(false);
        info.setFromid(msg.getFromuserid());
        info.setTimestamp(msg.getCreatetime());

        return RetResult.success(info);
    }

    @Override
    public RetResult<List<MsgRecord>> offlineMsg(int userid) {
        List<MsgRecord> records = dataSource.queryList(MsgRecord.class, FilterNode.create("touserid", userid).and("status", 10));
        return RetResult.success(records);
    }


}
