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

import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.chat.db.mapper.GroupInfoMapper;
import cn.reghao.tnb.content.app.chat.db.mapper.GroupMemberMapper;
import cn.reghao.tnb.content.app.chat.model.dto.contact.ContactInfo;
import cn.reghao.tnb.content.app.chat.model.dto.group.*;
import cn.reghao.tnb.content.app.chat.model.po.GroupInfo;
import cn.reghao.tnb.content.app.chat.model.po.GroupMember;
import cn.reghao.tnb.content.app.chat.model.po.contact.UserContact;
import cn.reghao.tnb.user.api.dto.ContactDetail;
import cn.reghao.tnb.user.api.dto.UserInfo;
import cn.reghao.tnb.user.api.iface.UserContactService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2022-04-29 11:22:13
 */
@Service
public class GroupMemberService {
    @DubboReference(check = false)
    private UserContactService contactService;

    private final GroupMemberMapper groupMemberMapper;
    private final GroupInfoMapper groupInfoMapper;

    public GroupMemberService(GroupMemberMapper groupMemberMapper, GroupInfoMapper groupInfoMapper) {
        this.groupMemberMapper = groupMemberMapper;
        this.groupInfoMapper = groupInfoMapper;
    }

    public GroupInfoRetList getGroups() {
        long loginUser = UserContext.getUserId();
        List<GroupInfoRet> rows = groupInfoMapper.findGroupsByUserId(loginUser);
        rows.forEach(groupInfoRet -> {
            if (groupInfoRet.isOwner()) {
                groupInfoRet.setLeader(2);
            } else {
                groupInfoRet.setLeader(0);
            }

            if (groupInfoRet.isDisturb()) {
                groupInfoRet.setIsDisturb(1);
            } else {
                groupInfoRet.setIsDisturb(2);
            }
        });

        return new GroupInfoRetList(rows);
    }

    public List<GroupMemberRet> getGroupMember(long groupId) {
        List<GroupMemberRet> memberList = groupMemberMapper.findByGroupId(groupId);
        memberList.forEach(groupMemberRet -> {
            long userId = groupMemberRet.getUserId();
            ContactDetail contactDetail = new ContactDetail();
            groupMemberRet.setNickname(contactDetail.getScreenName());
            groupMemberRet.setAvatar(contactDetail.getAvatarUrl());
            groupMemberRet.setGender(contactDetail.getGender());
            groupMemberRet.setMotto(contactDetail.getSignature());
        });

        memberList.forEach(groupMemberRet -> {
            if (groupMemberRet.isOwner()) {
                groupMemberRet.setLeader(2);
            } else {
                groupMemberRet.setLeader(0);
            }
        });
        return memberList;
    }

    public void setNicknameInGroup(MemberRemark memberRemark) {
        long loginUser = UserContext.getUserId();
        long groupId = memberRemark.getGroupId();
        String remarkName = memberRemark.getVisitCard();
        groupMemberMapper.updateSetMemberRemark(groupId, loginUser, remarkName);
    }

    public List<ContactInfo> getInvitedUsers(long groupId) {
        long loginUser = UserContext.getUserId();
        List<UserContact> list = new ArrayList<>();
        /*if (groupId == 0) {
            list = userContactMapper.findByUserId(loginUser);
        } else {
            list = userContactMapper.findFriendsByNotInGroup(loginUser, groupId);
        }*/

        List<ContactInfo> list1 = list.stream().map(userContact -> {
            long friendId = userContact.getFriendId();
            UserInfo userInfo = contactService.getUserInfo(friendId);
            return new ContactInfo();
        }).collect(Collectors.toList());

        return list1;
    }

    public void inviteUsers(GroupInvite groupInvite) {
        long loginUser = UserContext.getUserId();
        long groupId = groupInvite.getGroupId();
        GroupMember groupMember = groupMemberMapper.findByGroupAndUserId(groupId, loginUser);
        if (groupMember == null) {
            // TODO 非本群用户不能邀请其他用户进群
            return;
        }

        List<GroupMember> list = Arrays.stream(groupInvite.getIds().split(","))
                .map(memberId -> new GroupMember(groupId, Long.valueOf(memberId)))
                .collect(Collectors.toList());
        groupMemberMapper.saveAll(list);
    }

    public void leaveGroup(SecedeGroup secedeGroup) {
        long loginUser = UserContext.getUserId();
        long groupId = secedeGroup.getGroupId();
        GroupInfo groupInfo = groupInfoMapper.findByGroupId(groupId);
        long ownerId = groupInfo.getOwnerId();
        if (loginUser == ownerId) {
            // TODO 群主请先解散群
            return;
        }

        groupMemberMapper.deleteGroupMembers(groupId, List.of(loginUser));
        //chatDialogMapper.deleteGroupChatDialog(groupId, List.of(loginUser));
    }

    public void removeMembers(RemoveMember removeMember) {
        long loginUser = UserContext.getUserId();
        long groupId = removeMember.getGroupId();
        GroupInfo groupInfo = groupInfoMapper.findByGroupId(groupId);
        long ownerId = groupInfo.getOwnerId();
        if (loginUser != ownerId) {
            // TODO 没有权限, 只有群主才能移除群成员
            return;
        }

        List<Long> userIds = Arrays.stream(removeMember.getMembersIds().split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        groupMemberMapper.deleteGroupMembers(groupId, userIds);
        //chatDialogMapper.deleteGroupChatDialog(groupId, userIds);
    }
}
