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.EmotionRecordCreateRequest;
import com.emotion.dto.request.EmotionRecordPageRequest;
import com.emotion.dto.request.EmotionRecordUpdateRequest;
import com.emotion.dto.response.EmotionRecordResponse;
import com.emotion.entity.EmotionRecord;
import com.emotion.mapper.EmotionRecordMapper;
import com.emotion.service.EmotionRecordService;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * 情绪记录服务实现类
 * 
 * @author huazhongmin
 * @date 2025-07-24
 */
@Service
public class EmotionRecordServiceImpl extends ServiceImpl<EmotionRecordMapper, EmotionRecord> implements EmotionRecordService {

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

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

    @Override
    public IPage<EmotionRecord> getPage(BasePageRequest request) {
        Page<EmotionRecord> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<EmotionRecord> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w.like(EmotionRecord::getDescription, request.getKeyword())
                    .or().like(EmotionRecord::getNotes, request.getKeyword()));
        }
        
        wrapper.eq(EmotionRecord::getIsDeleted, 0).orderByDesc(EmotionRecord::getCreateTime);
        return this.page(page, wrapper);
    }

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

    @Override
    public EmotionRecord createEmotionRecord(String userId, String emotionType, Double intensity, 
                                           String trigger, String location, String notes) {
        EmotionRecord record = new EmotionRecord();
        record.setId(snowflakeIdGenerator.nextIdAsString()); // 使用雪花算法生成ID
        record.setUserId(userId);
        record.setEmotionType(emotionType);
        record.setIntensity(BigDecimal.valueOf(intensity));
        record.setTriggers(trigger);
        record.setLocation(location);
        record.setNotes(notes);
        record.setRecordDate(LocalDate.now());

        this.save(record);
        return record;
    }

    // 新增的方法实现

    @Override
    public PageResult<EmotionRecordResponse> getPageWithResponse(EmotionRecordPageRequest request) {
        IPage<EmotionRecord> page = getPage(request);
        List<EmotionRecordResponse> responses = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        PageResult<EmotionRecordResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());
        pageResult.setRecords(responses);
        return pageResult;
    }

    @Override
    public PageResult<EmotionRecordResponse> getPageByUserIdWithResponse(String userId, EmotionRecordPageRequest request) {
        IPage<EmotionRecord> page = getPageByUserId(request, userId);
        List<EmotionRecordResponse> responses = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        PageResult<EmotionRecordResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());
        pageResult.setRecords(responses);
        return pageResult;
    }

    @Override
    public EmotionRecordResponse getEmotionRecordResponseById(String id) {
        EmotionRecord record = this.getById(id);
        if (record == null) {
            return null;
        }
        return convertToResponse(record);
    }

    @Override
    public EmotionRecordResponse createEmotionRecordWithResponse(EmotionRecordCreateRequest request) {
        EmotionRecord record = new EmotionRecord();
        record.setId(snowflakeIdGenerator.nextIdAsString()); // 使用雪花算法生成ID
        record.setUserId(request.getUserId());
        record.setRecordDate(request.getRecordDate());
        record.setEmotionType(request.getEmotionType());
        record.setIntensity(request.getIntensity());
        record.setTriggers(request.getTriggers());
        record.setDescription(request.getDescription());
        // 注意：tags字段在实体类中是String类型，需要转换
        record.setTags(request.getTags() != null ? request.getTags().toString() : null);
        record.setWeather(request.getWeather());
        record.setLocation(request.getLocation());
        record.setActivity(request.getActivity());
        record.setPeople(request.getPeople());
        record.setNotes(request.getNotes());

        this.save(record);
        return convertToResponse(record);
    }

    @Override
    public EmotionRecordResponse updateEmotionRecordWithResponse(EmotionRecordUpdateRequest request) {
        EmotionRecord record = this.getById(request.getId());
        if (record == null) {
            return null;
        }

        // 更新字段
        if (request.getRecordDate() != null) {
            record.setRecordDate(request.getRecordDate());
        }
        if (request.getEmotionType() != null) {
            record.setEmotionType(request.getEmotionType());
        }
        if (request.getIntensity() != null) {
            record.setIntensity(request.getIntensity());
        }
        if (request.getTriggers() != null) {
            record.setTriggers(request.getTriggers());
        }
        if (request.getDescription() != null) {
            record.setDescription(request.getDescription());
        }
        // 注意：tags字段在实体类中是String类型，需要转换
        if (request.getTags() != null) {
            record.setTags(request.getTags().toString());
        }
        if (request.getWeather() != null) {
            record.setWeather(request.getWeather());
        }
        if (request.getLocation() != null) {
            record.setLocation(request.getLocation());
        }
        if (request.getActivity() != null) {
            record.setActivity(request.getActivity());
        }
        if (request.getPeople() != null) {
            record.setPeople(request.getPeople());
        }
        if (request.getNotes() != null) {
            record.setNotes(request.getNotes());
        }

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

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

    @Override
    public Map<String, Object> getEmotionStats(String userId, String startDate, String endDate) {
        Map<String, Object> stats = new HashMap<>();

        // 构建查询条件
        LambdaQueryWrapper<EmotionRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmotionRecord::getUserId, userId)
                .eq(EmotionRecord::getIsDeleted, 0);

        // 如果提供了日期范围，则添加时间条件
        if (StringUtils.hasText(startDate) && StringUtils.hasText(endDate)) {
            try {
                LocalDateTime start = LocalDate.parse(startDate).atStartOfDay();
                LocalDateTime end = LocalDate.parse(endDate).atTime(23, 59, 59);
                wrapper.between(EmotionRecord::getCreateTime, start, end);
            } catch (Exception e) {
                // 如果日期解析失败，忽略日期条件
            }
        }

        // 查询用户的所有情绪记录
        List<EmotionRecord> records = this.list(wrapper);

        if (records.isEmpty()) {
            stats.put("emotionDistribution", new HashMap<>());
            stats.put("totalRecords", 0);
            stats.put("averageIntensity", 0.0);
            stats.put("mostFrequentEmotion", null);
            stats.put("emotionTrend", "no_data");
            return stats;
        }

        // 情绪类型分布
        Map<String, Long> emotionDistribution = records.stream()
                .collect(Collectors.groupingBy(EmotionRecord::getEmotionType, Collectors.counting()));

        stats.put("emotionDistribution", emotionDistribution);
        stats.put("totalRecords", records.size());

        // 平均情绪强度
        double avgIntensity = records.stream()
                .mapToDouble(record -> record.getIntensity().doubleValue())
                .average()
                .orElse(0.0);
        stats.put("averageIntensity", avgIntensity);

        // 最常见的情绪类型
        String mostFrequentEmotion = emotionDistribution.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse(null);
        stats.put("mostFrequentEmotion", mostFrequentEmotion);

        // 情绪趋势（简单实现：比较前半段和后半段的平均强度）
        if (records.size() > 1) {
            int mid = records.size() / 2;
            double firstHalfAvg = records.subList(0, mid).stream()
                    .mapToDouble(record -> record.getIntensity().doubleValue())
                    .average()
                    .orElse(0.0);

            double secondHalfAvg = records.subList(mid, records.size()).stream()
                    .mapToDouble(record -> record.getIntensity().doubleValue())
                    .average()
                    .orElse(0.0);

            if (secondHalfAvg > firstHalfAvg) {
                stats.put("emotionTrend", "improving");
            } else if (secondHalfAvg < firstHalfAvg) {
                stats.put("emotionTrend", "declining");
            } else {
                stats.put("emotionTrend", "stable");
            }
        } else {
            stats.put("emotionTrend", "insufficient_data");
        }

        return stats;
    }

    /**
     * 转换为响应对象
     */
    private EmotionRecordResponse convertToResponse(EmotionRecord record) {
        EmotionRecordResponse response = new EmotionRecordResponse();
        BeanUtils.copyProperties(record, response);
        response.setId(record.getId());
        if (record.getCreateTime() != null) {
            response.setCreateTime(record.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (record.getUpdateTime() != null) {
            response.setUpdateTime(record.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        return response;
    }
}