package com.ruoyi.interfaces.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.CheckException;
import com.ruoyi.common.utils.OkHttpUtils;
import com.ruoyi.interfaces.domain.PtService;
import com.ruoyi.interfaces.domain.PtServiceReturn;
import com.ruoyi.interfaces.service.IPtServiceReturnService;
import com.ruoyi.interfaces.service.PtServiceService;
import com.ruoyi.interfaces.service.ServiceDataViewService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LinQiLong
 * @date 2022/2/14 19:15
 */
@Service
public class ServiceDataViewServiceImpl implements ServiceDataViewService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static final Map<String, String> HEADER_MAP = new HashMap<String, String>() {{
        put("Content-Type", "application/json; charset=utf-8");
    }};

    @Autowired
    private PtServiceService ptServiceService;

    @Autowired
    private IPtServiceReturnService ptServiceReturnService;

    @Override
    public Map<String, Object> getDataView(String srvId) {
        Map<String, Object> map = new HashMap<>(2);

        PtService ptService = ptServiceService.get(srvId);
        Optional.ofNullable(ptService).orElseThrow(() -> new CheckException("url invalid"));
        List<PtServiceReturn> ptServiceReturnList = ptServiceReturnService.selectPtServiceReturnBySrvId(srvId);

        //第二步：设置请求参数 ptService.getUrl()
        Map<String, Object> queryParams = new HashMap<>();
//        for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
//            if (entry.getValue().length <= 1) {
//                queryParams.put(entry.getKey(), entry.getValue()[0]);
//            } else {
//                List<String> paraValues = new ArrayList<>();
//                Collections.addAll(paraValues, entry.getValue());
//                queryParams.put(entry.getKey(), paraValues);
//            }
//        }

        String xmlInfo = null;
        try {
            if ("get".equalsIgnoreCase(ptService.getRqtype())) {
                xmlInfo = OkHttpUtils.getMap(ptService.getUrl(), queryParams);
            } else {
                xmlInfo = OkHttpUtils.postJson(ptService.getUrl(), JSON.toJSONString(queryParams), HEADER_MAP);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        List<Object> list = getList(JSONObject.parseObject(xmlInfo));
        list = Optional.ofNullable(list).orElse(new ArrayList<>());
        list = list.stream().limit(10).collect(Collectors.toList());
        map.put("return", ptServiceReturnList);
        map.put("list", list);
        return map;
    }

    private List getList(Map<String, Object> map) {
        if (null == map) {
            return new ArrayList<>();
        }

        List list = null;
        for (String key : map.keySet()) {
            Object obj = map.get(key);
            if (obj instanceof List) {
                return (List) obj;
            } else if (obj instanceof Map) {
                list = getList((Map) obj);
                if (list != null) {
                    return list;
                }
            }
        }
        return new ArrayList<>();
    }

}
