package com.sifang.modules.taskdispatch.service.autod;

import com.sifang.modules.taskdispatch.entity.CrmReviewGroup;
import com.sifang.modules.taskdispatch.service.CrmReviewGroupService;
import com.sifang.modules.taskdispatch.util.ItemTaskSignal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Lazy(false)
@DependsOn("JFinalDb")
public class ItemAutoDispatchService {

    private static final Timer timer = new Timer();
    private static final Logger log = LoggerFactory.getLogger(ItemAutoDispatchService.class);
    private static final List<GroupDispatchRunner> runners = new ArrayList<>();
    private static final Map<String, GroupItemManager> groupItemManagerMap = new ConcurrentHashMap<>();
    private static final Map<String, GroupDispatchRunner> groupDispatchRunnerMap = new ConcurrentHashMap<>();

    @Autowired
    private CrmReviewGroupService groupService;

    public static List<GroupItemManager> getItemManagers(Set<String> groupIds) {
        List<GroupItemManager> ret = new ArrayList<>();
        for (String groupId : groupIds) {
            GroupItemManager manager = groupItemManagerMap.get(groupId);
            if (manager != null && Objects.equals(manager.getGroupId(), groupId)) {
                ret.add(manager);
            }
        }
        return ret;
    }

    public static GroupDispatchRunner getRunner(String partnerId) {
        return groupDispatchRunnerMap.get(partnerId);
    }

    @PostConstruct
    public void start() {
        List<ItemTaskSignal> signals = new ArrayList<>();
        List<CrmReviewGroup> reviewGroups = groupService.allGroups();
        Map<String, List<CrmReviewGroup>> partnerId2GroupMap = reviewGroups.stream().collect(Collectors.groupingBy(CrmReviewGroup::getPartnerId));
        Set<Map.Entry<String, List<CrmReviewGroup>>> partnerId2Groups = partnerId2GroupMap.entrySet();

        for (Map.Entry<String, List<CrmReviewGroup>> partnerGroupsEntry : partnerId2Groups) {
            List<CrmReviewGroup> partnerGroups = partnerGroupsEntry.getValue();
            String partnerId = partnerGroupsEntry.getKey();
            List<GroupItemManager> itemManagers = new ArrayList<>();
            for (CrmReviewGroup group : partnerGroups) {
                GroupItemManager groupItemManager = new GroupItemManager(partnerId, group.getId(), group.getType());
                itemManagers.add(groupItemManager);
                groupItemManagerMap.put(group.getId(), groupItemManager);
            }
            ItemTaskSignal signal = new ItemTaskSignal();
            signals.add(signal);
            GroupDispatchRunner runner = new GroupDispatchRunner(partnerId, itemManagers, signal);
            runners.add(runner);
            groupDispatchRunnerMap.put(partnerId, runner);
            new Thread(runner).start();
        }

        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                for (ItemTaskSignal signal : signals) {
                    signal.pump();
                }
            }
        }, 1000 * 60, 1000 * 60 * 2); // 每两分钟自动派工一次
    }

    public void dispatch(List<String> userIds) {
        for (GroupDispatchRunner runner : runners) {
            runner.dispatch(userIds);
        }
    }

}
