package com.friday.custody.service.trustService.zx.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.friday.base.common.response.DubboResult;
import com.friday.custody.dto.InterProviderResponseDto;
import com.friday.custody.entity.InvokeRecordEntity;
import com.friday.custody.service.basicService.impl.InvokeRecordServiceImpl;
import com.friday.mystery.forwardapi.dto.DistributorGetDatePostResponseDto;
import com.friday.mystery.forwardapi.service.IHttpRequestService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ZxUtils {
    
    @Autowired
    private InvokeRecordServiceImpl invokeRecordService;

    public Map<String, Object> sendMessage(String resource, Map<String, List<String>> paramMaps, Integer startRow, Integer rowNum, String orderBy, List<String> selectedFields) throws InterruptedException {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"dubboContext.xml"});
        context.start();

        // 获取远程服务代理
        IHttpRequestService httpRequestService = (IHttpRequestService) context.getBean("httpRequestService");
        // 执行查询操作
        DubboResult<DistributorGetDatePostResponseDto> resultData = httpRequestService.getInformationByDistributor(resource, paramMaps, startRow, rowNum, orderBy, selectedFields);
        InterProviderResponseDto responseDto = getInterProviderResponse(resultData);
        log.info("从咨询平台查询行情指数:{}", resultData);
        //保存调用记录
        saveInvokeRecord("H000000", "99", resource, null, responseDto);
        JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(resultData));
        return result;
    }
    public void saveInvokeRecord(String tenantName, String trustNo, String invokeType, JSONObject jsonObject, InterProviderResponseDto invokeResult) {
        Date now = new Date();
        InvokeRecordEntity invokeRecordEntity = InvokeRecordEntity.builder()
                .trustNo(trustNo)
                .admin(tenantName)
                .invokeType(invokeType)
                .reqParam(JSON.toJSONString(jsonObject))
                .invokeTime(now)
                .invokeResult(JSON.toJSONString(invokeResult))
                .queryKey(tenantName + "::" + trustNo + "::" + invokeType)
                .createTime(now)
                .updateTime(now)
                .build();
        invokeRecordService.save(invokeRecordEntity);
    }

    private InterProviderResponseDto getInterProviderResponse(DubboResult<DistributorGetDatePostResponseDto> resultData){
        if (resultData == null) {
            return InterProviderResponseDto.builder().success(false).failMsg("资讯接口调用失败，返回结果为空！").build();
        }
        if (resultData.success()) {
            DistributorGetDatePostResponseDto responseDto = resultData.getObject();
            if (responseDto.getRetCode() == 0) {
                String value = JSON.toJSONString(responseDto.getValue());
                if (StringUtils.isNotEmpty(value)) {
                    return JSON.parseObject(value, InterProviderResponseDto.class);
                }
            } else {
                return InterProviderResponseDto.builder().success(false).failMsg(responseDto.getMessage()).build();
            }
        }
        return InterProviderResponseDto.builder().success(false).failMsg(resultData.getError() + resultData.getMessage()).build();
    }
}
