package com.jkcredit.invoice.hub.controller.base;

import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.Result;
import com.baidu.unbiz.fluentvalidator.jsr303.HibernateSupportedValidator;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.validation.Validator;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toSimple;

/**
 * @description:
 * @author: xusonglin
 * @create: 2019/12/29 20:23
 * @version: V1.0
 **/
public class BaseResource {

    @Autowired
    private Validator validator;

    protected ModelMapper mapper;

    protected <T> void validate(T fb) {
        // todo 目前校验返回格式不对，字段不存在才返回，需要增加正则非空判断
        Result result = FluentValidator.checkAll()
                .on(fb, new HibernateSupportedValidator<T>().setHiberanteValidator(validator))
                .doValidate()
                .result(toSimple());

        if (!result.isSuccess()) {
            throw new ServiceException(result.getErrors().toString());
        }
    }

    @PostConstruct
    protected void initMapper() {
        mapper = new ModelMapper();
    }
}
