package com.usky.sas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usky.sas.domain.SasEventTypeGroup;
import com.usky.sas.service.SasEventPriorityService;
import com.usky.sas.service.SasEventTypeGroupService;
import com.usky.sas.service.vo.EventPriorityConfigRequest;
import com.usky.sas.service.vo.EventPriorityConfigResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 事件优先级配置 服务实现
 *
 * 说明：这里直接基于事件组上的 eventLevel 字段做分类：
 * 1: urgent, 2: high, 3: normal, 其他: none
 */
@Service
public class SasEventPriorityServiceImpl implements SasEventPriorityService {

    @Autowired
    private SasEventTypeGroupService eventTypeGroupService;

    @Override
    public EventPriorityConfigResponse getConfig() {
        List<SasEventTypeGroup> all = eventTypeGroupService.list(new LambdaQueryWrapper<>());
        EventPriorityConfigResponse resp = new EventPriorityConfigResponse();
        resp.setUrgent(filterByLevel(all, 1));
        resp.setHigh(filterByLevel(all, 2));
        resp.setNormal(filterByLevel(all, 3));
        resp.setNone(filterByLevel(all, null));
        return resp;
    }

    private List<String> filterByLevel(List<SasEventTypeGroup> all, Integer level) {
        List<String> ids = new ArrayList<>();
        for (SasEventTypeGroup g : all) {
            Integer lv = g.getEventLevel();
            if (level == null) {
                if (lv == null || (lv != 1 && lv != 2 && lv != 3)) {
                    ids.add(g.getId());
                }
            } else if (level.equals(lv)) {
                ids.add(g.getId());
            }
        }
        return ids;
    }

    @Override
    public void updateConfig(EventPriorityConfigRequest request) {
        updateLevel(request.getUrgent(), 1);
        updateLevel(request.getHigh(), 2);
        updateLevel(request.getNormal(), 3);
        updateLevel(request.getNone(), null);
    }

    private void updateLevel(List<String> ids, Integer level) {
        if (ids == null) {
            return;
        }
        for (String id : ids) {
            SasEventTypeGroup group = eventTypeGroupService.getById(id);
            if (group == null) {
                continue;
            }
            group.setEventLevel(level);
            eventTypeGroupService.updateById(group);
        }
    }
}

