//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.prolog.upcloud.base.wh.operate.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.framework.bz.common.search.FieldMapping;
import com.prolog.framework.bz.common.search.SearchException;
import com.prolog.framework.bz.core.util.ObjectUtils;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.utils.ClassUtils;
import com.prolog.framework.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SearchApi {
    private static Logger logger = LoggerFactory.getLogger(SearchApi.class);
    @Autowired
    private RestTemplate restTemplate;
    @Value("${prolog.serarch.url:http://service-data-api/search}")
    private String url;

    public SearchApi() {
    }

    public String getUrl() {
        return this.url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public <T> List<T> search(String apiId, Map<String, Object> params, Class<T> clz) throws SearchException, JsonProcessingException, InstantiationException, IllegalAccessException {
        String data = this.searchData(apiId, params);
        RestMessage rest = null;

        try {
            rest = RestMessage.parseJsonStringForList(data, new TypeReference<RestMessage<List<T>>>() {
            });
        } catch (IOException var8) {
            throw new SearchException("查询失败," + var8.getMessage());
        }

        if (rest.isSuccess()) {
            List list = (List)rest.getData();
            List<T> result = this.setInstanceValue(list, (List)null, clz);
            return result;
        } else {
            throw new SearchException("查询失败," + rest.getMessage());
        }
    }

    public <T> List<T> search(String apiId, Map<String, Object> params, List<FieldMapping> fieldMappings, Class<T> clz) throws SearchException, IllegalAccessException, InstantiationException, JsonProcessingException {
        String data = this.searchData(apiId, params);
        logger.info("查询服务查询所得数据->" + data);
        RestMessage rest = null;

        try {
            rest = RestMessage.parseJsonStringForList(data, new TypeReference<RestMessage<List<Map>>>() {
            });
        } catch (IOException var9) {
            throw new SearchException("查询失败," + var9.getMessage());
        }

        if (rest.isSuccess()) {
            List list = (List)rest.getData();
            List<T> result = this.setInstanceValue(list, fieldMappings, clz);
            return result;
        } else {
            throw new SearchException("查询失败," + rest.getMessage());
        }
    }

    public List<Map> searchForMap(String apiId, Map<String, Object> params) throws SearchException, IllegalAccessException, InstantiationException, JsonProcessingException {
        String data = this.searchData(apiId, params);
        RestMessage rest = null;

        try {
            logger.info("查询服务查询所得数据->" + data);
            rest = RestMessage.parseJsonStringForList(data, new TypeReference<RestMessage<List<Map>>>() {
            });
        } catch (IOException var6) {
            throw new SearchException("查询失败," + var6.getMessage());
        }

        if (rest.isSuccess()) {
            List list = (List)rest.getData();
            return list;
        } else {
            throw new SearchException("查询失败," + rest.getMessage());
        }
    }

    private <T> List<T> setInstanceValue(List list, List<FieldMapping> fieldMappings, Class<T> clz) throws SearchException, IllegalAccessException, InstantiationException {
        List<T> dlist = new ArrayList();
        if (ObjectUtils.isNull(list)) {
            return dlist;
        } else {
            list.stream().forEach((x) -> {
                Map map = (Map)x;

                try {
                    T t = clz.newInstance();
                    map.forEach((k, v) -> {
                        String property = this.getPropertyName((String) k, fieldMappings);
                        ClassUtils.setFieldValue(property, t, v);
                    });
                    dlist.add(t);
                } catch (InstantiationException var7) {
                    ;
                } catch (IllegalAccessException var8) {
                    ;
                }

            });
            return dlist;
        }
    }

    private String getPropertyName(String columnName, List<FieldMapping> fieldMappings) {
        if (fieldMappings != null && fieldMappings.size() != 0) {
            String pname = (String)fieldMappings.stream().filter((x) -> {
                return x.getColumn().equalsIgnoreCase(columnName);
            }).findFirst().map((y) -> {
                return y.getProperty();
            }).orElse(columnName);
            return pname;
        } else {
            return columnName;
        }
    }

    private String searchData(String apiId, Map<String, Object> params) throws SearchException, JsonProcessingException {
        if (this.restTemplate == null) {
            throw new SearchException("查询失败,RestTemplate为null");
        } else {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            Map map = new HashMap();
            map.put("num", apiId);
            map.put("params", params);
            HttpEntity<String> formEntity = new HttpEntity(JsonUtils.toString(map), headers);
            String string = JsonUtils.toString(map);
            logger.info("查询服务入参->" + string);
            String data = (String)this.restTemplate.postForObject(this.url, formEntity, String.class, new Object[0]);
            return data;
        }
    }

//    public static void main(String[] args) throws InstantiationException, IllegalAccessException, JsonProcessingException {
//        new RestTemplate();
//        SearchApi api = new SearchApi();
//        api.setUrl("http://192.168.1.88:31533/search");
//        List<Map> models = api.search("querylocator", MapUtils.put("warehouseId", "901884530611326976")
//                .put("itemId","ssssslhbh002").put("currentUser.enterpriseId","900356013474058240").getMap(), Map.class);
//        System.out.println(((TestModel)models.get(0)).getP_email_addr());
//    }
}
