package com.yeejoin.amos.boot.module.jg.biz.reminder.core;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jg.biz.reminder.dto.MatchItemDto;
import com.yeejoin.amos.boot.module.jg.biz.reminder.dto.ReminderField;
import com.yeejoin.amos.boot.module.jg.biz.reminder.dto.ReminderItemDto;
import org.springframework.context.ApplicationContext;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class DefaultReminder implements IReminderHandler {
    private final ApplicationContext applicationContext;

    public DefaultReminder(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public IPage<ReminderItemDto> remindersPage(Page<ReminderItemDto> page, String bizId, SourceType sourceType, Map<String, Object> formData) {
        IPage<ReminderItemDto> params = parse(page, bizId, sourceType, formData);
        ReminderFieldDiff reminderFieldDiff = applicationContext.getBean(ReminderFieldDiff.class);
        MatchItemDto matchItemDto = getMatchItem(bizId, formData) == null ? MatchItemDto.builder().build() : getMatchItem(bizId, formData);
        matchItemDto.setBizType(supportBizType());
        matchItemDto.setPage(page);
        return reminderFieldDiff.getReminderItemsPage(params, matchItemDto);
    }

    @Override
    public Integer getReminderLevel(String bizId) {
        ReminderFieldDiff reminderFieldDiff = applicationContext.getBean(ReminderFieldDiff.class);
        MatchItemDto matchItemDto = getMatchItem(bizId) == null ? MatchItemDto.builder().build() : getMatchItem(bizId);
        List<ReminderItemDto> equips = reminderFieldDiff.getReminderItemList(realtimeParse(bizId, null).getRecords(), matchItemDto);
        List<ReminderField> items = equips.stream().flatMap(s -> s.getItems().stream()).collect(Collectors.toList());
        return items.stream().max(Comparator.comparingInt(ReminderField::getSId)).map(ReminderField::getSId).orElse(-1);
    }

    private IPage<ReminderItemDto> parse(Page<ReminderItemDto> page, String bizId, SourceType sourceType, Map<String, Object> formData) {
        switch (sourceType) {
            case realTime:
                return realtimeParse(bizId, page);
            case json:
                return jsonParse(bizId, formData, page);
            default:
                throw new RuntimeException("no support type for " + sourceType);
        }
    }

    public abstract IPage<ReminderItemDto> realtimeParse(String bizId, Page<ReminderItemDto> page);


    public abstract IPage<ReminderItemDto> jsonParse(String bizId, Map<String, Object> formData, Page<ReminderItemDto> page);


    public abstract MatchItemDto getMatchItem(String bizId, Map<String, Object> formData);

    public abstract MatchItemDto getMatchItem(String bizId);

}
