package cn.fateverse.query.handler.adapter.impl;

import cn.fateverse.common.core.exception.CustomException;
import cn.fateverse.query.entity.dto.MockParam;
import cn.fateverse.query.entity.bo.PortalBo;
import cn.fateverse.query.enums.PortalEnum;
import cn.fateverse.query.handler.adapter.AbstractDataAdapterHandler;
import cn.fateverse.query.handler.reader.EngineExecuteHandlerReader;
import cn.fateverse.query.mapper.DataAdapterMapper;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author Clay
 * @date 2024/4/19 22:12
 */
@Slf4j
@Service
public class ExternalDataAdapterHandler extends AbstractDataAdapterHandler {

    /**
     * 请求对象
     */
    private final RestTemplate restTemplate;

    public ExternalDataAdapterHandler(DataAdapterMapper dataAdapterMapper,
                                      EngineExecuteHandlerReader handlerReader,
                                      RestTemplate restTemplate) {
        super(dataAdapterMapper, handlerReader);
        this.restTemplate = restTemplate;
    }


    @Override
    public Object mockExecute(PortalBo portal, MockParam mockParam) {
        if (!PortalEnum.EXTERNAL.equals(portal.getType())) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HashMap<String, Object> map = new HashMap<>();
        JSONObject response = null;
        switch (portal.getRequestMethod()) {
            case "GET":
                response = restTemplate.getForObject(portal.getUrl(), JSONObject.class, map);
                break;
            case "POST":
                response = restTemplate.postForObject(portal.getUrl(), map, JSONObject.class);
                break;
            default:
                throw new CustomException("请求方式错误");
        }
        if (portal.getCreateDataAdapter()) {
            return super.execute(portal.getAdapterId(), response, true);
        } else {
            return response;
        }
    }

    @Override
    public Object execute(PortalBo portal, HttpServletRequest request) {
        return null;
    }
}
