package com.crm.activity.service.impl;

import com.crm.activity.dao.mapper.ActivityRaceRuleMapper;
import com.crm.activity.dao.repository.ActivityRaceRuleRepository;
import com.crm.activity.service.ActivityRaceRuleService;
import com.crm.rely.backend.core.dto.base.BaseLongSelectDto;
import com.crm.rely.backend.model.pojo.table.ActivityRaceRuleTable;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * @author y
 * @create 2022/7/21
 */
@Service
public class ActivityRaceRuleServiceImpl implements ActivityRaceRuleService {

    @Autowired
    private ActivityRaceRuleMapper activityRaceRuleMapper;
    @Autowired
    private ActivityRaceRuleRepository activityRaceRuleRepository;

    @Override
    public List<BaseLongSelectDto> getAllDropDownByType(Integer raceType) throws Exception {

        List<ActivityRaceRuleTable> tables = activityRaceRuleMapper.findAllLimitedByRaceType(raceType, 10);
        return convertTablesToDropDownDtos(tables);
    }

    @Override
    public List<BaseLongSelectDto> getDropDownForCustomByType(Long customId, Integer raceType) throws Exception {
        List<ActivityRaceRuleTable> tables = activityRaceRuleMapper.findAllLimitedByRaceType(raceType, 10);
        return convertTablesToDropDownDtos(tables);
    }

    @Override
    public Integer getNextSerialByRaceType(Integer raceType) throws Exception {

        Integer maxSerial = activityRaceRuleMapper.getMaxSerialByRaceType(raceType);
        return maxSerial + 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTable(ActivityRaceRuleTable table) throws Exception {
        activityRaceRuleRepository.save(table);
    }

    @Override
    public List<ActivityRaceRuleTable> findAllCaleRule(Date date) throws Exception {
        return activityRaceRuleMapper.findAllByDateBt(date);
    }

    @Override
    public Boolean existsByDate(Date startDate, Date endDate, Integer raceType) {
        Integer count = activityRaceRuleMapper.countByStartDateAndEndDateAndRaceType(startDate, endDate, raceType);
        return (count != null && count > 0);
    }

    private List<BaseLongSelectDto> convertTablesToDropDownDtos(List<ActivityRaceRuleTable> tables) {
        List<BaseLongSelectDto> dtos = Lists.newArrayList();
        if (CollectionUtils.isEmpty(tables)) {
            return dtos;
        }
        for (ActivityRaceRuleTable table : tables) {
            BaseLongSelectDto dto = new BaseLongSelectDto();
            dtos.add(dto);
            dto.setId(table.getSerial().longValue());
            dto.setVal(String.format("第%d期", table.getSerial()));
        }
        return dtos;
    }
}
