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

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.model.entity.ClaudeSession;
import com.cyksj.model.views.ClaudeCarSessionView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.claude.ClaudeSessionService;
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;

/**
 * @author chan
 * @date 2024/8/9 10:02
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/mirror/claude")
public class CmsClaudeController {

    private final BeanSearcher beanSearcher;

    private final ClaudeSessionService claudeSessionService;

    private final RedisService redisService;

    private final HttpServletRequest request;

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

    /**
     * 编辑镜像车队账号列表
     */
    @PutMapping("/update")
    public Result<String> updateMirrorCarSession(@RequestBody ClaudeSession claudeSession) {
        Long id = claudeSession.getId();
        ClaudeSession dbChatSession = claudeSessionService.getById(id);
        Integer sessionId = null;
        Boolean isUpdateSession = false;
        if (!ObjectUtil.equal(dbChatSession.getEmail(), claudeSession.getEmail()) || !ObjectUtil.equal(dbChatSession.getPassword(), claudeSession.getPassword())) {
            sessionId = claudeSessionService.getSession(dbChatSession.getEmail(), dbChatSession.getPassword(), claudeSession.getOfficialSession(), claudeSession.getIsPlus());
            isUpdateSession = true;
        }
        Integer selectCount = claudeSessionService.getBaseMapper().selectCount(Wrappers.lambdaQuery(ClaudeSession.class)
                .and(e -> e.eq(ClaudeSession::getEmail, claudeSession.getEmail())
                        .or().eq(ClaudeSession::getCarId, claudeSession.getCarId()))
                .ne(ClaudeSession::getId, claudeSession.getId()));
        if (selectCount > 0) {
            throw BusinessRuntimeException.getInstance("请检验车队ID或账号是否已存在");
        }
        if (isUpdateSession) {
            if (sessionId != null) {
                claudeSession.setStatus(1);
            } else claudeSession.setStatus(0);
        }
        claudeSessionService.updateById(claudeSession);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 删除镜像车队账号
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteMirrorCarSession(@PathVariable Long id) {
        Optional.ofNullable(claudeSessionService.getById(id))
                .ifPresent(e -> {
                    String carId = e.getCarId();
                    if (StrUtil.isNotBlank(carId)) {
                        claudeSessionService.removeById(e.getId());
                        String highCarChatKey = RedisService.key.CLAUDE_CAR_CHAT.getName() + carId;
                        redisService.del(highCarChatKey);
                    }
                });
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 新增镜像车队账号
     */
    @PostMapping("/post/mirror/car/session")
    public Result<String> postMirrorCarSession(@RequestBody ClaudeSession claudeSession) {
        Integer selectCount = claudeSessionService.getBaseMapper().selectCount(Wrappers.lambdaQuery(ClaudeSession.class)
                .eq(ClaudeSession::getCarId, claudeSession.getCarId()).or().eq(ClaudeSession::getEmail, claudeSession.getEmail()));
        if (selectCount > 0) {
            throw BusinessRuntimeException.getInstance("请检验车队ID或账号是否已存在");
        }
        claudeSessionService.getSession(claudeSession.getEmail(), claudeSession.getPassword(), claudeSession.getOfficialSession(), claudeSession.getIsPlus());
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

}
