package com.mvc.service.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mvc.model.ResultGeekerModel;
import com.mvc.service.aihcxd.OnnxIdenService;
import com.mvc.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.util.Base64;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ServerIdenTest {
    private static final String SERVER_URL = "http://localhost:6060/api/v1/ai/watermeters/iden";

    private static Logger log = LoggerFactory.getLogger(OnnxIdenService.class);

    @Resource
    private RestTemplate restTemplate;

    public void test() {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        threadPool.execute(() -> testThread());
    }

    private void testThread() {
        for (int i = 0; i < 100; i++) {
            long pumpWellCode = 111001200001L;
            String path = "E:/download/ftp/2024image/";
            //path="E:/download/ftp/2024image";
            File dir = new File(path);
            String[] arrary = dir.list();
            try {
                for (String fileName : arrary) {
                    byte[] data = FileUtil.readBytesFile(path + fileName);
                    String image = Base64.getEncoder().encodeToString(data);

                    postInParam(String.valueOf(pumpWellCode), image);
                    pumpWellCode++;
                    Thread.sleep(100);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private void postInParam(String pumpWellCode, String image) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("pumpWellCode", pumpWellCode);
        map.add("image", image);
        map.add("replaceFlag", "0");

        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(SERVER_URL, entity, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            //log.info("服务侧识别结果:" + body);
            ResultGeekerModel aiIdenMap = JSON.parseObject(body, new TypeReference<>() {
            });

            String json = aiIdenMap.getData().toString();
            log.info("服务识别结果:[" + pumpWellCode + "]" + json);

        }
    }
}
