package com.ym.im.handler;

import com.ym.im.entity.StaffSocketInfo;
import com.ym.im.entity.UserSocketInfo;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: JJww
 * @Date:2020/10/14
 */
@Component
public class ChannelGroupHandler {

    /**
     * 在线用户Group
     */
    public final Map<Long, UserSocketInfo> USER_GROUP = new ConcurrentHashMap<>();

    /**
     * 在线客服Group
     */
    public final Map<Long, Map<Long, StaffSocketInfo>> STAFF_GROUP = new ConcurrentHashMap<>();


    /**
     * 新增商户 客服
     *
     * @param merchantId
     * @param staffSocketInfo
     */
    public void putMerchantStaff(Long merchantId, StaffSocketInfo staffSocketInfo) {
        final Map<Long, StaffSocketInfo> staffSocketInfoMap = STAFF_GROUP.get(merchantId) != null ? STAFF_GROUP.get(merchantId) : new HashMap<Long, StaffSocketInfo>();
        staffSocketInfoMap.put(staffSocketInfo.getStaffId(), staffSocketInfo);
        STAFF_GROUP.put(merchantId, staffSocketInfoMap);
    }

    /**
     * 移除商户 客服
     *
     * @param merchantId
     * @param staffId
     */
    public void removeMerchantStaff(Long merchantId, Long staffId) {
        final Map<Long, StaffSocketInfo> staffSocketInfoMap = STAFF_GROUP.get(merchantId);
        staffSocketInfoMap.remove(staffId);
        if (staffSocketInfoMap.isEmpty()) {
            STAFF_GROUP.remove(merchantId);
        }
    }


    public StaffSocketInfo getMerchantStaff(Long merchantId, Long staffId) {
        return STAFF_GROUP.get(merchantId).get(staffId);
    }

    public StaffSocketInfo getMerchantStaff(Long staffId) {
        StaffSocketInfo staffSocketInfo = null;
        for (Map<Long, StaffSocketInfo> staffGroup : STAFF_GROUP.values()) {
            for (StaffSocketInfo staffInfo : staffGroup.values()) {
                if (staffInfo.getStaffId().equals(staffId)) {
                    staffInfo = staffSocketInfo;
                }
            }
        }
        return staffSocketInfo;
    }
}