package com.cyksj.service.mini.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.mapper.mini.MiniPopularizeUserConversationChatMapper;
import com.cyksj.mapper.mini.MiniPopularizeUserMapper;
import com.cyksj.model.entity.MiniPopularizeUser;
import com.cyksj.model.entity.MiniPopularizeUserConversationChat;
import com.cyksj.redis.RedisService;
import com.cyksj.service.mini.MiniPopularizeCommonService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 项目名: yhlxj2
 * 文件名: MiniPopularizeCommonServiceImpl
 * 创建者: JavaZou
 * 创建时间:2025/4/11 11:46
 */
@Service
@RequiredArgsConstructor
public class MiniPopularizeCommonServiceImpl implements MiniPopularizeCommonService {

	private final RedisService redisService;

	private final MiniPopularizeUserMapper miniPopularizeUserMapper;

	private final MiniPopularizeUserConversationChatMapper conversationChatMapper;

	@Override
	public void recoverUserLimit(Long userId, Boolean recoverNum) {
		if (!recoverNum) {
			return;
		}
		miniPopularizeUserMapper.incrNum(userId, 1);
	}

	@Override
	public Boolean saveImgRecord(MiniPopularizeUserConversationChat record) {
		Long id = record.getId();
		if (id != null) {
			MiniPopularizeUserConversationChat dbChat = conversationChatMapper.selectById(id);
			if (StrUtil.isNotBlank(dbChat.getImg())) {
				//已更新 直接返回false
				return false;
			}
			conversationChatMapper.updateById(record);
		} else conversationChatMapper.insert(record);
		return true;
	}

	@Override
	public void recordChatEndOfAnswer(String conversationId, Long userId, String content, MiniPopularizeUserConversationChat.Role role) {
		MiniPopularizeUserConversationChat chat = MiniPopularizeUserConversationChat
				.builder()
				.conversationId(conversationId)
				.userId(userId)
				.content(content)
				.type(MiniPopularizeUserConversationChat.Type.text)
				.role(role).build();
		conversationChatMapper.insert(chat);
	}

	@Override
	public void incrGptTimes(long userId, Integer oriNum, Integer addNum) {
		int i = miniPopularizeUserMapper.incrNumSync(userId, oriNum, addNum);
		while (i == 0) {
			MiniPopularizeUser user = miniPopularizeUserMapper.selectOne(Wrappers.lambdaQuery(MiniPopularizeUser.class)
					.eq(MiniPopularizeUser::getUserId, userId)
					.last("limit 1"));
			if (user == null) {
				break;
			}
			oriNum = user.getNum();
			i = miniPopularizeUserMapper.incrNumSync(userId, oriNum, addNum);
		}
	}

	@Override
	public Boolean checkImageIsCompleted(Long imgRecordId) {
		MiniPopularizeUserConversationChat dbChat = conversationChatMapper.selectById(imgRecordId);
		if (dbChat == null || (dbChat.getType() == MiniPopularizeUserConversationChat.Type.image && StrUtil.isEmpty(dbChat.getImg()) && dbChat.getStatus() == MiniPopularizeUserConversationChat.Status.processing)) {
			return false;
		}
		return true;
	}
}
