package shop.alien.lawyer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerAiInteractionLog;
import shop.alien.entity.store.vo.LawyerAiInteractionLogVo;
import shop.alien.lawyer.service.LawyerAiInteractionLogService;
import shop.alien.mapper.LawyerAiInteractionLogMapper;
import shop.alien.util.common.ListToPage;

import java.util.*;

/**
 * AI交互日志 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class LawyerAiInteractionLogServiceImpl extends ServiceImpl<LawyerAiInteractionLogMapper, LawyerAiInteractionLog> implements LawyerAiInteractionLogService {

    private final LawyerAiInteractionLogMapper aiInteractionLogMapper;

    @Override
    public R<IPage<LawyerAiInteractionLog>> getAiInteractionLogList(int pageNum, int pageSize, Integer clientUserId,
                                                               String conversationId, Integer problemScenarioId) {
        log.info("LawyerAiInteractionLogServiceImpl.getAiInteractionLogList?pageNum={},pageSize={},clientUserId={},conversationId={},problemScenarioId={}",
                pageNum, pageSize, clientUserId, conversationId, problemScenarioId);
        Page<LawyerAiInteractionLog> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LawyerAiInteractionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerAiInteractionLog::getDeleteFlag, 0);
        if (clientUserId != null) {
            queryWrapper.eq(LawyerAiInteractionLog::getClientUserId, clientUserId);
        }
        if (StringUtils.hasText(conversationId)) {
            queryWrapper.eq(LawyerAiInteractionLog::getConversationId, conversationId);
        }
        if (problemScenarioId != null) {
            queryWrapper.eq(LawyerAiInteractionLog::getProblemScenarioId, problemScenarioId);
        }
        queryWrapper.orderByDesc(LawyerAiInteractionLog::getInteractionTime);
        IPage<LawyerAiInteractionLog> pageResult = this.page(page, queryWrapper);
        return R.data(pageResult);
    }

    @Override
    public List<LawyerAiInteractionLog> getListByConversationId(String conversationId) {
        log.info("LawyerAiInteractionLogServiceImpl.getListByConversationId?conversationId={}", conversationId);
        LambdaQueryWrapper<LawyerAiInteractionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerAiInteractionLog::getConversationId, conversationId)
                .eq(LawyerAiInteractionLog::getDeleteFlag, 0)
                .orderByAsc(LawyerAiInteractionLog::getInteractionTime);
        return this.list(queryWrapper);
    }

    @Override
    public R<LawyerAiInteractionLog> addAiInteractionLog(LawyerAiInteractionLog aiInteractionLog) {
        log.info("LawyerAiInteractionLogServiceImpl.addAiInteractionLog?aiInteractionLog={}", aiInteractionLog);
        boolean result = this.save(aiInteractionLog);
        if (result) {
            return R.data(aiInteractionLog);
        }
        return R.fail("新增失败");
    }

    @Override
    public R<LawyerAiInteractionLog> editAiInteractionLog(LawyerAiInteractionLog aiInteractionLog) {
        log.info("LawyerAiInteractionLogServiceImpl.editAiInteractionLog?aiInteractionLog={}", aiInteractionLog);
        boolean result = this.updateById(aiInteractionLog);
        if (result) {
            return R.data(aiInteractionLog);
        }
        return R.fail("修改失败");
    }

    @Override
    public R<Boolean> deleteAiInteractionLog(Integer id) {
        log.info("LawyerAiInteractionLogServiceImpl.deleteAiInteractionLog?id={}", id);
        boolean result = this.removeById(id);
        if (result) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @Override
    public R<Map<String, Object>> sendAIMessage(String message, String sessionId, Integer clientUserId) {
        log.info("LawyerAiInteractionLogServiceImpl.sendAIMessage?message={},sessionId={},clientUserId={}", message, sessionId, clientUserId);

        // 如果没有sessionId，生成一个新的
        if (sessionId == null || sessionId.isEmpty()) {
            sessionId = UUID.randomUUID().toString().replace("-", "");
        }

        // TODO: 这里需要调用实际的AI服务接口，目前返回模拟数据
        String aiReply = "您好！我是AI助手UBAO，正在为您分析问题...";

        // 保存AI交互日志
        LawyerAiInteractionLog log = new LawyerAiInteractionLog();
        log.setClientUserId(clientUserId);
        log.setConversationId(sessionId);
        log.setQueryText(message);
        log.setResponseText(aiReply);
        log.setInteractionTime(new Date());
        this.save(log);

        Map<String, Object> result = new HashMap<>();
        result.put("reply", aiReply);
        result.put("sessionId", sessionId);
        result.put("hasRecommendLawyers", false);
        result.put("recommendLawyerIds", new ArrayList<>());

        return R.data(result);
    }

    @Override
    public R<Map<String, Object>> saveChatLog(LawyerAiInteractionLog aiInteractionLog) {
        log.info("LawyerAiInteractionLogController.saveChatLog?aiInteractionLog={}", aiInteractionLog);
        Map<String, Object> result = new HashMap<>();
//        LawyerAiInteractionLogVo log = new LawyerAiInteractionLogVo();
//        log.setClientUserId(clientUserId);
//        log.setQueryText(queryText);
//        log.setResponseText(responseText);
//        log.setInteractionTime(new Date());
//        log.setDeleteFlag(0);
//        log.setCreatedTime(new Date());
//        log.setUpdatedTime(new Date());
//        int num =aiInteractionLogMapper.insertLog(log);
        LawyerAiInteractionLog log = new LawyerAiInteractionLog();
        log.setClientUserId(aiInteractionLog.getClientUserId());
        log.setQueryText(aiInteractionLog.getQueryText());
        log.setResponseText(aiInteractionLog.getResponseText());
        log.setInteractionTime(new Date());
        log.setDeleteFlag(0);
        log.setSceneId(aiInteractionLog.getSceneId());
        log.setCreatedTime(new Date());
        log.setUpdatedTime(new Date());
        //向表中插入一条新的数据，插入成功后获取插入该条数据的id
        boolean A=this.save(log);
        if (A) {
            result.put("result","聊天记录保存成功");
            result.put("log",log);
            return R.data(result);
        }
        result.put("result","聊天记录保存失败");
        return R.data(result);
    }

    @Override
    public R<Map<String, Object>> updatedLog(Integer id) {
        log.info("LawyerAiInteractionLogController.updatedLog?id={}", id);
        Map<String, Object> result = new HashMap<>();
        LawyerAiInteractionLogVo log = new LawyerAiInteractionLogVo();
        log.setId(id);
        log.setDeleteFlag(1);
        log.setUpdatedTime(new Date());
        int num=aiInteractionLogMapper.updateLog(log);
        if (num>0) {
            result.put("result","删除成功");
            result.put("log",log);
            return R.data(result);
        }
        result.put("result","删除失败");
        return R.data(result);
    }

    @Override
    public R<IPage<LawyerAiInteractionLog>> getLogList(Integer clientUserId,Integer page, Integer size) {
        List<LawyerAiInteractionLog> list = aiInteractionLogMapper.getLogList(clientUserId,page,size);
        IPage<LawyerAiInteractionLog> iPag =ListToPage.setPage(list,page, size);
        return R.data(iPag);
    }


}

