package cn.reghao.tnb.content.app.chat.service;

import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.chat.db.mapper.GroupMemberMapper;
import cn.reghao.tnb.content.app.chat.db.mapper.GroupNoticeMapper;
import cn.reghao.tnb.content.app.chat.model.dto.group.EditGroupNotice;
import cn.reghao.tnb.content.app.chat.model.dto.group.NoticeListRet;
import cn.reghao.tnb.content.app.chat.model.dto.group.NoticeRet;
import cn.reghao.tnb.content.app.chat.model.po.GroupMember;
import cn.reghao.tnb.content.app.chat.model.po.GroupNotice;
import cn.reghao.tnb.user.api.dto.ContactDetail;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author reghao
 * @date 2022-04-29 11:23:24
 */
@Service
public class GroupNoticeService {
    private final GroupNoticeMapper groupNoticeMapper;
    private final GroupMemberMapper groupMemberMapper;

    public GroupNoticeService(GroupNoticeMapper groupNoticeMapper, GroupMemberMapper groupMemberMapper) {
        this.groupNoticeMapper = groupNoticeMapper;
        this.groupMemberMapper = groupMemberMapper;
    }

    public void createOrUpdateNotice(EditGroupNotice editGroupNotice) {
        long loginUser = UserContext.getUserId();
        int noticeId = editGroupNotice.getNoticeId();
        GroupNotice groupNotice = new GroupNotice(editGroupNotice, loginUser);
        if (noticeId == 0) {
            groupNoticeMapper.save(groupNotice);
        } else {
            GroupNotice groupNotice1 = groupNoticeMapper.findByNoticeId(noticeId);
            if (groupNotice1.getCreateBy() == loginUser) {
                groupNoticeMapper.updateSetNotice(groupNotice);
            } else {
                // TODO 群公告只能由创建者修改
            }
        }
    }

    public NoticeListRet getNoticeList(long groupId) {
        long loginUser = UserContext.getUserId();
        GroupMember groupMember = groupMemberMapper.findByGroupAndUserId(groupId, loginUser);
        if (groupMember == null) {
            // TODO 不是该组成员, 没有权限查看群公告
            return new NoticeListRet(new ArrayList<>());
        }

        List<NoticeRet> rows = groupNoticeMapper.findByGroupId(groupId);
        rows.forEach(noticeRet -> {
            long userId = noticeRet.getUserId();
            ContactDetail contactDetail = new ContactDetail();
            noticeRet.setNickname(contactDetail.getScreenName());
            noticeRet.setAvatar(contactDetail.getAvatarUrl());
        });
        return new NoticeListRet(rows);
    }
}
