package cn.quant.baa.pay.service;

import cn.quant.baa.pay.context.TransactionSession;
import cn.quant.baa.pay.jpa.entity.AccountEntity;
import cn.quant.baa.pay.jpa.entity.AccountIds;
import cn.quant.baa.pay.jpa.entity.EntityBuilder;
import cn.quant.spring.IllegalParameterException;
import cn.quant.spring.NullException;
import cn.quant.spring.context.ContextLoader;
import cn.quant.spring.context.ServerApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Created by Administrator on 2021/8/25 0025.
 */
public abstract class BusinessService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessService.class);

    @Autowired
    private Validator validator;

    public <T> void validate(T t) {

        if (t == null) {
            throw new NullException();
        }

        Set<ConstraintViolation<T>> validate = validator.validate(t);
        if (validate.size() > 0) {
            ConstraintViolation<T> next = validate.iterator().next();
            String s = next.getPropertyPath().toString();
            String template = next.getMessageTemplate();
            ServerApplicationContext applicationContext = ContextLoader.getCurrentApplicationContext();
            String message = applicationContext.getMessage(template, "{0}-Illegal request parameter", (Object) s);
            throw new IllegalParameterException(message);
        }
    }

    public TransactionSession prepare(String institutionId, String productId, String buyerId, TransactionSession session) {

        if (session == null) {
            throw new NullException("Session is null.");
        }

        AccountIds ids = new AccountIds();
        ids.setInstitutionId(institutionId);
        ids.setAccountRefNo(buyerId);
        AccountEntity account = session.findOne(AccountEntity.class, ids);
        if (account == null) {
            Long id = session.nextId(buyerId.hashCode());
            account = EntityBuilder.account(ids, productId, id, buyerId, session.partitionKey(id));
            session.pushEntity(account);
        }

        session.setAccount(account);
        return session;
    }
}
