package com.bocloud.cmp.provider.convertor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: BeanJsonConvertor<T>
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2019/7/26 14:05
 */
public interface BeanJsonConvertor<T> {

    default T convertModel(JSONObject object) {
        return null;
    }

    default List<T> convertList(JSONArray array) {
        return Optional.ofNullable(array)
                .map(list -> list.stream()
                        .map(JSON::toJSONString)
                        .map(JSON::parseObject)
                        .map(this::convertModel)
                        .collect(Collectors.toList()))
                .orElse(new ArrayList<>());
    }

    //需要形参时 使用
    default T convertModelParams(JSONObject object, String... params) {
        return null;
    }

    //需要形参时 使用
    default List<T> convertListParams(JSONArray array, String... params) {
        return Optional.ofNullable(array)
                .map(list -> list.stream()
                        .map(JSON::toJSONString)
                        .map(JSON::parseObject)
                        .map(jsonObject -> this.convertModelParams(jsonObject, params))
                        .collect(Collectors.toList()))
                .orElse(new ArrayList<>());
    }

}
