package com.xinda.iot.ruleEngine;

import com.alibaba.fastjson2.JSON;
import com.dtflys.forest.http.ForestRequest;
import com.xinda.http.service.HttpClientFactory;
import com.xinda.iot.domain.Bridge;
import com.xinda.iot.domain.HttpClient;
import com.xinda.iot.service.IBridgeService;
import com.xinda.iot.service.IHttpClientService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import org.springframework.beans.factory.annotation.Autowired;

@LiteflowComponent("httpBridge")
public class HttpBridge extends NodeComponent {

    @Autowired
    private IHttpClientService httpClientService;
    @Autowired
    private IBridgeService bridgeService;

    @Override
    public void process() throws Exception {
        // 获取上下文对象
        MsgContext cxt = this.getContextBean(MsgContext.class);
        Integer id = cxt.getData("httpBridgeID");
        Bridge bridge = bridgeService.selectBridgeById(Long.valueOf(id));
        if (bridge != null) {
            HttpClient config = JSON.parseObject(bridge.getConfigJson(), HttpClient.class);
            ForestRequest request = HttpClientFactory.instance(httpClientService.buildhttpclientconfig(config));
            if (config.getRequestBody() != "") {
                request.addBody(cxt.placeholders(config.getRequestBody()));
            } else {
                request.addBody(cxt.getPayload());
            }
            request.execute();
        }
    }
}
