package org.qinan.safetyeval.domain.service;

import org.qinan.safetyeval.domain.entity.QualFilingExpertEntity;
import org.qinan.safetyeval.domain.exception.BizException;
import org.qinan.safetyeval.domain.exception.ErrorCode;
import org.qinan.safetyeval.domain.gateway.QualFilingExpertGateway;
import org.qinan.safetyeval.domain.query.PageResult;
import org.qinan.safetyeval.domain.query.QualFilingExpertQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 审核专家领域服务
 *
 * @author safety-eval
 */
@Service
public class QualFilingExpertDomainService {

    @Resource
    private QualFilingExpertGateway qualFilingExpertGateway;

    public QualFilingExpertEntity add(QualFilingExpertEntity entity) {
        assertAccountUnique(entity.getAccount(), null);
        return qualFilingExpertGateway.save(entity);
    }

    public QualFilingExpertEntity get(Long id) {
        return qualFilingExpertGateway.get(id);
    }

    public QualFilingExpertEntity modify(QualFilingExpertEntity entity) {
        QualFilingExpertEntity existing = qualFilingExpertGateway.get(entity.getId());
        if (existing == null) {
            throw new BizException(ErrorCode.QUAL_FILING_EXPERT_NOT_FOUND);
        }
        assertAccountUnique(entity.getAccount(), entity.getId());
        return qualFilingExpertGateway.modify(entity);
    }

    public void delete(Long id) {
        QualFilingExpertEntity existing = qualFilingExpertGateway.get(id);
        if (existing == null) {
            throw new BizException(ErrorCode.QUAL_FILING_EXPERT_NOT_FOUND);
        }
        qualFilingExpertGateway.delete(id);
    }

    public PageResult<QualFilingExpertEntity> page(QualFilingExpertQuery query) {
        return qualFilingExpertGateway.page(query);
    }

    private void assertAccountUnique(String account, Long excludeId) {
        if (!StringUtils.hasText(account)) {
            return;
        }
        QualFilingExpertEntity found = qualFilingExpertGateway.getByAccount(account);
        if (found != null && (excludeId == null || !excludeId.equals(found.getId()))) {
            throw new BizException(ErrorCode.QUAL_FILING_EXPERT_ACCOUNT_EXISTS);
        }
    }
}
