package com.zkqy.common.utils.http;

import com.zkqy.common.config.bpm.BpmProperties;
import com.zkqy.common.core.domain.AjaxResult;
import com.zkqy.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.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


@Component
public class Sending<T> {

    @Autowired
    private BpmProperties bpmProperties;

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

    /**
     * get请求拼接参数使用
     *
     * @param url
     * @param obj  map类型或实体类型
     * @return
     */
    private String appendParamsToUrl(String url, T obj) {
        Map<String, Object> params = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                String fieldName = field.getName();
                Object fieldValue = field.get(obj);

                if (fieldValue != null) {
                    if (field.getType() == Map.class) {
                        // 如果字段是 Map 类型，将其拼接到 URL
                        Map<String, Object> mapFieldValue = (Map<String, Object>) fieldValue;
                        for (Map.Entry<String, Object> entry : mapFieldValue.entrySet()) {
                            params.put(fieldName + "[" + entry.getKey() + "]", entry.getValue());
                        }
                    } else {
                        // 处理其他类型的字段
                        params.put(fieldName, fieldValue);
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if (!params.isEmpty()) {
            StringBuilder urlBuilder = new StringBuilder(url);
            urlBuilder.append("?");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() instanceof Collection && ((Collection<?>) entry.getValue()).isEmpty()) {
                    // 如果值是集合且为空，跳过拼接
                    continue;
                }
                urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = urlBuilder.toString();
        }

        return url;
    }


    public ResponseEntity<String> sendCommon(String url, String httpMethod, T param) {
        // 得到当前用户的token  下发流程请求需要携带
        String token = SecurityUtils.getLoginUser().getToken();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "XIAFA" + token);
        // 判断请求类型
        if (HttpMethod.GET.name().equalsIgnoreCase(httpMethod)) {
            // 如果是 GET 请求，将参数拼接到 URL 上
            url = appendParamsToUrl(url, param);
        }
        // 将请求体和请求头添加到 HttpEntity
        HttpEntity<Object> requestEntity = new HttpEntity<>(param, headers);
        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.resolve(httpMethod), requestEntity, String.class);
        // 返回响应
        return response;
    }

    /**
     * 共通get请求，params传参形式
     * @param url 地址
     * @param param
     * @return
     */
    public ResponseEntity<AjaxResult> sendCommonGetParams(String url,T param){

        // 得到当前用户的token  下发流程请求需要携带
        String token = SecurityUtils.getLoginUser().getToken();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "XIAFA" + token);
        HttpEntity request = new HttpEntity(headers);
        ResponseEntity<AjaxResult> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                request,
                AjaxResult.class,
                param
        );
        return response;
    }

    /**
     * 执行流程排产 -> 共通修改
     */
    public ResponseEntity sendCommonUpdate(T param) {
        return this.sendCommon(bpmProperties.formCommonUpdateIp, "PUT", param);
    }

    /**
     * 根据脚本key得到所有异常脚本信息
     */
    public ResponseEntity sendGetScriptInfo(T param) {
        return this.sendCommon(bpmProperties.getNodeScriptsIp, "POST", param);
    }

    /**
     * 共通获取详情接口
     */
    public ResponseEntity sendCommonGetInfo(T param) {
        return this.sendCommon(bpmProperties.formCommonGetInfoIp, "GET", param);
    }

    /**
     * 通过字段类型得到当前租户字典的所有值
     */
    public ResponseEntity sendGetTenantDict(T param) {
        return this.sendCommon(bpmProperties.getTenantDictValIp, "GET", param);
    }

    /**
     * 根据scriptKey获取节点脚本详情接口
     */
    public ResponseEntity sendGetNodeScript(T param) {
        return this.sendCommonGetParams(bpmProperties.getNodeScriptIp,param);
    }

    /**
     * 查看角色下是否存在真实用户接口
     */
    public ResponseEntity sendQueryUserExistsByRoleKey(T param) {
        return this.sendCommonGetParams(bpmProperties.queryUserExistsByRoleKeyIp,param);
    }

    /**
     * 查看一组用户下是否存在真实用户接口
     */
    public ResponseEntity sendQueryUserExistsByUserIds(T param) {
        return this.sendCommonGetParams(bpmProperties.queryUserExistsByUserIdsIp,param);
    }

    /**
     * FORM_共通批量新增接口
     */
    public ResponseEntity sendCommonInsert(T param) {
        return this.sendCommon(bpmProperties.formCommonInsertIp, "POST", param);
    }

    /**
     * 根据fid获取表单详情接口
     */
    public ResponseEntity sendGetFormInfo(T param) {
        return this.sendCommonGetParams(bpmProperties.formGetFormInfoIp,param);
    }

    /**
     * 根据fid获取表格组详情接口
     */
    public ResponseEntity sendGetGroupInfo(T param) {
        return this.sendCommonGetParams(bpmProperties.getFormGetGroupInfoIp(),param);
    }

    /**
     * 获取模板库数据表信息接口
     */
    public ResponseEntity sendQueryTemplateBaseTable(){
        // 得到当前用户的token  下发流程请求需要携带
        String token = SecurityUtils.getLoginUser().getToken();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "XIAFA" + token);
        HttpEntity request = new HttpEntity(headers);
        ResponseEntity<AjaxResult> response = restTemplate.exchange(
                bpmProperties.crmQueryTemplateBaseTableIp,
                HttpMethod.GET,
                request,
                AjaxResult.class
        );;
        return response;
    }
}
