package com.emotion.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
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.PageResult;
import com.emotion.dto.request.userprofile.UserProfileCreateRequest;
import com.emotion.dto.request.userprofile.UserProfilePageRequest;
import com.emotion.dto.request.userprofile.UserProfileUpdateRequest;
import com.emotion.dto.response.userprofile.UserProfileResponse;
import com.emotion.entity.LifeEvent;
import com.emotion.entity.User;
import com.emotion.entity.UserProfile;
import com.emotion.mapper.UserProfileMapper;
import com.emotion.service.LifeEventService;
import com.emotion.service.UserProfileService;
import com.emotion.service.UserService;
import com.emotion.util.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户档案服务实现类
 *
 * @author huazhongmin
 * @date 2025-12-21
 */
@Slf4j
@Service
public class UserProfileServiceImpl extends ServiceImpl<UserProfileMapper, UserProfile> implements UserProfileService {

    @Autowired
    private UserService userService;

    @Lazy
    @Autowired
    private LifeEventService lifeEventService;

    @Override
    public UserProfileResponse createProfile(UserProfileCreateRequest request) {
        log.info("Creating user profile: {}", request);
        
        // 获取当前登录用户ID
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!StringUtils.hasText(currentUserId)) {
            throw new RuntimeException("用户未登录");
        }
        
        // 检查是否已存在档案
        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserProfile::getUserId, currentUserId);
        if (count(queryWrapper) > 0) {
            throw new RuntimeException("当前用户已存在档案信息");
        }

        UserProfile userProfile = new UserProfile();
        BeanUtils.copyProperties(request, userProfile);
        userProfile.setUserId(currentUserId);
        userProfile.setStatus(1); // 默认正常

        save(userProfile);
        log.info("User profile created with ID: {}", userProfile.getId());
        
        return convertToResponse(userProfile);
    }

    @Override
    public UserProfileResponse updateProfile(UserProfileUpdateRequest request) {
        log.info("Updating user profile: {}", request);
        
        // 获取当前登录用户ID
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!StringUtils.hasText(currentUserId)) {
            throw new RuntimeException("用户未登录");
        }

        UserProfile userProfile = null;
        
        // 先根据请求ID查询
        if (StringUtils.hasText(request.getId())) {
            userProfile = getById(request.getId());
        }
        
        // 如果没有查到，根据当前用户ID查询
        if (userProfile == null) {
            LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserProfile::getUserId, currentUserId);
            userProfile = getOne(queryWrapper);
        }
        
        // 如果还是没有，则创建新档案
        if (userProfile == null) {
            log.info("User profile not found, creating new profile for user: {}", currentUserId);
            UserProfileCreateRequest createRequest = new UserProfileCreateRequest();
            BeanUtils.copyProperties(request, createRequest);
            return createProfile(createRequest);
        }

        // 权限校验：只能修改自己的档案
        if (!userProfile.getUserId().equals(currentUserId)) {
            throw new RuntimeException("无权修改他人档案");
        }

        // 使用Hutool的BeanUtil进行部分更新，忽略null值
        BeanUtil.copyProperties(request, userProfile, CopyOptions.create().setIgnoreNullValue(true));
        updateById(userProfile);
        log.info("User profile updated: {}", userProfile.getId());
        
        return convertToResponse(userProfile);
    }

    @Override
    public UserProfileResponse getCurrentUserProfile() {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!StringUtils.hasText(currentUserId)) {
            throw new RuntimeException("用户未登录");
        }
        
        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserProfile::getUserId, currentUserId);
        // 获取最新的一条（理论上应该只有一条）
        List<UserProfile> list = list(queryWrapper);
        if (list.isEmpty()) {
            return null;
        }
        return convertToResponse(list.get(0));
    }

    @Override
    public UserProfileResponse getProfileById(String id) {
        UserProfile userProfile = getById(id);
        if (userProfile == null) {
            return null;
        }
        return convertToResponse(userProfile);
    }

    @Override
    public PageResult<UserProfileResponse> getProfilePage(UserProfilePageRequest request) {
        Page<UserProfile> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        if (StringUtils.hasText(request.getUserId())) {
            queryWrapper.eq(UserProfile::getUserId, request.getUserId());
        }
        if (StringUtils.hasText(request.getNickname())) {
            queryWrapper.like(UserProfile::getNickname, request.getNickname());
        }
        if (StringUtils.hasText(request.getMbti())) {
            queryWrapper.eq(UserProfile::getMbti, request.getMbti());
        }
        if (request.getStatus() != null) {
            queryWrapper.eq(UserProfile::getStatus, request.getStatus());
        }
        
        queryWrapper.orderByDesc(UserProfile::getCreateTime);
        
        IPage<UserProfile> userProfilePage = page(page, queryWrapper);
        
        List<UserProfileResponse> list = userProfilePage.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        PageResult<UserProfileResponse> result = new PageResult<>();
        result.setCurrent(userProfilePage.getCurrent());
        result.setSize(userProfilePage.getSize());
        result.setTotal(userProfilePage.getTotal());
        result.setPages(userProfilePage.getPages());
        result.setRecords(list);
        
        return result;
    }

    @Override
    public List<UserProfileResponse> getProfileList(UserProfilePageRequest request) {
        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        if (StringUtils.hasText(request.getUserId())) {
            queryWrapper.eq(UserProfile::getUserId, request.getUserId());
        }
        if (StringUtils.hasText(request.getNickname())) {
            queryWrapper.like(UserProfile::getNickname, request.getNickname());
        }
        if (StringUtils.hasText(request.getMbti())) {
            queryWrapper.eq(UserProfile::getMbti, request.getMbti());
        }
        if (request.getStatus() != null) {
            queryWrapper.eq(UserProfile::getStatus, request.getStatus());
        }
        
        queryWrapper.orderByDesc(UserProfile::getCreateTime);
        
        List<UserProfile> list = list(queryWrapper);
        return list.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public boolean deleteProfile(String id) {
        log.info("Deleting user profile: {}", id);
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int migrateLifeEventsFromProfiles() {
        log.info("开始迁移用户档案中的生命事件数据到t_life_event表");
        
        // 查询所有有生命事件数据的用户档案
        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(w -> w
                .isNotNull(UserProfile::getChildhoodContent).ne(UserProfile::getChildhoodContent, "")
                .or().isNotNull(UserProfile::getPeakContent).ne(UserProfile::getPeakContent, "")
                .or().isNotNull(UserProfile::getValleyContent).ne(UserProfile::getValleyContent, "")
        );
        
        List<UserProfile> profiles = list(queryWrapper);
        log.info("找到 {} 个有生命事件数据的用户档案", profiles.size());
        
        int migratedCount = 0;
        
        for (UserProfile profile : profiles) {
            String userId = profile.getUserId();
            List<LifeEvent> eventsToSave = new ArrayList<>();
            
            // 迁移童年记忆
            if (StringUtils.hasText(profile.getChildhoodContent())) {
                if (!isEventExists(userId, "childhood")) {
                    LifeEvent childhoodEvent = createLifeEventFromProfile(
                            userId, 
                            "童年记忆", 
                            profile.getChildhoodContent(), 
                            profile.getChildhoodDate(),
                            "childhood"
                    );
                    eventsToSave.add(childhoodEvent);
                }
            }
            
            // 迁移高光时刻 (peak -> joy)
            if (StringUtils.hasText(profile.getPeakContent())) {
                if (!isEventExists(userId, "joy")) {
                    LifeEvent peakEvent = createLifeEventFromProfile(
                            userId, 
                            "光芒闪耀的时刻", 
                            profile.getPeakContent(), 
                            profile.getPeakDate(),
                            "joy"
                    );
                    eventsToSave.add(peakEvent);
                }
            }
            
            // 迁移低谷时期 (valley -> low)
            if (StringUtils.hasText(profile.getValleyContent())) {
                if (!isEventExists(userId, "low")) {
                    LifeEvent valleyEvent = createLifeEventFromProfile(
                            userId, 
                            "在暗夜中潜行", 
                            profile.getValleyContent(), 
                            profile.getValleyDate(),
                            "low"
                    );
                    eventsToSave.add(valleyEvent);
                }
            }
            
            // 批量保存
            if (!eventsToSave.isEmpty()) {
                lifeEventService.saveBatch(eventsToSave);
                migratedCount += eventsToSave.size();
                log.info("用户 {} 迁移了 {} 条生命事件", userId, eventsToSave.size());
            }
        }
        
        log.info("生命事件数据迁移完成，共迁移 {} 条记录", migratedCount);
        return migratedCount;
    }

    /**
     * 检查用户是否已存在指定标签的生命事件
     *
     * @param userId 用户ID
     * @param tag 标签
     * @return 是否存在
     */
    private boolean isEventExists(String userId, String tag) {
        LambdaQueryWrapper<LifeEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeEvent::getUserId, userId)
                .eq(LifeEvent::getIsDeleted, 0)
                .like(LifeEvent::getTags, tag);
        return lifeEventService.count(wrapper) > 0;
    }

    /**
     * 从用户档案数据创建生命事件
     *
     * @param userId 用户ID
     * @param title 事件标题
     * @param content 事件内容
     * @param eventDate 事件日期
     * @param tag 事件标签
     * @return 生命事件实体
     */
    private LifeEvent createLifeEventFromProfile(String userId, String title, String content, 
                                                  LocalDate eventDate, String tag) {
        LifeEvent event = new LifeEvent();
        event.setUserId(userId);
        event.setTitle(title);
        event.setContent(content);
        event.setEventType("milestone");
        event.setTags(List.of(tag));
        
        // 设置事件日期，如果没有则使用当前时间
        if (eventDate != null) {
            event.setEventDate(eventDate.atStartOfDay());
        } else {
            event.setEventDate(java.time.LocalDateTime.now());
        }
        
        return event;
    }

    private UserProfileResponse convertToResponse(UserProfile userProfile) {
        if (userProfile == null) {
            return null;
        }
        UserProfileResponse response = new UserProfileResponse();
        BeanUtils.copyProperties(userProfile, response);
        return response;
    }
}
