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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.jg.api.dto.ReminderField;
import com.yeejoin.amos.boot.module.jg.api.dto.ReminderItemDto;
import com.yeejoin.amos.boot.module.jg.api.entity.TzsJgColumnReminderRule;
import com.yeejoin.amos.boot.module.jg.biz.reminder.core.ReminderFieldDiff;
import com.yeejoin.amos.boot.module.jg.biz.reminder.dto.MatchItemDto;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.TzsJgColumnReminderRuleServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.utils.MemoryPageUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@RequiredArgsConstructor
public class ReminderFieldDiffImpl implements ReminderFieldDiff {

    private final TzsJgColumnReminderRuleServiceImpl reminderRuleService;

    @Override
    public IPage<ReminderItemDto> getReminderItemsPage(List<ReminderItemDto> reminderItemDtos, IPage<ReminderItemDto> page, MatchItemDto matchItem) {
        reminderItemDtos.forEach(reminderItemDto -> {
            reminderItemDto.setItems(this.buildRemindItem(reminderItemDto, matchItem));
        });
        List<ReminderItemDto> itemDtoListMissing = reminderItemDtos.stream().filter(item -> !item.getItems().isEmpty()).collect(Collectors.toList());
        return MemoryPageUtils.paginate(itemDtoListMissing, page.getCurrent(), page.getSize());
    }

    @Override
    public List<ReminderItemDto> getReminderItemList(List<ReminderItemDto> equips, MatchItemDto matchItem) {
        equips.forEach(reminderItemDto -> {
            reminderItemDto.setItems(this.buildRemindItemGrade(reminderItemDto, matchItem));
        });
        return equips;
    }

    private List<ReminderField> buildRemindItemGrade(ReminderItemDto reminderItemDto, MatchItemDto matchItem) {
        // regType默认0-新增，不同regType对应不同字段时，配置多行
        List<TzsJgColumnReminderRule> rules = reminderRuleService.list(new LambdaQueryWrapper<TzsJgColumnReminderRule>()
                .eq(TzsJgColumnReminderRule::getBizType, matchItem.getBizType())
                .eq(StringUtils.isNotEmpty(matchItem.getRegType()), TzsJgColumnReminderRule::getRegType, matchItem.getRegType())
                .eq(TzsJgColumnReminderRule::getWhetherVehicleCylinder, matchItem.getWhetherVehicleCylinder())
                .eq(matchItem.getIsRegister() != null, TzsJgColumnReminderRule::getIsRegister, matchItem.getIsRegister()));
        return getReminderFieldList(reminderItemDto, matchItem, rules);
    }

    private List<ReminderField> getReminderFieldList(ReminderItemDto reminderItemDto, MatchItemDto matchItem, List<TzsJgColumnReminderRule> rules) {
        List<TzsJgColumnReminderRule> equCategoryMatch = new ArrayList<>();
        List<TzsJgColumnReminderRule> equListMatch = new ArrayList<>();
        // 特殊不一样的配置设备类别
        if (matchItem.getEquCategory() != null) {
            equCategoryMatch = rules.stream().filter(r -> r.getEquCategory() != null && r.getEquCategory().contains(matchItem.getEquCategory())).collect(Collectors.toList());
        }
        // 和设备类别没关系配置设备种类
        if (matchItem.getEquList() != null) {
            equListMatch = rules.stream().filter(r -> r.getEquList().contains(matchItem.getEquList())).collect(Collectors.toList());
        }
        Set<TzsJgColumnReminderRule> reminderRules = new HashSet<>(Stream.concat(equCategoryMatch.stream(), equListMatch.stream()).collect(Collectors.toMap(TzsJgColumnReminderRule::getColumnKey, Function.identity(), (O1, O2) -> O1)).values());
        return reminderRules.stream().filter(e -> !containKeyAndValue(reminderItemDto.getDetailData(), e.getColumnKey())).map(e -> {
            ReminderField reminderField = new ReminderField();
            reminderField.setColumnKey(e.getColumnKey());
            reminderField.setColumnLabel(e.getColumnLabel());
            reminderField.setColumnValue(e.getColumnValue());
            reminderField.setSId(e.getSId());
            return reminderField;
        }).collect(Collectors.toList());
    }

    private List<ReminderField> buildRemindItem(ReminderItemDto reminderItemDto, MatchItemDto matchItem) {
        // regType默认0-新增，不同regType对应不同字段时，配置多行
        List<TzsJgColumnReminderRule> rules = reminderRuleService.list(new LambdaQueryWrapper<TzsJgColumnReminderRule>()
                .eq(TzsJgColumnReminderRule::getBizType, matchItem.getBizType())
                .eq(StringUtils.isNotEmpty(matchItem.getRegType()), TzsJgColumnReminderRule::getRegType, matchItem.getRegType())
                .eq(TzsJgColumnReminderRule::getWhetherVehicleCylinder, matchItem.getWhetherVehicleCylinder())
                .eq(BaseEntity::getIsDelete, false)
                .eq(matchItem.getIsRegister() != null, TzsJgColumnReminderRule::getIsRegister, matchItem.getIsRegister()));
        return getReminderFieldList(reminderItemDto, matchItem, rules);
    }

    private boolean containKeyAndValue(Map<String, Object> detailData, String columnKey) {
        return Arrays.stream(columnKey.split(",")).anyMatch(k -> detailData.containsKey(k) && ObjectUtils.isNotEmpty(detailData.get(k)));
    }
}
