package com.izouma.zhirongip.service;

import com.izouma.zhirongip.domain.Information;
import com.izouma.zhirongip.domain.Personal;
import com.izouma.zhirongip.domain.User;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.dto.PersonalDTO;
import com.izouma.zhirongip.enums.ApplyStatus;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InformationRepo;
import com.izouma.zhirongip.repo.PersonalRepo;
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 PersonalService {

    private final PersonalRepo    personalRepo;
    private final UserRepo        userRepo;
    private final InformationRepo informationRepo;

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

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

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

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