package com.mortals.xhx.busiz.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ILogService;
import com.mortals.framework.service.impl.FileLogServiceImpl;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.utils.IatModelMulMain;
import com.mortals.xhx.common.utils.IatModelMulUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.mortals.xhx.base.framework.exception.ExceptionHandle.*;

@RestController
@Slf4j
@RequestMapping("audio")
public class ApiSendMsgController {
    @Autowired
    protected ILogService logService = FileLogServiceImpl.getInstance();
    @Autowired
    private UploadService uploadService;

    private String hostUrl = "https://iat.cn-huabei-1.xf-yun.com/v1"; // 注意多语种识别，也支持中文音频
    private String appid = "3cc52607"; //在控制台-我的应用获取
    private String apiSecret = "ZTdmMjFjMGYxYmJhN2VmYjFlMTg3N2Rk"; // 在控制台-我的应用获取
    private String apiKey = "d0f73d44e996c2da9924c4476c578a30"; // 在控制台-我的应用获取


    @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamEvents() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(i -> "Event " + i);
    }

    @GetMapping(value = "/events/create", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamEventsCreate() {
        return Flux.create(sink -> {
            for (int i = 1; i <= 10; i++) {
                new Thread(() -> { // 需要异步执行，否则会阻塞
                    sink.next("Message ");
                    // 每秒发送一条数据
                }).start();

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            sink.complete(); // 结束流
        });
    }

    @GetMapping("/emitter")
    @UnAuth
    public SseEmitter test() throws IOException, InterruptedException {
        // filters.forEach(filter -> System.out.println("Loaded filter: " + filter.getClass().getName()));
        //每3s向前端推送消息
        SseEmitter emitter = new SseEmitter(30000L);
        for (int i = 0; i < 50; i++) {
            log.info("num:{}", i);
            emitter.send("后端推送信息" + i);

            Thread.sleep(1000);
        }
        emitter.complete();
        return emitter;
    }

    @RequestMapping(value = "upload")
    @UnAuth
    public String doFileUpload(MultipartFile file, @RequestParam(value = "prePath", defaultValue = "") String prePath) {
        Map<String, Object> model = new HashMap<>();
        String jsonStr = "";
        try {
            if (file == null || file.getSize() == 0L) throw new AppException("文件为空!");
            if (!"pcm".equalsIgnoreCase(FileUtil.getSuffix(file.getOriginalFilename())))
                throw new AppException("只支持pcm！");
            //if (file.getOriginalFilename())
            String filePath = uploadService.saveFileUpload(file, prePath, null);
            filePath = uploadService.getFilePath(filePath);

            log.info("filePath==>" + filePath);

           // byte[] bytes = file.getBytes();

            IatModelMulUtil iatModelMulUtil = new IatModelMulUtil(filePath, appid);

            String authUrl = IatModelMulUtil.getAuthUrl(hostUrl, apiKey, apiSecret);
            //log.info("authUrl==>" + authUrl);
            OkHttpClient client = new OkHttpClient.Builder().build();

            String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();

            WebSocket webSocket = client.newWebSocket(request, iatModelMulUtil);

            // 等待返回结果（阻塞直到收到完整数据或超时）
            String result = iatModelMulUtil.getResultFuture().get(60, TimeUnit.SECONDS);
            log.info("识别结果：" + result);
            model.put("result", result);
            // model.put("url", filePath);
            // model.put("fileName", file.getOriginalFilename());
            // model.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            jsonStr = JSONObject.toJSONString(model);
        } catch (AppException e) {
            log.error("异常", e);

            model.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            model.put(KEY_RESULT_MSG, e.getMessage());
            jsonStr = JSONObject.toJSONString(model);
        } catch (Exception e) {
            log.error("异常", e);
            model.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            model.put(KEY_RESULT_MSG, "文件上传失败");
            jsonStr = JSONObject.toJSONString(model);
        }
        return jsonStr;
    }

}
