package com.ym.im.mq;

import com.ym.im.entity.*;
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.ChatService;
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 {

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

    @Autowired
    private StaffService staffService;

    @Autowired
    private ChannelGroupHandler channelGroup;

    @Autowired
    private ChatService staffSingleChatServiceImpl;

    @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 json
     */
    @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;
        }
        final StaffSocketInfo staffSocketInfo = channelGroup.getMerchantStaff(userSocketInfo.getStaffId(stroke.getMcId())) == null ? staffService.getIdleStaff(mcId, userId) : channelGroup.getMerchantStaff(userSocketInfo.getStaffId(stroke.getMcId()));
        final ChatRecord chatRecord = new ChatRecord().setMsgInfo(json).setUserId(userId).setSendTime(new Date()).setMsgType(MsgBody.ORDER);
        final MsgBody<ChatRecord> orderInfo = new MsgBody<ChatRecord>().setCode(MsgBody.ORDER).setData(chatRecord);
        staffSingleChatServiceImpl.save(staffSocketInfo.getStaffId(), orderInfo);
        if (staffSocketInfo != null) {
            staffSocketInfo.writeAndFlush(orderInfo);
            log.info("客服订单: " + "给客服(" + staffSocketInfo.getStaffId() + ")发送订单:" + json);
        }
    }


}