package org.qinan.safetyeval.domain.service;

import org.qinan.safetyeval.domain.constant.QualFilingStatusEnum;
import org.qinan.safetyeval.domain.entity.*;
import org.qinan.safetyeval.domain.exception.BizException;
import org.qinan.safetyeval.domain.exception.ErrorCode;
import org.qinan.safetyeval.domain.gateway.QualFilingGateway;
import org.qinan.safetyeval.domain.query.QualFilingQuery;
import org.qinan.safetyeval.domain.query.PageResult;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 资质备案申请领域服务
 *
 * @author safety-eval
 */
@Service
public class QualFilingDomainService {

    @Resource
    private QualFilingGateway qualFilingGateway;

    public QualFilingEntity add(QualFilingEntity entity) {
        return qualFilingGateway.save(entity);
    }

    public QualFilingEntity get(Long id) {
        return qualFilingGateway.get(id);
    }

    public QualFilingEntity modify(QualFilingEntity entity) {
        QualFilingEntity existing = qualFilingGateway.get(entity.getId());
        if (existing == null) {
            throw new BizException(ErrorCode.QUAL_FILING_NOT_FOUND);
        }
        return qualFilingGateway.modify(entity);
    }

    public void delete(Long id) {
        QualFilingEntity existing = qualFilingGateway.get(id);
        if (existing == null) {
            throw new BizException(ErrorCode.QUAL_FILING_NOT_FOUND);
        }
        qualFilingGateway.delete(id);
    }

    public PageResult<QualFilingEntity> page(QualFilingQuery query) {
        return qualFilingGateway.page(query);
    }

    public Long aggregationSaveOrEdit(QualFilingEntity entity, QualFilingCommitmentEntity commitmentEntity, List<QualFilingEquipmentEntity> equipmentEntities, List<QualFilingMaterialEntity> materialEntities, List<QualFilingPersonnelEntity> personnelEntities, List<QualFilingPersonnelCertEntity> personnelCertEntities) {
        return qualFilingGateway.aggregationSaveOrEdit(entity, commitmentEntity, equipmentEntities, materialEntities, personnelEntities, personnelCertEntities);
    }

    public void review(Long filingId, String reviewResult, String reviewResultRemark, Long filingExpertId, String filingExpertName, String reviewOpinion) {
        QualFilingEntity filing = qualFilingGateway.get(filingId);
        if (filing == null || filing.getFilingStatusCode() == null
                || filing.getFilingStatusCode() != QualFilingStatusEnum.REVIEWING.getCode()) {
            throw new BizException(ErrorCode.QUAL_FILING_STATUS_INVALID);
        }
        qualFilingGateway.review(filingId, reviewResult, reviewResultRemark, filingExpertId, filingExpertName, reviewOpinion);
    }
}
