package com.ruoyi.common.utils.form;

import com.ruoyi.common.config.form.FormProperties;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


/**
 * 共通下发流程节点或脚本请求
 *
 * @param <T>
 */
@Component
public class FromUtils<T> {

    @Autowired  // 共通接口地址
    private FormProperties formProperties;

    // 创建RestTemplate实例
    RestTemplate restTemplate = new RestTemplate();

    /**
     * 执行流程排产
     */
    public HttpStatus runBpmProductionScheduling(T param) {


        // 得到当前用户的token  下发流程请求需要携带
        String token = SecurityUtils.getLoginUser().getToken();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "XIAFA" + token);
        // 构造请求体
        // Map<String, Object> requestBody = new HashMap<>();
        // 将请求体和请求头添加到HttpEntity
        HttpEntity<Map<String, Object>> requestEntity = (HttpEntity<Map<String, Object>>) new HttpEntity<>(param, headers);
        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(formProperties.runBpmIp, HttpMethod.POST, requestEntity, String.class);
        // 处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            System.err.println("Response: " + responseBody);
            return response.getStatusCode();
        } else {
            // System.out.println("Request failed with status code: " + response.getStatusCode());
            return response.getStatusCode();
        }
    }

    /**
     * 触发脚本
     */
    public HttpStatus triggerScript(T param) {
        // 得到当前用户的token  下发流程请求需要携带
        String token = SecurityUtils.getLoginUser().getToken();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "XIAFA" + token);
        // 构造请求体
        // Map<String, Object> requestBody = new HashMap<>();
        // 将请求体和请求头添加到HttpEntity
        HttpEntity<Map<String, Object>> requestEntity = (HttpEntity<Map<String, Object>>) new HttpEntity<>(param, headers);
        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(formProperties.runScriptIp, HttpMethod.POST, requestEntity, String.class);
        // 处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            System.out.println("Response: " + responseBody);
            return response.getStatusCode();
        } else {
            // System.out.println("Request failed with status code: " + response.getStatusCode());
            return response.getStatusCode();
        }
    }
}
