package com.td.boss.game.complayerland.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.td.boss.common.service.CommonServiceImpl;
import com.td.boss.game.complayerland.pojo.ComPlayerDisasterProtected;
import com.td.boss.game.complayerland.repository.ComPlayerDisasterProtectedRepository;
import com.td.boss.game.complayerland.vo.ComPlayerDisasterEnum;
import com.td.boss.game.complayerland.vo.ComPlayerDisasterProtectedVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ComPlayerDisasterProtectedServiceImpl extends CommonServiceImpl<ComPlayerDisasterProtectedVo, ComPlayerDisasterProtected, String> implements ComPlayerDisasterProtectedService {
    @Autowired
    private ComPlayerDisasterProtectedRepository repository;

    /**
     * 按照用户编号获取 防护灾难 记录
     *
     * @param userId
     * @return
     */
    public List<ComPlayerDisasterProtected> getComPlayerDisasterProtectedByUserIdOrderByProtectTimeDesc(String userId) {
        return repository.getComPlayerDisasterProtectedsByUserId(userId);
    }

    /**
     * 购买灾难防护 自动延长时间
     * @param userId 购买者
     * @param comPlayerDisasterEnum 购买类型
     * @param days 购买天数
     */
    public void append(String userId, ComPlayerDisasterEnum comPlayerDisasterEnum, Integer days) {
        //获取购买过的历史防护
        List<ComPlayerDisasterProtected> protectedList = getComPlayerDisasterProtectedByUserIdOrderByProtectTimeDesc(userId);
        //获取 当前类型 防护时间 倒叙第一条作为最后防御时间
        Date protectTime = protectedList.stream()
                .filter(a -> a.getDsasterType().equals(comPlayerDisasterEnum.getCode()))
                .sorted(Comparator.comparing(ComPlayerDisasterProtected::getProtectTime).reversed())
                .map(ComPlayerDisasterProtected::getProtectTime).findFirst().orElse(new Date());

        ComPlayerDisasterProtectedVo comPlayerDisasterProtected = new ComPlayerDisasterProtectedVo();
        comPlayerDisasterProtected.setCreateTime(new Date());
        comPlayerDisasterProtected.setUserId(userId);
        comPlayerDisasterProtected.setDsasterType(comPlayerDisasterEnum.getCode());
        comPlayerDisasterProtected.setDsasterName(comPlayerDisasterEnum.getMsg());
        comPlayerDisasterProtected.setProtectTime(DateUtil.date(protectTime).offset(DateField.DAY_OF_YEAR, days));
        save(comPlayerDisasterProtected);
    }
}
