package com.izouma.zhirongip.service;

import com.izouma.zhirongip.domain.Information;
import com.izouma.zhirongip.domain.Institution;
import com.izouma.zhirongip.domain.User;
import com.izouma.zhirongip.dto.InstitutionDTO;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.enums.ApplyStatus;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InformationRepo;
import com.izouma.zhirongip.repo.InstitutionRepo;
import com.izouma.zhirongip.repo.UserRepo;
import com.izouma.zhirongip.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class InstitutionService {

    private final InstitutionRepo institutionRepo;
    private final UserRepo        userRepo;
    private final InformationRepo informationRepo;

    public Page<InstitutionDTO> all(PageQuery pageQuery) {
        Page<Institution> all = institutionRepo.findAll(JpaUtils.toSpecification(pageQuery, Institution.class), JpaUtils
                .toPageRequest(pageQuery));
        List<Long> ids = all.getContent().stream().map(Institution::getUserId).collect(Collectors.toList());
        Map<Long, User> userMap = userRepo.findAllById(ids)
                .stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        return all.map(institution -> new InstitutionDTO(institution, userMap.get(institution.getUserId())));
    }

    public void audit(Long id, boolean pass, String remark) {
        Institution institution = institutionRepo.findById(id).orElseThrow(new BusinessException("无记录"));

        Information information = Information.builder()
                .receiveUserId(institution.getUserId())
                .isRead(false)
                .build();

        if (pass) {
            institution.setStatus(ApplyStatus.PASS);
            institutionRepo.save(institution);
            information.setContent("您的认证已通过审核！");
            informationRepo.save(information);
            return;
        }
        institution.setStatus(ApplyStatus.DENY);
        institutionRepo.save(institution);
        information.setContent("您的认证未通过审核，原因为：" + remark);
        informationRepo.save(information);
    }

}
