package com.ym.im.mq;

import com.ym.im.entity.MsgBody;
import com.ym.im.entity.StaffSocketInfo;
import com.ym.im.entity.Stroke;
import com.ym.im.entity.UserSocketInfo;
import com.ym.im.entity.base.NettyConstant;
import com.ym.im.entity.model.IdModel;
import com.ym.im.handler.ChannelGroupHandler;
import com.ym.im.service.StaffService;
import com.ym.im.util.JsonUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

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

/**
 * @author: JJww
 * @Date:2019-05-30
 */
@Slf4j
@Component
public class Receiver {

    @Autowired
    private Queue queue;

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

    @Autowired
    private StaffService staffService;

    @Autowired
    private ChannelGroupHandler channelGroup;

    @RabbitListener(queues = "#{staffOfflineQueue.name}")
    public void offlineHandler(StaffSocketInfo staffSocketInfo) {

        final Long staffId = staffSocketInfo.getStaffId();
        //移除用户列表
        redisTemplate.delete(NettyConstant.STAFF_USERIDS_KEY + staffId);
        //客服真离线后 才转发
        if (channelGroup.getMerchantStaff(staffId) == null) {
            final Set userIds = staffSocketInfo.getUserIds();
            log.info("客服离线队列: " + "ID: " + "UserIds:" + userIds);
            userIds.forEach(uid -> {
                Long userId = Long.valueOf(uid.toString());
                //用户在线才重新分配和转发
                if (channelGroup.USER_GROUP.get(userId) != null) {
                    final StaffSocketInfo idleStaff = staffService.getIdleStaff(staffSocketInfo.getMerchantId(), userId);
                    if (idleStaff != null) {
                        idleStaff.writeAndFlush(new MsgBody<>().setCode(MsgBody.DISTRIBUTION_STAFF).setData(new IdModel().setStaffId(staffId).setUserId(userId)));
                    }
                }
            });
        }
    }


    /**
     * 订单相关处理
     *
     * @param orderModel
     */
    @SneakyThrows
    @RabbitListener(queues = "#{orderQueue.name}")
    public void orderHandler(String json) {
        final Stroke stroke = JsonUtils.json2Obj(json, Stroke.class);
        log.info("订单信息: " + json);
        final Long mcId = stroke.getMcId();
        final Long userId = stroke.getUserId();
        final UserSocketInfo userSocketInfo = channelGroup.USER_GROUP.get(userId);
        if (userSocketInfo == null) {
            return;
        }
        stroke.setSendTime(new Date());
        final MsgBody<Stroke> orderInfo = new MsgBody<Stroke>().setCode(MsgBody.ORDER).setData(stroke);
        final StaffSocketInfo staffSocketInfo = channelGroup.getMerchantStaff(userSocketInfo.getStaffId(stroke.getMcId())) == null ? staffService.getIdleStaff(mcId, userId) : channelGroup.getMerchantStaff(userSocketInfo.getStaffId(stroke.getMcId()));
        if (staffSocketInfo != null) {
            staffSocketInfo.writeAndFlush(orderInfo);
            log.info("客服订单: " + "给客服(" + staffSocketInfo.getStaffId() + ")发送订单:" + json);
        }
    }


}