package com.lxyer.redim.impl;

import com.lxyer.base.JBean;
import com.lxyer.bbs.base.BaseService;
import com.lxyer.bbs.base.user.UserRecord;
import com.lxyer.redim.entity.MsgRecord;
import com.lxyer.redim.info.MsgInfo;
import com.lxyer.redim.service.ImMsgService;
import org.redkale.net.http.RestService;
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 JBean insert(MsgRecord... msg) {
        source.insertAsync(msg);
        return JBean.ok();
    }

    /**
     * 消息修改
     *
     * @param msg
     */
    @Override
    public JBean update(MsgRecord ... msg) {
        source.updateAsync(msg);
        return JBean.ok();
    }

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

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

        UserRecord userRecord;
        if (fromuserid > 0){
            userRecord = source.find(UserRecord.class, fromuserid);
            info.setUsername(userRecord.getUsername());
            info.setAvatar(userRecord.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 JBean.by(info);
    }

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


}
