package com.ruoyi.loanpricing.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.loanpricing.domain.dto.ModelInvokeDTO;
import com.ruoyi.loanpricing.domain.entity.ModelCorpOutputFields;
import com.ruoyi.loanpricing.domain.entity.ModelRetailOutputFields;
import org.springframework.beans.factory.annotation.Value;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * @Author 吴凯程
 * @Date 2025/12/11
 **/
@Service
@Slf4j
@EnableAsync
public class ModelService {

    @Value("${model.personal-url}")
    private String personalModelUrl;

    @Value("${model.corporate-url}")
    private String corporateModelUrl;


    public ModelRetailOutputFields invokePersonalModel(ModelInvokeDTO modelInvokeDTO) {
        JSONObject mappingOutputFields = invokeModel(personalModelUrl, modelInvokeDTO);
        return JSON.parseObject(mappingOutputFields.toJSONString(), ModelRetailOutputFields.class);
    }

    public ModelCorpOutputFields invokeCorporateModel(ModelInvokeDTO modelInvokeDTO) {
        JSONObject mappingOutputFields = invokeModel(corporateModelUrl, modelInvokeDTO);
        return JSON.parseObject(mappingOutputFields.toJSONString(), ModelCorpOutputFields.class);
    }

    private JSONObject invokeModel(String modelUrl, ModelInvokeDTO modelInvokeDTO) {
        Map<String, String> requestBody = entityToMap(modelInvokeDTO);
        JSONObject response = HttpUtils.doPostFormUrlEncoded(modelUrl, requestBody, null, JSONObject.class);
        log.info("------------------->调用模型返回结果:" + JSON.toJSONString(response));
        if(Objects.nonNull(response) && response.containsKey("code") && response.getInteger("code") == 10000){
            return response.getJSONObject("data").getJSONObject("mappingOutputFields");
        }else{
            log.error("------------------->调用模型失败,失败原因为:" + response.getString("message"));
            throw new ServiceException("调用模型失败");
        }
    }

    /**
     * 使用FastJSON将实体类转换为Map<String, String>
     * @param obj 待转换的实体类对象
     * @return 转换后的Map
     */
    public static Map<String, String> entityToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        // 先转为JSON字符串，再转换为指定类型的Map
        String jsonStr = JSON.toJSONString(obj);
        return JSON.parseObject(jsonStr, new TypeReference<Map<String, String>>() {});
    }







}
