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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.Result;
import com.baidu.unbiz.fluentvalidator.jsr303.HibernateSupportedValidator;
import com.jkcredit.invoice.hub.constant.CommonConstant;
import com.jkcredit.invoice.hub.enums.ApiResponseCodeEnum;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.spi.rest.data.ApiResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Validator;

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

/**
 * @description:
 * @author: xusonglin
 * @create: 2019/12/29 20:55
 * @version: V1.0
 **/
@Slf4j
public class BaseService {

    @Autowired
    private Validator validator;

    protected <T> void validate(T fb) {
        Result result = FluentValidator.checkAll()
                .on(fb, new HibernateSupportedValidator<T>().setHiberanteValidator(validator))
                .doValidate()
                .result(toSimple());

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

    protected ApiResponseData analyzeApiResultItems(String result) {
        try {
            JSONObject jsonObject = JSON.parseObject(result);
            String item = jsonObject.getString("items");
            return ApiResponseData.success(ApiResponseCodeEnum.CODE_200.getValue(), item);
        } catch (Exception e) {
            log.info("[-companyQuery-] 解析异常：" + e.getMessage());
            throw new com.jkcredit.invoice.hub.spi.lang.exception.ServiceException(CommonConstant.QUERY_FAILED);
        }
    }
}
