package com.zhentao.service.impl;

import com.zhentao.entity.User;
import com.zhentao.entity.UserProfile;
import com.zhentao.entity.UserVip;
import com.zhentao.mapper.UserMapper;
import com.zhentao.mapper.UserProfileMapper;
import com.zhentao.mapper.UserVipMapper;
import com.zhentao.service.UserService;
import com.zhentao.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserProfileMapper userProfileMapper;
    
    @Autowired
    private UserVipMapper userVipMapper;
    
    @Override
    public UserInfoVO getUserInfo(Long userId) {
        System.out.println("=== UserService.getUserInfo ===");
        System.out.println("请求的用户ID: " + userId);
        
        // 查询用户基本信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            System.out.println("用户不存在，用户ID: " + userId);
            throw new RuntimeException("用户不存在，ID: " + userId);
        }
        
        System.out.println("找到用户: " + user.getNickname() + " (ID: " + user.getUserId() + ")");
        
        // 查询用户扩展信息（使用userId查询，不是profileId）
        UserProfile profile = userProfileMapper.selectByUserId(userId);
        
        // 组装VO
        UserInfoVO vo = new UserInfoVO();
        
        // 基本信息
        vo.setUserId(user.getUserId());
        vo.setNickname(user.getNickname());
        vo.setAvatar(user.getAvatarUrl());
        vo.setPhone(maskPhone(user.getPhone()));
        vo.setEmail(user.getEmail());
        vo.setGender(user.getGender());
        vo.setGenderText(getGenderText(user.getGender()));
        vo.setBirthDate(user.getBirthDate());
        vo.setAge(calculateAge(user.getBirthDate()));
        
        // 如果有扩展信息
        if (profile != null) {
            vo.setIsVerified(profile.getIsRealNameVerified() == 1);
            vo.setHeight(profile.getHeight());
            vo.setWeight(profile.getWeight());
            vo.setStar(profile.getStar());
            vo.setAnimal(profile.getAnimal());
            vo.setEducationLevel(profile.getEducationLevel());
            vo.setEducationText(getEducationText(profile.getEducationLevel()));
            vo.setSchoolName(profile.getSchoolName());
            vo.setCompany(profile.getCompany());
            vo.setJobTitle(profile.getJobTitle());
            vo.setSalaryRange(profile.getSalaryRange());
            vo.setSalaryText(getSalaryText(profile.getSalaryRange()));
            vo.setMaritalStatus(profile.getMaritalStatus());
            vo.setMaritalText(getMaritalText(profile.getMaritalStatus()));
            vo.setHouse(profile.getHouse());
            vo.setHouseText(getHouseText(profile.getHouse()));
            vo.setCar(profile.getCar());
            vo.setCarText(getCarText(profile.getCar()));
            vo.setHobby(profile.getHobby());
            vo.setIntroduction(profile.getIntroduction());
            vo.setAuthenticityScore(profile.getAuthenticityScore());
            vo.setProvinceId(profile.getProvinceId());
            vo.setCityId(profile.getCityId());
            vo.setAreaId(profile.getAreaId());
        } else {
            vo.setIsVerified(false);
        }
        
        // 设置照片列表（暂时使用头像作为照片，后续可以扩展为照片列表）
        java.util.List<String> photos = new java.util.ArrayList<>();
        if (user.getAvatarUrl() != null && !user.getAvatarUrl().isEmpty()) {
            photos.add(user.getAvatarUrl());
        }
        vo.setPhotos(photos);
        
        // 计算资料完善度
        vo.setProfileProgress(calculateProfileProgress(user, profile));
        
        // 查询VIP状态
        vo.setIsVip(checkUserVipStatus(userId));
        
        return vo;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserBasicInfo(User user) {
        // 数据验证
        if (user.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 验证用户是否存在
        User existUser = userMapper.selectById(user.getUserId());
        if (existUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 保持重要字段不被清空
        if (user.getPhone() == null) {
            user.setPhone(existUser.getPhone());
        }
        if (user.getEmail() == null) {
            user.setEmail(existUser.getEmail());
        }
        if (user.getPassword() == null) {
            user.setPassword(existUser.getPassword());
        }
        if (user.getStatus() == null) {
            user.setStatus(existUser.getStatus());
        }
        if (user.getSourceChannel() == null) {
            user.setSourceChannel(existUser.getSourceChannel());
        }
        if (user.getIsProfileComplete() == null) {
            user.setIsProfileComplete(existUser.getIsProfileComplete());
        }
        if (user.getConsentToCollect() == null) {
            user.setConsentToCollect(existUser.getConsentToCollect());
        }
        if (user.getHasWechatLogin() == null) {
            user.setHasWechatLogin(existUser.getHasWechatLogin());
        }
        if (user.getCreatedAt() == null) {
            user.setCreatedAt(existUser.getCreatedAt());
        }
        if (user.getLastLoginAt() == null) {
            user.setLastLoginAt(existUser.getLastLoginAt());
        }
        if (user.getLastActiveAt() == null) {
            user.setLastActiveAt(existUser.getLastActiveAt());
        }
        
        // 设置更新时间
        user.setUpdatedAt(LocalDateTime.now());
        
        // 执行更新
        int result = userMapper.updateById(user);
        System.out.println("更新用户基本信息 - 用户ID: " + user.getUserId() + ", 影响行数: " + result);
        
        return result > 0;
    }
    
    @Override
    public Integer calculateUserAge(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return null;
        }
        return calculateAge(user.getBirthDate());
    }
    
    @Override
    public Boolean updateAvatarUrl(Long userId, String avatarUrl) {
        System.out.println("=== UserService.updateAvatarUrl ===");
        System.out.println("用户ID: " + userId);
        System.out.println("头像URL: " + avatarUrl);
        
        // 重试机制：最多重试3次
        int maxRetries = 3;
        int retryCount = 0;
        Exception lastException = null;
        
        while (retryCount < maxRetries) {
            try {
                // 调用实际的更新方法（事务方法）
                return doUpdateAvatarUrl(userId, avatarUrl, retryCount);
                
            } catch (org.springframework.dao.CannotAcquireLockException e) {
                lastException = e;
                retryCount++;
                System.err.println("⚠️ 数据库锁定，第 " + retryCount + " 次重试...");
                
                if (retryCount < maxRetries) {
                    try {
                        // 等待一段时间后重试（递增等待时间）
                        long waitTime = 200L * retryCount;
                        System.out.println("等待 " + waitTime + " 毫秒后重试...");
                        Thread.sleep(waitTime);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("重试被中断", ie);
                    }
                } else {
                    System.err.println("❌ 重试 " + maxRetries + " 次后仍然失败");
                    throw new RuntimeException("更新头像失败，数据库繁忙，请稍后重试", e);
                }
            } catch (RuntimeException e) {
                // 其他运行时异常不重试，直接抛出
                System.err.println("❌ 更新失败: " + e.getMessage());
                throw e;
            }
        }
        
        // 不应该到达这里
        throw new RuntimeException("更新头像失败", lastException);
    }
    
    /**
     * 实际执行更新的方法（带事务）
     */
    @Transactional(rollbackFor = Exception.class, timeout = 10)
    public Boolean doUpdateAvatarUrl(Long userId, String avatarUrl, int retryCount) {
        // 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新头像URL
        User updateUser = new User();
        updateUser.setUserId(userId);
        updateUser.setAvatarUrl(avatarUrl);
        updateUser.setUpdatedAt(LocalDateTime.now());
        
        int result = userMapper.updateById(updateUser);
        System.out.println("✅ 更新头像URL成功 - 用户ID: " + userId + ", 影响行数: " + result + ", 重试次数: " + retryCount);
        
        return result > 0;
    }
    
    @Override
    public String getAvatarUrl(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return null;
        }
        return user.getAvatarUrl();
    }
    
    /**
     * 手机号部分隐藏
     */
    private String maskPhone(String phone) {
        if (phone == null || phone.length() < 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
    
    /**
     * 计算年龄（改进版，处理边界情况）
     */
    private Integer calculateAge(LocalDate birthDate) {
        if (birthDate == null) {
            return null;
        }
        
        LocalDate now = LocalDate.now();
        
        // 检查出生日期是否在未来
        if (birthDate.isAfter(now)) {
            return 0;
        }
        
        // 使用Period计算准确年龄
        Period period = Period.between(birthDate, now);
        return period.getYears();
    }
    
    /**
     * 计算资料完善度
     */
    private Integer calculateProfileProgress(User user, UserProfile profile) {
        int total = 0;
        int completed = 0;
        
        // 基本信息（8项）
        total += 8;
        if (user.getNickname() != null && !user.getNickname().isEmpty()) completed++;
        if (user.getAvatarUrl() != null && !user.getAvatarUrl().isEmpty()) completed++;
        if (user.getPhone() != null && !user.getPhone().isEmpty()) completed++;
        if (user.getEmail() != null && !user.getEmail().isEmpty()) completed++;
        if (user.getGender() != null && user.getGender() > 0) completed++;
        if (user.getBirthDate() != null) completed++;
        if (user.getConsentToCollect() != null && user.getConsentToCollect() == 1) completed++;
        if (user.getIsProfileComplete() != null && user.getIsProfileComplete() == 1) completed++;
        
        if (profile != null) {
            // 扩展信息（10项）
            total += 10;
            if (profile.getHeight() != null && profile.getHeight() > 0) completed++;
            if (profile.getWeight() != null && profile.getWeight() > 0) completed++;
            if (profile.getEducationLevel() != null && profile.getEducationLevel() > 0) completed++;
            if (profile.getSchoolName() != null && !profile.getSchoolName().isEmpty()) completed++;
            if (profile.getCompany() != null && !profile.getCompany().isEmpty()) completed++;
            if (profile.getJobTitle() != null && !profile.getJobTitle().isEmpty()) completed++;
            if (profile.getSalaryRange() != null && profile.getSalaryRange() > 0) completed++;
            if (profile.getMaritalStatus() != null) completed++;
            if (profile.getHouse() != null) completed++;
            if (profile.getCar() != null) completed++;
        }
        
        return total > 0 ? (completed * 100 / total) : 0;
    }
    
    /**
     * 性别文字
     */
    private String getGenderText(Integer gender) {
        if (gender == null) return "未知";
        switch (gender) {
            case 1: return "男";
            case 2: return "女";
            default: return "未知";
        }
    }
    
    /**
     * 学历文字
     */
    private String getEducationText(Integer level) {
        if (level == null) return null;
        switch (level) {
            case 1: return "高中";
            case 2: return "专科";
            case 3: return "本科";
            case 4: return "硕士";
            case 5: return "博士";
            case 6: return "无";
            case 7: return "初中";
            case 8: return "小学";
            default: return "未知";
        }
    }
    
    /**
     * 薪资文字
     */
    private String getSalaryText(Integer range) {
        if (range == null) return null;
        switch (range) {
            case 1: return "5k以下";
            case 2: return "5-10k";
            case 3: return "10-20k";
            case 4: return "20-50k";
            case 5: return "50k以上";
            default: return "未知";
        }
    }
    
    /**
     * 婚姻状况文字
     */
    private String getMaritalText(Integer status) {
        if (status == null) return null;
        switch (status) {
            case 0: return "未婚";
            case 1: return "离异";
            case 2: return "丧偶";
            default: return "未知";
        }
    }
    
    /**
     * 房产文字
     */
    private String getHouseText(Integer house) {
        if (house == null) return null;
        return house == 1 ? "有房" : "无房";
    }
    
    /**
     * 车产文字
     */
    private String getCarText(Integer car) {
        if (car == null) return null;
        return car == 1 ? "有车" : "无车";
    }
    
    /**
     * 检查用户VIP状态
     */
    private Boolean checkUserVipStatus(Long userId) {
        try {
            // 查询用户当前生效的VIP记录
            UserVip currentVip = userVipMapper.selectActiveVipByUserId(userId);
            
            if (currentVip != null) {
                // 检查VIP是否过期
                LocalDateTime now = LocalDateTime.now();
                if (currentVip.getEndTime() != null && currentVip.getEndTime().isAfter(now)) {
                    System.out.println("✅ 用户 " + userId + " 是VIP会员，到期时间: " + currentVip.getEndTime());
                    return true;
                } else {
                    System.out.println("⚠️ 用户 " + userId + " 的VIP已过期");
                    return false;
                }
            } else {
                System.out.println("ℹ️ 用户 " + userId + " 不是VIP会员");
                return false;
            }
        } catch (Exception e) {
            System.err.println("❌ 查询VIP状态失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}

