package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.common.PageResult;
import com.emotion.dto.request.TopicInteractionCreateRequest;
import com.emotion.dto.request.TopicInteractionPageRequest;
import com.emotion.dto.request.TopicInteractionUpdateRequest;
import com.emotion.dto.response.TopicInteractionResponse;
import com.emotion.entity.TopicInteraction;
import com.emotion.mapper.TopicInteractionMapper;
import com.emotion.service.TopicInteractionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.format.DateTimeFormatter;

/**
 * 话题互动服务实现类
 * 
 * @author huazhongmin
 * @date 2025-07-24
 */
@Service
public class TopicInteractionServiceImpl extends ServiceImpl<TopicInteractionMapper, TopicInteraction> implements TopicInteractionService {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public PageResult<TopicInteractionResponse> getPageWithResponse(TopicInteractionPageRequest request) {
        Page<TopicInteraction> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<TopicInteraction> wrapper = new LambdaQueryWrapper<>();
        
        // 根据关键词查询
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w.like(TopicInteraction::getContent, request.getKeyword())
                    .or().like(TopicInteraction::getUserInput, request.getKeyword())
                    .or().like(TopicInteraction::getAiResponse, request.getKeyword()));
        }
        
        // 根据话题ID查询
        if (StringUtils.hasText(request.getTopicId())) {
            wrapper.eq(TopicInteraction::getTopicId, request.getTopicId());
        }

        // 根据用户ID查询
        if (StringUtils.hasText(request.getUserId())) {
            wrapper.eq(TopicInteraction::getCreateBy, request.getUserId());
        }

        // 根据互动类型查询
        if (StringUtils.hasText(request.getInteractionType())) {
            wrapper.eq(TopicInteraction::getType, request.getInteractionType());
        }

        wrapper.eq(TopicInteraction::getIsDeleted, 0).orderByDesc(TopicInteraction::getCreateTime);
        Page<TopicInteraction> resultPage = this.page(page, wrapper);

        // 转换为响应对象
        PageResult<TopicInteractionResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setSize(resultPage.getSize());
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPages(resultPage.getPages());
        pageResult.setRecords(resultPage.getRecords().stream()
                .map(this::convertToResponse)
                .toList());

        return pageResult;
    }

    @Override
    public TopicInteractionResponse getTopicInteractionResponseById(String id) {
        TopicInteraction topicInteraction = this.getById(id);
        if (topicInteraction == null || topicInteraction.getIsDeleted() == 1) {
            return null;
        }
        return convertToResponse(topicInteraction);
    }

    @Override
    public TopicInteractionResponse createTopicInteractionWithResponse(TopicInteractionCreateRequest request) {
        TopicInteraction topicInteraction = new TopicInteraction();
        BeanUtils.copyProperties(request, topicInteraction);
        // 设置用户ID为当前登录用户
        topicInteraction.setCreateBy(getCurrentUserId());
        this.save(topicInteraction);
        return convertToResponse(topicInteraction);
    }

    @Override
    public TopicInteractionResponse updateTopicInteractionWithResponse(TopicInteractionUpdateRequest request) {
        TopicInteraction topicInteraction = this.getById(request.getId());
        if (topicInteraction == null || topicInteraction.getIsDeleted() == 1) {
            return null;
        }

        // 只更新非空字段
        if (StringUtils.hasText(request.getTopicId())) {
            topicInteraction.setTopicId(request.getTopicId());
        }
        if (StringUtils.hasText(request.getInteractionType())) {
            topicInteraction.setType(request.getInteractionType());
        }
        if (StringUtils.hasText(request.getContent())) {
            topicInteraction.setContent(request.getContent());
        }
        if (StringUtils.hasText(request.getUserInput())) {
            topicInteraction.setUserInput(request.getUserInput());
        }
        if (StringUtils.hasText(request.getAiResponse())) {
            topicInteraction.setAiResponse(request.getAiResponse());
        }
        if (request.getRating() != null) {
            topicInteraction.setRating(request.getRating());
        }
        if (StringUtils.hasText(request.getFeedback())) {
            topicInteraction.setFeedback(request.getFeedback());
        }

        this.updateById(topicInteraction);
        return convertToResponse(topicInteraction);
    }

    @Override
    public boolean deleteTopicInteraction(String id) {
        TopicInteraction topicInteraction = this.getById(id);
        if (topicInteraction == null) {
            return false;
        }
        // 使用 MyBatis-Plus 的 removeById 方法，自动处理逻辑删除
        return this.removeById(id);
    }

    /**
     * 将实体对象转换为响应对象
     */
    private TopicInteractionResponse convertToResponse(TopicInteraction topicInteraction) {
        if (topicInteraction == null) {
            return null;
        }
        TopicInteractionResponse response = new TopicInteractionResponse();
        BeanUtils.copyProperties(topicInteraction, response);
        response.setId(topicInteraction.getId());
        if (topicInteraction.getCreateTime() != null) {
            response.setCreateTime(topicInteraction.getCreateTime().format(FORMATTER));
        }
        if (topicInteraction.getUpdateTime() != null) {
            response.setUpdateTime(topicInteraction.getUpdateTime().format(FORMATTER));
        }
        return response;
    }

    /**
     * 获取当前登录用户ID（模拟实现）
     */
    private String getCurrentUserId() {
        // 实际项目中应从token中获取用户ID
        return "current_user_id";
    }
}