package com.yice.webadmin.app.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yice.common.core.object.ResponseResult;
import com.yice.common.log.annotation.OperationLog;
import com.yice.common.log.model.constant.SysOperationLogType;
import com.yice.webadmin.app.config.PythonConfig;
import com.yice.webadmin.app.service.ProxyPythonService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;

@Api(tags = "接收python消息接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/receive")
public class ReceivePythonController {
    @Autowired
    private PythonConfig pythonConfig;
    @Autowired
    private ProxyPythonService proxyPythonService;
    private final WebClient webClient;

    public ReceivePythonController(WebClient webClient) {
        this.webClient = webClient;
    }

    @OperationLog(type = SysOperationLogType.OTHER)
    @PostMapping("/originalPredict")
    public Mono<String> originalPredict(@RequestBody String requestBody) throws JsonProcessingException {
        return webClient.post()
                .uri(this.pythonConfig.getFactoryInterface())
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(new ObjectMapper().readTree(requestBody))
                .retrieve()
                .bodyToMono(String.class);
    }

    @OperationLog(type = SysOperationLogType.OTHER)
    @PostMapping("/predict")
    public ResponseResult<String> predict(@RequestBody String requestBody) throws IOException {
        return ResponseResult.success(this.proxyPythonService.predictPost(pythonConfig.getFactoryInterface(), requestBody));
    }
}
