package com.cyksj.web.controller.manage.account;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.ChatgptSessionMapper;
import com.cyksj.model.entity.ChatgptSession;
import com.cyksj.model.views.ChatgptCarSessionView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.chatgpt.ChatGptAccountService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/** admin/镜像车队账号管理
 * 项目名: yhlxj
 * 文件名: CmsGptCarController
 * 创建者: JavaZou
 * 创建时间:2024/4/12 15:12
 */
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/manage/account/gptCar")
@RestController
public class CmsGptCarController {
	private final ChatGptAccountService chatGptAccountService;

	private final ChatgptSessionMapper chatgptSessionMapper;

	private final RedisService redisService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	/**
	 * 获取镜像车队账号列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<ChatgptCarSessionView>> getMirrorCarSession() {
		SearchResult<ChatgptCarSessionView> search = beanSearcher.search(ChatgptCarSessionView.class, MapUtils.flatBuilder(request.getParameterMap())
				.orderBy(ChatgptCarSessionView::getId).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 编辑镜像车队账号列表
	 */
	@PutMapping("/update")
	public Result<String> updateMirrorCarSession(@RequestBody ChatgptSession chatgptSession) {
		Long id = chatgptSession.getId();
		ChatgptSession dbChatSession = chatgptSessionMapper.selectById(id);
		if (!ObjectUtil.equal(dbChatSession.getEmail(), chatgptSession.getEmail()) || !ObjectUtil.equal(dbChatSession.getPassword(), chatgptSession.getPassword())) {
			String gptSession = chatGptAccountService.getGptSession(dbChatSession.getEmail(), dbChatSession.getPassword());
			chatgptSession.setOfficialSession(gptSession);
		}
		Integer selectCount = chatgptSessionMapper.selectCount(Wrappers.lambdaQuery(ChatgptSession.class)
				.and(e -> e.eq(ChatgptSession::getEmail, chatgptSession.getEmail())
						.or().eq(ChatgptSession::getCarId, chatgptSession.getCarId()))
				.ne(ChatgptSession::getId, chatgptSession.getId()));
		if (selectCount > 0) {
			throw BusinessRuntimeException.getInstance("请检验车队ID或账号是否已存在");
		}
		chatgptSessionMapper.updateById(chatgptSession);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除镜像车队账号
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deleteMirrorCarSession(@PathVariable Long id) {
		Optional.ofNullable(chatgptSessionMapper.selectById(id))
				.ifPresent(e -> {
					String carId = e.getCarId();
					if (StrUtil.isNotBlank(carId)) {
						chatgptSessionMapper.deleteById(e.getId());

						String highCarChatKey = RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId;
						String lowCarChatKey = RedisService.key.CHATGPT_CAR_LOW_CHAT.getName() + carId;
						//从zSet中删除车队
						String carScoresKey = RedisService.key.CHATGPT_CAR_SCORES.getName();
						redisService.zRemove(carScoresKey, carId);
						redisService.del(highCarChatKey);
						redisService.del(lowCarChatKey);
					}
				});
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 新增镜像车队账号
	 */
	@PostMapping("/post/mirror/car/session")
	public Result<String> postMirrorCarSession(@RequestBody ChatgptSession chatgptSession) {
		Integer selectCount = chatgptSessionMapper.selectCount(Wrappers.lambdaQuery(ChatgptSession.class)
				.eq(ChatgptSession::getCarId, chatgptSession.getCarId()).or().eq(ChatgptSession::getEmail, chatgptSession.getEmail()));
		if (selectCount > 0) {
			throw BusinessRuntimeException.getInstance("请检验车队ID或账号是否已存在");
		}
		String gptSession = chatGptAccountService.getGptSession(chatgptSession.getEmail(), chatgptSession.getPassword());
		chatgptSession.setIsCar(true);
		chatgptSession.setOfficialSession(gptSession);
		chatgptSessionMapper.insert(chatgptSession);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}
}
