package com.emotion.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 com.emotion.common.BasePageRequest;
import com.emotion.common.PageResult;
import com.emotion.dto.request.EmotionAnalysisCreateRequest;
import com.emotion.dto.request.EmotionAnalysisPageRequest;
import com.emotion.dto.request.EmotionAnalysisUpdateRequest;
import com.emotion.dto.response.EmotionAnalysisResponse;
import com.emotion.entity.EmotionAnalysis;
import com.emotion.mapper.EmotionAnalysisMapper;
import com.emotion.service.EmotionAnalysisService;
import com.emotion.util.SnowflakeIdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 情绪分析服务实现类
 * 
 * @author huazhongmin
 * @date 2025-07-24
 */
@Service
public class EmotionAnalysisServiceImpl extends ServiceImpl<EmotionAnalysisMapper, EmotionAnalysis> implements EmotionAnalysisService {

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

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

    @Override
    public IPage<EmotionAnalysis> getPage(BasePageRequest request) {
        Page<EmotionAnalysis> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<EmotionAnalysis> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w.like(EmotionAnalysis::getPrimaryEmotion, request.getKeyword())
                    .or().like(EmotionAnalysis::getPolarity, request.getKeyword()));
        }
        
        wrapper.eq(EmotionAnalysis::getIsDeleted, 0);
        
        // 排序
        if (StringUtils.hasText(request.getOrderBy())) {
            if ("asc".equalsIgnoreCase(request.getOrderDirection())) {
                wrapper.orderByAsc(EmotionAnalysis::getCreateTime);
            } else {
                wrapper.orderByDesc(EmotionAnalysis::getCreateTime);
            }
        } else {
            wrapper.orderByDesc(EmotionAnalysis::getCreateTime);
        }
        
        return this.page(page, wrapper);
    }

    @Override
    public IPage<EmotionAnalysis> getPageByUserId(BasePageRequest request, String userId) {
        Page<EmotionAnalysis> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<EmotionAnalysis> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmotionAnalysis::getCreateBy, userId)
                .eq(EmotionAnalysis::getIsDeleted, 0)
                .orderByDesc(EmotionAnalysis::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public EmotionAnalysis getByMessageId(String messageId) {
        LambdaQueryWrapper<EmotionAnalysis> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmotionAnalysis::getMessageId, messageId)
               .eq(EmotionAnalysis::getIsDeleted, 0);
        return this.getOne(wrapper);
    }

    @Override
    public EmotionAnalysis createEmotionAnalysis(String messageId, String userId, String primaryEmotion, 
            String polarity, Double intensity, Double confidence) {
        EmotionAnalysis analysis = new EmotionAnalysis();
        analysis.setId(snowflakeIdGenerator.nextIdAsString()); // 使用雪花算法生成ID
        analysis.setMessageId(messageId);
        analysis.setCreateBy(userId);
        analysis.setPrimaryEmotion(primaryEmotion);
        analysis.setPolarity(polarity);
        analysis.setIntensity(BigDecimal.valueOf(intensity));
        analysis.setConfidence(BigDecimal.valueOf(confidence));

        this.save(analysis);
        return analysis;
    }

    // 新增的方法实现

    @Override
    public PageResult<EmotionAnalysisResponse> getPageWithResponse(EmotionAnalysisPageRequest request) {
        IPage<EmotionAnalysis> page = getPage(request);
        List<EmotionAnalysisResponse> responses = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        return createPageResult(page, responses);
    }

    @Override
    public PageResult<EmotionAnalysisResponse> getPageByUserIdWithResponse(String userId,
            EmotionAnalysisPageRequest request) {
        IPage<EmotionAnalysis> page = getPageByUserId(request, userId);
        List<EmotionAnalysisResponse> responses = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        return createPageResult(page, responses);
    }

    @Override
    public EmotionAnalysisResponse getEmotionAnalysisResponseById(String id) {
        EmotionAnalysis analysis = this.getById(id);
        if (analysis == null) {
            return null;
        }
        return convertToResponse(analysis);
    }

    @Override
    public EmotionAnalysisResponse getEmotionAnalysisResponseByMessageId(String messageId) {
        EmotionAnalysis analysis = getByMessageId(messageId);
        if (analysis == null) {
            return null;
        }
        return convertToResponse(analysis);
    }

    @Override
    public EmotionAnalysisResponse createEmotionAnalysisWithResponse(EmotionAnalysisCreateRequest request) {
        EmotionAnalysis analysis = createEmotionAnalysis(
                request.getMessageId(),
                request.getUserId(),
                request.getPrimaryEmotion(),
                request.getPolarity(),
                request.getIntensity(),
                request.getConfidence());
        return convertToResponse(analysis);
    }

    @Override
    public EmotionAnalysisResponse updateEmotionAnalysisWithResponse(EmotionAnalysisUpdateRequest request) {
        EmotionAnalysis analysis = this.getById(request.getId());
        if (analysis == null) {
            return null;
        }

        // 更新字段
        if (request.getMessageId() != null) {
            analysis.setMessageId(request.getMessageId());
        }
        if (request.getUserId() != null) {
            analysis.setCreateBy(request.getUserId());
        }
        if (request.getPrimaryEmotion() != null) {
            analysis.setPrimaryEmotion(request.getPrimaryEmotion());
        }
        if (request.getPolarity() != null) {
            analysis.setPolarity(request.getPolarity());
        }
        if (request.getIntensity() != null) {
            analysis.setIntensity(BigDecimal.valueOf(request.getIntensity()));
        }
        if (request.getConfidence() != null) {
            analysis.setConfidence(BigDecimal.valueOf(request.getConfidence()));
        }

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

    @Override
    public boolean deleteEmotionAnalysis(String id) {
        return this.removeById(id);
    }

    /**
     * 创建PageResult对象
     */
    private <T> PageResult<T> createPageResult(IPage<?> page, List<T> records) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());
        pageResult.setRecords(records);
        return pageResult;
    }

    /**
     * 转换为响应对象
     */
    private EmotionAnalysisResponse convertToResponse(EmotionAnalysis analysis) {
        EmotionAnalysisResponse response = new EmotionAnalysisResponse();
        BeanUtils.copyProperties(analysis, response);
        response.setId(analysis.getId());
        if (analysis.getCreateTime() != null) {
            response.setCreateTime(analysis.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (analysis.getUpdateTime() != null) {
            response.setUpdateTime(analysis.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        // 处理Double类型转换
        if (analysis.getIntensity() != null) {
            response.setIntensity(analysis.getIntensity().doubleValue());
        }
        if (analysis.getConfidence() != null) {
            response.setConfidence(analysis.getConfidence().doubleValue());
        }
        return response;
    }
}