package com.izouma.nineth.service;

import com.alibaba.fastjson.JSONArray;
import com.izouma.nineth.config.Constants;
import com.izouma.nineth.domain.DestroyRecord;
import com.izouma.nineth.domain.RecordRank;
import com.izouma.nineth.domain.SysConfig;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.DestroyRecordRepo;
import com.izouma.nineth.repo.RecordRankRepo;
import com.izouma.nineth.repo.SysConfigRepo;
import com.izouma.nineth.utils.JpaUtils;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class DestroyRecordService {

    private final SysConfigRepo sysConfigRepo;

    private DestroyRecordRepo destroyRecordRepo;

    private RecordRankRepo recordRankRepo;

    public Page<DestroyRecord> all(PageQuery pageQuery) {
        return destroyRecordRepo.findAll(JpaUtils.toSpecification(pageQuery, DestroyRecord.class), JpaUtils.toPageRequest(pageQuery));
    }

    public List<RecordRank> destroyRecordRank(String rare) {
        LocalDateTime countDateTime = LocalDateTime.of(2000, 1, 1, 0, 0, 0);
        String not = null;
        if (Constants.Rarity.SSR.equals(rare)) {
            not = Constants.Rarity.U_LIKE;
        }
        if (Constants.Rarity.SR.equals(rare)) {
            countDateTime = LocalDateTime.of(2022, 7, 23, 21, 0, 0);
            not = Constants.Rarity.SSR_LIKE;
        }
        if (Constants.Rarity.U.equals(rare)) {
            not = Constants.Rarity.SR_LIKE;
        }
        SysConfig sysConfig = sysConfigRepo.findByName(Constants.Rarity.ACTIVITY_RANK_ID).orElseThrow(new BusinessException("请先配置盲盒id"));
        if (StringUtil.isBlank(sysConfig.getValue())) {
            throw new BusinessException("请先配置盲盒id");
        }
        Long blindBoxId = Long.parseLong(sysConfig.getValue());
        List<Map<String, String>> map = destroyRecordRepo.destroyRecordRank(blindBoxId, "%" + rare + " #%", not, countDateTime);
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(map);
        List<RecordRank> recordRanks = jsonArray.toJavaList(RecordRank.class);
        List<RecordRank> dbRecordRanks = recordRankRepo.findAllByBlindBoxIdAndRareAndDel(blindBoxId, rare, Boolean.FALSE);
        if (CollectionUtils.isEmpty(dbRecordRanks)) {
            return recordRanks;
        }
        recordRanks.addAll(dbRecordRanks);
        recordRanks.sort(Comparator.comparingInt(RecordRank::getNum).reversed());
        return recordRanks;
    }
}
