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.enums.ResultStatus;
import com.ym.im.entity.model.IdModel;
import com.ym.im.handler.ChannelGroupHandler;
import com.ym.im.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;

import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;

/**
 * @author: JJww
 * @Date:2019-05-22
 */
@Service
public class StaffServiceImpl implements StaffService {

    @Autowired
    private ChannelGroupHandler channelGroup;

    @Override
    public StaffSocketInfo getIdleStaff(Long merchantId,Long userId) {

        final LinkedHashMap<Long, StaffSocketInfo> collect = channelGroup.STAFF_GROUP.get(merchantId)
                .entrySet()
                .stream()
                .sorted(comparingByValue(new Comparator<StaffSocketInfo>() {
                    @Override
                    public int compare(StaffSocketInfo o1, StaffSocketInfo o2) {
                        return Integer.valueOf(o1.getUserIds().size()).compareTo(Integer.valueOf(o2.getUserIds().size()));
                    }
                })).collect(toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, LinkedHashMap::new));

        if (collect.size() == 0) {
            channelGroup.USER_GROUP.get(userId).setStaffId(null);
            return null;
        }
        //客服和用户绑定
        StaffSocketInfo staffSocketInfo = collect.entrySet().iterator().next().getValue();
        staffSocketInfo.getUserIds().add(userId);
        Long staffId = staffSocketInfo.getStaffId();
        //用户和客服绑定
        final UserSocketInfo userSocketInfo = channelGroup.USER_GROUP.get(userId);
        if (userSocketInfo != null) {
            userSocketInfo.setStaffId(staffId);
            //通知用户 新的客服
            userSocketInfo.writeAndFlush(new MsgBody<>().setStatus(MsgBody.DISTRIBUTION_STAFF).setData(new IdModel().setStaffId(staffId).setUserId(userId)));
        }
        return staffSocketInfo;
    }


    @Override
    public MsgBody forward(IdModel idModel) {

        final UserSocketInfo userSocketInfo = channelGroup.USER_GROUP.get(idModel.getUserId());
        final StaffSocketInfo staffSocketInfo =channelGroup.getMerchantStaff(idModel.getStaffId());
        if (staffSocketInfo == null || userSocketInfo == null) {
            return new MsgBody<>().setStatus(MsgBody.BINDINGFAILURE).setMessage(ResultStatus.FORWARD_FAILURE.getMessage());
        }
        //移除原客服绑定
        channelGroup.getMerchantStaff(userSocketInfo.getStaffId()).getUserIds().remove(idModel.getUserId());
        //设置新的客服
        staffSocketInfo.getUserIds().add(idModel.getUserId());
        userSocketInfo.setStaffId(idModel.getStaffId());
        final MsgBody<IdModel> msgBody = new MsgBody<IdModel>().setStatus(MsgBody.DISTRIBUTION_STAFF).setData(idModel);
        //通知用户 新客服ID
        userSocketInfo.writeAndFlush(msgBody);
        //通知新客服
        staffSocketInfo.writeAndFlush(msgBody);
        return new MsgBody<>().setData(ResultStatus.SUCCESS.getCode());

    }

    @Override
    public MsgBody getMerchantStaffGroup(Long merchantId) {
        List<StaffSocketInfo> staffs = new ArrayList<StaffSocketInfo>();
        channelGroup.STAFF_GROUP.get(merchantId).forEach((k, v) -> {
            staffs.add(v);
        });
        return new MsgBody<>().setStatus(ResultStatus.SUCCESS.getCode()).setData(staffs);
    }


}
