package com.cyksj.server.listener;


import cn.hutool.core.util.StrUtil;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.util.StringUtil;
import com.cyksj.model.entity.MiniPopularizeUserConversationChat;
import com.cyksj.model.gpt.Message;
import com.cyksj.service.mini.MiniPopularizeCommonService;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Slf4j
@Builder
public class ConsoleStreamListener extends AbstractStreamListener {

	final Long userId;

	final String conversationId;

	final Long imgRecordId;

	final MiniPopularizeCommonService miniPopularizeCommonService;

	//是否需要恢复次数
	final Boolean recoverNum;

	@Override
	public void onMsg(Object message) {
		Message delta = (Message) message;
		String content = delta.getContent();
		String img = null;
		if (StrUtil.isNotBlank(content)) {
			if (content.contains(Constant.GPT_FILE_DOMAIN) || content.contains(Constant.GPT_VIDEO_DOMAIN)) {
				String urlPattern = "\\bhttps?://[^\\s/$.?#].[^\\s]*\\b";
				Pattern pattern = Pattern.compile(urlPattern);
				Matcher matcher = pattern.matcher(content);
				while (matcher.find()) {
					img = matcher.group();
					break;
				}
				if (miniPopularizeCommonService.saveImgRecord(setImagRecord(imgRecordId, img, MiniPopularizeUserConversationChat.Status.success, content))) {
					//返回图片
					log.info("返回图片：{}", img);
				}
//				SendMessageUtil.sendMessage(userId, img);
				return;
			}

			if (content.contains("失败") || content.contains("Generation failed")) {
				//将用户使用次数返回
				miniPopularizeCommonService.recoverUserLimit(userId, recoverNum);
				miniPopularizeCommonService.saveImgRecord(setImagRecord(imgRecordId, img, MiniPopularizeUserConversationChat.Status.fail, content));
//				miniPopularizeCommonService.recordChatEndOfAnswer(conversationId, userId, "图片生成异常", MiniPopularizeUserConversationChat.Role.assistant);
			}
		}
		//任务已完成 但图未出
		if (content.contains("[DONE]")) {
			Boolean flag = miniPopularizeCommonService.checkImageIsCompleted(imgRecordId);
			if (!flag) {
				//将用户使用次数返回
				miniPopularizeCommonService.recoverUserLimit(userId, recoverNum);
				miniPopularizeCommonService.saveImgRecord(setImagRecord(imgRecordId, img, MiniPopularizeUserConversationChat.Status.fail, "任务结束，未出图"));
			}
		}
//		SendMessageUtil.sendMessage(userId, message);
	}

	@Override
	public void onError(Throwable throwable, String response) {
		//将用户使用次数返回
		miniPopularizeCommonService.recoverUserLimit(userId, recoverNum);
		miniPopularizeCommonService.saveImgRecord(setImagRecord(imgRecordId, null, MiniPopularizeUserConversationChat.Status.fail, StringUtil.getErrorText(throwable)));
		log.error("gpt对话异常，异常：{}", response);
//		Message message = Message.ofAssistant("图片生成异常");
//		SendMessageUtil.sendMessage(userId, message);
//		message = Message.ofAssistant("[DONE]");
//		SendMessageUtil.sendMessage(userId, message);
//		miniPopularizeCommonService.recordChatEndOfAnswer(conversationId, userId, "图片生成异常", MiniPopularizeUserConversationChat.Role.sys);
	}

	public MiniPopularizeUserConversationChat setImagRecord(Long imagRecordId, String img, MiniPopularizeUserConversationChat.Status status, String content) {
		String url = img;
//		if (StrUtil.isNotBlank(img)) {
//			try {
//				url = ImageUploadUtil.upload(img, "mgpt");
//			} catch (IOException e) {
//				url = img;
//			}
//		}
		if (StrUtil.isNotBlank(url)) {
			if (url.contains(Constant.GPT_VIDEO_DOMAIN)) {
				url = url.replaceAll(Constant.GPT_VIDEO_DOMAIN, Constant.GPT_VIDEO_REPLACE_DOMAIN);
			}
		}
		MiniPopularizeUserConversationChat build = MiniPopularizeUserConversationChat.builder()
				.conversationId(conversationId)
				.img(url)
				.type(MiniPopularizeUserConversationChat.Type.image)
				.content(content)
				.role(MiniPopularizeUserConversationChat.Role.assistant)
				.status(status).build();
		build.setId(imagRecordId);
		return build;
	}
}
