package com.ym.im.service.impl;

import com.ym.im.entity.*;
import com.ym.im.entity.base.ResultStatus;
import com.ym.im.service.ChannelGroupService;
import com.ym.im.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author: JJww
 * @Date:2019-07-24
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource(name = "myRedisTemplate")
    private RedisTemplate redisTemplate;


    @Override
    public MsgBody getUserList(Long staffId) {
        final Set usersId = redisTemplate.opsForSet().members(NettyConstant.STAFF_USERIDS_KEY + staffId);
        if (usersId.size() > 0) {
            redisTemplate.delete(NettyConstant.STAFF_USERIDS_KEY + staffId);
        }
        return new MsgBody(ResultStatus.SUCCESS.getCode(), usersId);
    }

    @Override
    public MsgBody deleteUserFromList(IdModel idModel) {

        final StaffSocketInfo staffSocketInfo = ChannelGroupService.STAFF_GROUP.get(idModel.getStaffId());
        if (staffSocketInfo == null) {
            return new MsgBody(ResultStatus.REQUEST_ERROR.getCode(), ResultStatus.REQUEST_ERROR.getMessage());
        }
        staffSocketInfo.getUserIds().remove(idModel.getUserId());
        final UserSocketInfo userSocketInfo = ChannelGroupService.USER_GROUP.get(idModel.getUserId());
        if (userSocketInfo != null && idModel.getStaffId().equals(userSocketInfo.getStaffId())) {
            userSocketInfo.setStaffId(null);
        }
        return new MsgBody(ResultStatus.SUCCESS.getCode());
    }

    @Override
    public MsgBody checkBinding(IdModel idModel) {

        final UserSocketInfo userSocketInfo = ChannelGroupService.USER_GROUP.get(idModel.getUserId());
        /**
         *  用户不在线 不校验绑定关系
         *  用户在线,只有绑定的客服才能发送消息
         *  用户在线未绑定客服
         */
        if (userSocketInfo == null || (userSocketInfo != null && idModel.getStaffId().equals(userSocketInfo.getStaffId()) || userSocketInfo.getStaffId() == null)) {
            return new MsgBody(ResultStatus.SUCCESS.getCode());
        }

        return new MsgBody(ResultStatus.CHECK_FAILURE.getCode(), userSocketInfo.getStaffId());
    }

}