package com.izouma.wenlvju.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.izouma.wenlvju.domain.Organization;
import com.izouma.wenlvju.domain.Rate;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.OrganizationRepo;
import com.izouma.wenlvju.repo.RateAuditRepo;
import com.izouma.wenlvju.repo.RateExpertAuditRepo;
import com.izouma.wenlvju.repo.RateRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

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

@Service
@AllArgsConstructor
public class OrganizationService {

    private final OrganizationRepo    organizationRepo;
    private final RateRepo            rateRepo;
    private final RateAuditRepo       rateAuditRepo;
    private final RateExpertAuditRepo rateExpertAuditRepo;

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

    public void saveRate(Rate rate) {
        Organization organization = organizationRepo.findById(rate.getOrganizationId())
                .orElseThrow(new BusinessException("无承办单位"));
        boolean flag = false;
        if (StrUtil.isBlank(organization.getOwner())) {
            organization.setOwner(rate.getOwner());
            flag = true;
        }
        if (StrUtil.isBlank(organization.getOwnerEmail())) {
            organization.setOwnerEmail(rate.getOwnerEmail());
            flag = true;
        }
        if (StrUtil.isBlank(organization.getOwnerPhone())) {
            organization.setOwnerPhone(rate.getOwnerPhone());
            flag = true;
        }
        if (flag) {
            organizationRepo.save(organization);
        }
    }

    public void del(Long id) {
        List<Rate> rates = rateRepo.findAllByOrganizationId(id);
        List<Long> rateIds = rates.stream().map(Rate::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(rateIds)) {
            // 评分审核记录
            rateAuditRepo.softDeleteByRateIdIn(rateIds);
            // 评分细则
            rateExpertAuditRepo.softDeleteByRateIdIn(rateIds);
        }

        // 评定申请
        rateRepo.softDeleteByOrganizationId(id);
        organizationRepo.softDelete(id);
    }
}
