package com.izouma.wenlvju.service.performance;

import cn.hutool.core.collection.CollUtil;
import com.izouma.wenlvju.converter.LongArrayConverter;
import com.izouma.wenlvju.domain.User;
import com.izouma.wenlvju.domain.performance.Arrange;
import com.izouma.wenlvju.domain.performance.ArrangeJudge;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.UserRepo;
import com.izouma.wenlvju.repo.performance.ArrangeJudgeRepo;
import com.izouma.wenlvju.repo.performance.ArrangeRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class ArrangeJudgeService {

    private ArrangeJudgeRepo arrangeJudgeRepo;
    private ArrangeRepo      arrangeRepo;
    private UserRepo         userRepo;

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

    public void assignJudge(String experts, String arranges) {
        LongArrayConverter converter = new LongArrayConverter();
        List<Long> expertIds = converter.convertToEntityAttribute(experts);
        List<Long> arrangeIds = converter.convertToEntityAttribute(arranges);
        Arrange arrange = arrangeRepo.findById(arrangeIds.get(0)).orElseThrow(new BusinessException("无分组"));
        LocalDate date = arrange.getDate();
        boolean morning = arrange.isMorning();
        List<Long> arrangeJudges = arrangeJudgeRepo.findExpertByDateAndMorning(date, morning);
        if (CollUtil.isNotEmpty(arrangeJudges)) {
            expertIds.forEach(id -> {
                if (arrangeJudges.contains(id)) {
                    User user = userRepo.findById(id).orElseThrow(new BusinessException("无此评委"));
                    throw new BusinessException("该时间段，" + user.getNickname() + "已分配");
                }
            });
        }

        List<ArrangeJudge> save = new ArrayList<>();
        arrangeIds.forEach(arrangeId ->
                expertIds.forEach(expertId ->
                        save.add(ArrangeJudge.builder()
                                .arrangeId(arrangeId)
                                .date(date)
                                .morning(morning)
                                .expertId(expertId)
                                .build())));

        arrangeJudgeRepo.saveAll(save);

    }

    public void cancelAssign(String arranges) {
        LongArrayConverter converter = new LongArrayConverter();
        List<Long> arrangeIds = converter.convertToEntityAttribute(arranges);
        if (CollUtil.isEmpty(arrangeIds))
        arrangeJudgeRepo.cancelJudge(arrangeIds);
    }
}
