package com.yd.csf.service.helper;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class FeignResultHelper {

    @Resource
    private ObjectMapper objectMapper;

    public <T> T extractData(Result<T> result) {
        if (result == null) {
            throw new BusinessException(ResultCode.FAIL.getCode(), "远程调用返回null");
        }
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException(result.getCode(), result.getMsg());
        }
        return result.getData();
    }

    public <T> List<T> extractListData(Result<?> result, Class<T> elementType) {
        if (result == null) {
            throw new BusinessException(ResultCode.FAIL.getCode(), "远程调用返回null");
        }
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException(result.getCode(), result.getMsg());
        }

        Object data = result.getData();
        if (data == null) {
            throw new BusinessException(ResultCode.FAIL.getCode(), "远程调用 result.getData() 为 null");
        }

        if (data instanceof List) {
            if (((List<?>) data).isEmpty()) {
                throw new BusinessException(ResultCode.FAIL.getCode(), "远程调用 result.getData() 为 []");
            }

            return objectMapper.convertValue(
                    data,
                    objectMapper.getTypeFactory().constructCollectionType(
                            List.class, elementType
                    )
            );
        } else {
            throw new BusinessException(ResultCode.FAIL.getCode(), "返回数据类型错误");
        }
    }
}