package com.ym.im.service.impl;

import com.ym.im.entity.MsgBody;
import com.ym.im.entity.StaffSocketInfo;
import com.ym.im.entity.UserSocketInfo;
import com.ym.im.entity.base.NettyConstant;
import com.ym.im.entity.enums.ResultStatus;
import com.ym.im.entity.model.IdModel;
import com.ym.im.handler.ChannelGroupHandler;
import com.ym.im.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;

    @Autowired
    private ChannelGroupHandler channelGroup;


    @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<>().setStatus(ResultStatus.SUCCESS.getCode()).setData(usersId);
    }

    @Override
    public MsgBody deleteUserFromList(IdModel idModel) {

        final StaffSocketInfo staffSocketInfo = channelGroup.getMerchantStaff(idModel.getStaffId());
        if (staffSocketInfo == null) {
            return new MsgBody<>().setStatus(ResultStatus.REQUEST_ERROR.getCode()).setMessage(ResultStatus.REQUEST_ERROR.getMessage());
        }
        staffSocketInfo.getUserIds().remove(idModel.getUserId());
        final UserSocketInfo userSocketInfo = channelGroup.USER_GROUP.get(idModel.getUserId());
        if (userSocketInfo != null && idModel.getStaffId().equals(userSocketInfo.getStaffId())) {
            userSocketInfo.setStaffId(null);
        }
        return new MsgBody().setStatus(ResultStatus.SUCCESS.getCode());
    }

    @Override
    public MsgBody checkBinding(IdModel idModel) {

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

    }

}