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.LifeEventCreateRequest;
import com.emotion.dto.request.LifeEventPageRequest;
import com.emotion.dto.request.LifeEventUpdateRequest;
import com.emotion.dto.response.LifeEventResponse;
import com.emotion.entity.LifeEvent;
import com.emotion.mapper.LifeEventMapper;
import com.emotion.service.LifeEventService;
import com.emotion.util.UserContextHolder;
import com.emotion.service.AiChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
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-12-22
 */
@Service
@Slf4j
public class LifeEventServiceImpl extends ServiceImpl<LifeEventMapper, LifeEvent>
        implements LifeEventService {

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

    /**
     * Coze工作流配置键 - AI疗愈
     */
    private static final String COZE_HEALING_CONFIG_KEY = "coze.user.dairy.summary";

    @Autowired
    private AiChatService aiChatService;

    @Override
    public PageResult<LifeEventResponse> getPageByCurrentUser(LifeEventPageRequest request) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return new PageResult<>();
        }

        Page<LifeEvent> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<LifeEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeEvent::getUserId, currentUserId)
                .eq(LifeEvent::getIsDeleted, 0);

        // 事件类型筛选
        if (StringUtils.hasText(request.getEventType())) {
            wrapper.eq(LifeEvent::getEventType, request.getEventType());
        }

        // 情绪类型筛选
        if (StringUtils.hasText(request.getEmotionType())) {
            wrapper.eq(LifeEvent::getEmotionType, request.getEmotionType());
        }

        // 关键词搜索
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w.like(LifeEvent::getTitle, request.getKeyword())
                    .or().like(LifeEvent::getContent, request.getKeyword()));
        }

        // 按事件日期倒序排列
        wrapper.orderByDesc(LifeEvent::getEventDate);

        Page<LifeEvent> resultPage = this.page(page, wrapper);
        List<LifeEventResponse> responses = resultPage.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        PageResult<LifeEventResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setSize(resultPage.getSize());
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPages(resultPage.getPages());
        pageResult.setRecords(responses);

        return pageResult;
    }

    @Override
    public List<LifeEventResponse> getListByCurrentUser() {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return List.of();
        }

        LambdaQueryWrapper<LifeEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeEvent::getUserId, currentUserId)
                .eq(LifeEvent::getIsDeleted, 0)
                .orderByDesc(LifeEvent::getEventDate);

        return this.list(wrapper).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public LifeEventResponse getEventById(String id) {
        LifeEvent event = this.getById(id);
        if (event == null || event.getIsDeleted() == 1) {
            return null;
        }

        // 验证权限
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!event.getUserId().equals(currentUserId)) {
            return null;
        }

        return convertToResponse(event);
    }

    @Override
    public LifeEventResponse createEvent(LifeEventCreateRequest request) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }

        LifeEvent event = new LifeEvent();
        event.setUserId(currentUserId);
        event.setEventType(StringUtils.hasText(request.getEventType()) ? request.getEventType() : "daily_log");
        event.setTitle(request.getTitle());
        event.setContent(request.getContent());
        event.setAiReply(request.getAiReply());
        event.setEmotionType(request.getEmotionType());
        event.setTags(request.getTags());

        // 解析事件日期，支持多种格式
        event.setEventDate(parseEventDate(request.getEventDate()));

        // 情绪评分
        if (request.getEmotionScore() != null) {
            event.setEmotionScore(BigDecimal.valueOf(request.getEmotionScore()));
        }

        // 调用Coze AI进行疗愈回复
        String aiGeneratedContent = generateHealingByAi(event);
        if (StringUtils.hasText(aiGeneratedContent)) {
            event.setAiReply(aiGeneratedContent);
        }

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

    /**
     * 调用Coze AI生成疗愈内容
     *
     * @param event 人生事件
     * @return AI生成的疗愈内容，失败时返回null
     */
    private String generateHealingByAi(LifeEvent event) {
        try {
            // 组装AI输入
            String input = assembleHealingInput(event);
            log.info("开始调用AI生成疗愈回复，用户ID: {}, 输入长度: {}", event.getUserId(), input.length());

            // 调用Coze工作流
            String result = aiChatService.callWorkflowByConfigKey(COZE_HEALING_CONFIG_KEY, input, event.getUserId());

            log.info("AI生成疗愈回复完成，用户ID: {}, 结果长度: {}", event.getUserId(), result != null ? result.length() : 0);
            return result;

        } catch (Exception e) {
            log.error("AI生成疗愈回复失败，用户ID: {}, 错误: {}", event.getUserId(), e.getMessage(), e);
            // AI调用失败不影响事件创建，返回null
            return null;
        }
    }

    /**
     * 组装AI疗愈输入内容
     *
     * @param event 人生事件
     * @return 格式化的输入字符串
     */
    private String assembleHealingInput(LifeEvent event) {
        StringBuilder sb = new StringBuilder();

        // 标题
        if (StringUtils.hasText(event.getTitle())) {
            sb.append("【事件标题】").append(event.getTitle()).append("\n");
        }

        // 发生时间
        if (!ObjectUtils.isEmpty(event.getEventDate())) {
            sb.append("【发生时间】").append(event.getEventDate()).append("\n");
        }

        // 经历详解
        if (StringUtils.hasText(event.getContent())) {
            sb.append("【经历详解】").append(event.getContent()).append("\n");
        }

        // 情绪类型
        if (StringUtils.hasText(event.getEmotionType())) {
            sb.append("【情绪类型】").append(event.getEmotionType()).append("\n");
        }

        return sb.toString().trim();
    }

    @Override
    public LifeEventResponse updateEvent(LifeEventUpdateRequest request) {
        LifeEvent event = this.getById(request.getId());
        if (event == null || event.getIsDeleted() == 1) {
            return null;
        }

        // 验证权限
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!event.getUserId().equals(currentUserId)) {
            return null;
        }

        // 更新字段
        if (StringUtils.hasText(request.getEventType())) {
            event.setEventType(request.getEventType());
        }
        if (StringUtils.hasText(request.getTitle())) {
            event.setTitle(request.getTitle());
        }
        if (StringUtils.hasText(request.getContent())) {
            event.setContent(request.getContent());
        }
        if (request.getAiReply() != null) {
            event.setAiReply(request.getAiReply());
        }
        if (request.getEmotionType() != null) {
            event.setEmotionType(request.getEmotionType());
        }
        if (request.getTags() != null) {
            event.setTags(request.getTags());
        }
        if (StringUtils.hasText(request.getEventDate())) {
            event.setEventDate(parseEventDate(request.getEventDate()));
        }
        if (request.getEmotionScore() != null) {
            event.setEmotionScore(BigDecimal.valueOf(request.getEmotionScore()));
        }

        // 调用Coze AI进行疗愈回复
        String aiGeneratedContent = generateHealingByAi(event);
        if (StringUtils.hasText(aiGeneratedContent)) {
            event.setAiReply(aiGeneratedContent);
        }

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

    @Override
    public boolean deleteEvent(String id) {
        LifeEvent event = this.getById(id);
        if (event == null) {
            return false;
        }

        // 验证权限
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!event.getUserId().equals(currentUserId)) {
            return false;
        }

        // 使用 MyBatis-Plus 的 removeById 方法，自动处理逻辑删除
        return this.removeById(id);
    }

    /**
     * 转换为响应对象
     */
    private LifeEventResponse convertToResponse(LifeEvent event) {
        LifeEventResponse response = new LifeEventResponse();
        BeanUtils.copyProperties(event, response);
        response.setId(event.getId());
        if (event.getEventDate() != null) {
            response.setEventDate(event.getEventDate().format(ISO_FORMATTER));
        }
        if (event.getEmotionScore() != null) {
            response.setEmotionScore(event.getEmotionScore().doubleValue());
        }
        if (event.getCreateTime() != null) {
            response.setCreateTime(event.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (event.getUpdateTime() != null) {
            response.setUpdateTime(event.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        return response;
    }

    /**
     * 解析事件日期，支持多种格式
     * 支持格式：yyyy-MM-dd、yyyy-MM-ddTHH:mm:ss、ISO_DATE_TIME
     *
     * @param dateStr 日期字符串
     * @return 解析后的LocalDateTime，解析失败返回当前时间
     */
    private LocalDateTime parseEventDate(String dateStr) {
        if (!StringUtils.hasText(dateStr)) {
            return LocalDateTime.now();
        }

        // 尝试ISO格式 (yyyy-MM-ddTHH:mm:ss.SSSZ)
        try {
            return LocalDateTime.parse(dateStr, ISO_FORMATTER);
        } catch (Exception ignored) {
        }

        // 尝试日期时间格式 (yyyy-MM-dd HH:mm:ss)
        try {
            return LocalDateTime.parse(dateStr, DATE_TIME_FORMATTER);
        } catch (Exception ignored) {
        }

        // 尝试纯日期格式 (yyyy-MM-dd)，时间设为当天开始
        try {
            return java.time.LocalDate.parse(dateStr, DATE_ONLY_FORMATTER).atStartOfDay();
        } catch (Exception ignored) {
        }

        // 所有格式都失败，返回当前时间
        return LocalDateTime.now();
    }
}
