package com.izouma.wenlvju.service;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.wenlvju.domain.Rate;
import com.izouma.wenlvju.domain.RateAudit;
import com.izouma.wenlvju.domain.RateExpertAudit;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.enums.OrganizationGrade;
import com.izouma.wenlvju.enums.RateStatus;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RateAuditRepo;
import com.izouma.wenlvju.repo.RateExpertAuditRepo;
import com.izouma.wenlvju.repo.RateRepo;
import com.izouma.wenlvju.service.sms.NjwlSmsService;
import com.izouma.wenlvju.utils.JpaUtils;
import com.izouma.wenlvju.utils.ObjUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class RateExpertAuditService {

    private final RateExpertAuditRepo rateExpertAuditRepo;
    private final RateRepo            rateRepo;
    private final NjwlSmsService      njwlSmsService;
    private final RateAuditRepo       rateAuditRepo;

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

    public void batchSave(List<RateExpertAudit> audits) {
        audits.forEach(record -> {
            if (record.getId() != null) {
                RateExpertAudit orig = rateExpertAuditRepo.findById(record.getId())
                        .orElseThrow(new BusinessException("无记录"));
                ObjUtils.merge(orig, record);
                rateExpertAuditRepo.save(orig);
            } else {
                RateExpertAudit orig = rateExpertAuditRepo.findByRateIdAndType(record.getRateId(), record.getType());
                if (ObjectUtil.isNotNull(orig)) {
                    ObjUtils.merge(orig, record);
                    rateExpertAuditRepo.save(orig);
                } else {
                    rateExpertAuditRepo.save(record);
                }

            }
        });
    }

    public void grade(Long rateId, Long userId) {
        List<RateExpertAudit> audits = rateExpertAuditRepo.findAllByRateId(rateId);
        int sum = audits.stream().mapToInt(RateExpertAudit::getExpertScore).sum();
        OrganizationGrade grade;
        if (sum >= 40) {
            grade = OrganizationGrade.EXCELLENT;
        } else if (sum >= 20) {
            grade = OrganizationGrade.ELIGIBLE;
        } else {
            grade = OrganizationGrade.NOT_ELIGIBLE;
        }
        Rate rate = rateRepo.findById(rateId).orElseThrow(new BusinessException("无申请"));
        rate.setScore(sum + 40);
        rate.setGrade(grade);
        rate.setStatus(RateStatus.SUBMIT_PAPER_MATERIALS);
        rateRepo.save(rate);
        RateAudit rateAudit = RateAudit.builder()
                .userId(userId)
                .rateId(rateId)
                .remark("市政管理员已评审完成，请你单位在5个工作日内将纸质申请材料（2份）送属地区文化行政主管部门。")
                .status(RateStatus.SUBMIT_PAPER_MATERIALS)
                .build();
        rateAuditRepo.save(rateAudit);
        // 市区评分发送短信
        njwlSmsService.sendSms(rate.getOwnerPhone(), "请你单位在5个工作日内将纸质申请材料（2份）送属" + rate.getDistrict() + "文化和旅游局文化行政主管部门，预期不送，作自动放弃处理。");
    }
}
