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.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户扩展信息服务实现类
 */
@Service
public class UserProfileServiceImpl implements UserProfileService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserProfileMapper userProfileMapper;
    
    @Autowired
    private UserVipMapper userVipMapper;
    
    @Override
    public Map<String, Object> getUserProfile(Long userId) {
        Map<String, Object> result = new HashMap<>();

        // 1. 查询用户基本信息（从users表）
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 2. 设置基本信息
        result.put("userId", user.getUserId());
        result.put("nickname", user.getNickname());
        result.put("avatar", user.getAvatarUrl());  // 前端使用avatar字段
        result.put("avatarUrl", user.getAvatarUrl()); // 同时保留avatarUrl以兼容其他接口
        result.put("gender", user.getGender());

        if (user.getBirthDate() != null) {
            result.put("birthDate", user.getBirthDate().toString());
            // 计算并设置年龄
            Integer age = calculateAgeFromLocalDate(user.getBirthDate());
            result.put("age", age);
        } else {
            result.put("birthDate", null);
            result.put("age", null);
        }
        
        // 3. 查询用户扩展信息（从user_profile表）
        UserProfile profile = userProfileMapper.selectByUserId(userId);
        
        if (profile != null) {
            // 扩展信息
            result.put("realName", profile.getRealName());
            result.put("idCard", profile.getIdCard());
            result.put("height", profile.getHeight());
            result.put("weight", profile.getWeight());
            result.put("star", profile.getStar());
            result.put("animal", profile.getAnimal());
            result.put("educationLevel", profile.getEducationLevel());
            result.put("schoolName", profile.getSchoolName());
            result.put("company", profile.getCompany());
            result.put("jobTitle", profile.getJobTitle());
            result.put("salaryRange", profile.getSalaryRange());
            result.put("maritalStatus", profile.getMaritalStatus());
            result.put("house", profile.getHouse());
            result.put("car", profile.getCar());
            result.put("hobby", profile.getHobby());
            result.put("privacySalary", profile.getPrivacySalary());
            result.put("privacyPhone", profile.getPrivacyPhone());
            result.put("authenticityScore", profile.getAuthenticityScore());
            
            // 认证状态
            result.put("isRealNameVerified", profile.getIsRealNameVerified() == 1);
            result.put("isEducationVerified", profile.getIsEducationVerified() == 1);
            result.put("isWorkVerified", profile.getIsWorkVerified() == 1);
            result.put("isMaritalVerified", profile.getIsMaritalVerified() == 1);
        } else {
            // 如果没有扩展信息，自动创建默认记录
            System.out.println("⚠️ 用户 " + userId + " 没有扩展资料，自动创建默认记录");
            profile = createDefaultProfile(userId, user);
            
            // 设置默认值
            result.put("realName", null);
            result.put("idCard", null);
            result.put("height", null);
            result.put("weight", null);
            result.put("star", null);
            result.put("animal", null);
            result.put("educationLevel", null);
            result.put("schoolName", null);
            result.put("company", null);
            result.put("jobTitle", null);
            result.put("salaryRange", null);
            result.put("maritalStatus", null);
            result.put("house", null);
            result.put("car", null);
            result.put("hobby", null);
            result.put("privacySalary", 0);
            result.put("privacyPhone", 0);
            result.put("authenticityScore", 0);
            result.put("isRealNameVerified", false);
            result.put("isEducationVerified", false);
            result.put("isWorkVerified", false);
            result.put("isMaritalVerified", false);
        }
        
        // 查询VIP状态
        result.put("isVip", checkUserVipStatus(userId));
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserProfile(UserProfile userProfile) {
        // 0. 数据验证
        if (userProfile.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 验证用户是否存在
        User user = userMapper.selectById(userProfile.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // ⭐ 关键修复：gender 和 birthDate 存储在 users 表中，需要单独更新
        boolean userTableUpdated = false;
        if (userProfile.getGender() != null || userProfile.getBirthDate() != null) {
            User userUpdate = new User();
            userUpdate.setUserId(userProfile.getUserId());
            
            if (userProfile.getGender() != null) {
                userUpdate.setGender(userProfile.getGender());
            }
            
            if (userProfile.getBirthDate() != null) {
                // 将 Date 转换为 LocalDate
                LocalDate birthLocalDate = userProfile.getBirthDate().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate();
                userUpdate.setBirthDate(birthLocalDate);
            }
            
            int userResult = userMapper.updateById(userUpdate);
            userTableUpdated = userResult > 0;
            System.out.println("✅ 更新users表 - 用户ID: " + userProfile.getUserId() +
                             ", gender: " + userProfile.getGender() +
                             ", birthDate: " + userProfile.getBirthDate() +
                             ", 影响行数: " + userResult);
        }
        
        // 1. 查询是否存在用户扩展信息
        UserProfile existProfile = userProfileMapper.selectByUserId(userProfile.getUserId());
        
        int result;
        LocalDateTime now = LocalDateTime.now();
        
        if (existProfile == null) {
            // 不存在则新增
            // 设置默认认证状态
            if (userProfile.getIsRealNameVerified() == null) userProfile.setIsRealNameVerified(0);
            if (userProfile.getIsEducationVerified() == null) userProfile.setIsEducationVerified(0);
            if (userProfile.getIsWorkVerified() == null) userProfile.setIsWorkVerified(0);
            if (userProfile.getIsMaritalVerified() == null) userProfile.setIsMaritalVerified(0);
            
            // 计算初始真实度评分
            int score = calculateAuthenticityScore(userProfile);
            userProfile.setAuthenticityScore(score);
            
            result = userProfileMapper.insert(userProfile);
            System.out.println("新增用户扩展信息 - 用户ID: " + userProfile.getUserId() + ", 初始评分: " + score);
        } else {
            // 存在则更新 - 创建完整的更新对象
            userProfile.setProfileId(existProfile.getProfileId());
            
            // ⭐ 关键修复：添加 gender 和 birthDate 的保护逻辑
            if (userProfile.getGender() == null) {
                userProfile.setGender(existProfile.getGender());
            }
            if (userProfile.getBirthDate() == null) {
                userProfile.setBirthDate(existProfile.getBirthDate());
            }
            
            // 处理认证状态字段 - 只在没有传入值时保持原值
            if (userProfile.getIsRealNameVerified() == null) {
                userProfile.setIsRealNameVerified(existProfile.getIsRealNameVerified());
            }
            if (userProfile.getIsEducationVerified() == null) {
                userProfile.setIsEducationVerified(existProfile.getIsEducationVerified());
            }
            if (userProfile.getIsWorkVerified() == null) {
                userProfile.setIsWorkVerified(existProfile.getIsWorkVerified());
            }
            if (userProfile.getIsMaritalVerified() == null) {
                userProfile.setIsMaritalVerified(existProfile.getIsMaritalVerified());
            }
            
            // 处理其他字段 - 保持原值以避免null覆盖
            if (userProfile.getHouse() == null) {
                userProfile.setHouse(existProfile.getHouse());
            }
            if (userProfile.getCar() == null) {
                userProfile.setCar(existProfile.getCar());
            }
            if (userProfile.getEducationLevel() == null) {
                userProfile.setEducationLevel(existProfile.getEducationLevel());
            }
            if (userProfile.getSalaryRange() == null) {
                userProfile.setSalaryRange(existProfile.getSalaryRange());
            }
            if (userProfile.getMaritalStatus() == null) {
                userProfile.setMaritalStatus(existProfile.getMaritalStatus());
            }
            if (userProfile.getProvinceId() == null) {
                userProfile.setProvinceId(existProfile.getProvinceId());
            }
            if (userProfile.getCityId() == null) {
                userProfile.setCityId(existProfile.getCityId());
            }
            if (userProfile.getAreaId() == null) {
                userProfile.setAreaId(existProfile.getAreaId());
            }
            if (userProfile.getPrivacySalary() == null) {
                userProfile.setPrivacySalary(existProfile.getPrivacySalary());
            }
            if (userProfile.getPrivacyPhone() == null) {
                userProfile.setPrivacyPhone(existProfile.getPrivacyPhone());
            }
            if (userProfile.getVerifiedAt() == null) {
                userProfile.setVerifiedAt(existProfile.getVerifiedAt());
            }
            
            // 计算更新后的真实度评分
            int score = calculateAuthenticityScore(userProfile);
            userProfile.setAuthenticityScore(score);
            
            // 只调用一次updateById，包含评分更新
            result = userProfileMapper.updateById(userProfile);
            System.out.println("✅ 更新user_profile表 - 用户ID: " + userProfile.getUserId() + ", 更新后评分: " + score + ", 影响行数: " + result);
        }
        
        // 只要 users 表或 user_profile 表有一个更新成功就返回 true
        return (result > 0) || userTableUpdated;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean forceUpdateUserProfile(UserProfile userProfile) {
        // 0. 数据验证
        if (userProfile.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 验证用户是否存在
        User user = userMapper.selectById(userProfile.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 1. 查询是否存在用户扩展信息
        UserProfile existProfile = userProfileMapper.selectByUserId(userProfile.getUserId());
        
        if (existProfile == null) {
            throw new RuntimeException("用户扩展资料不存在，请先创建基本资料");
        }
        
        // 2. 强制更新 - 允许设置null值清空字段
        userProfile.setProfileId(existProfile.getProfileId());
        
        // 计算更新后的真实度评分
        int score = calculateAuthenticityScore(userProfile);
        userProfile.setAuthenticityScore(score);
        
        // 使用自定义UPDATE语句强制更新所有字段（包括null值）
        int result = userProfileMapper.forceUpdateById(userProfile);
        System.out.println("强制更新用户扩展信息 - 用户ID: " + userProfile.getUserId() + ", 更新后评分: " + score + ", 影响行数: " + result);
        
        return result > 0;
    }
    
    /**
     * 计算真实度评分（0-100分）
     */
    private int calculateAuthenticityScore(UserProfile profile) {
        int score = 0;
        
        // 基本信息完整度（40分）
        if (profile.getRealName() != null && !profile.getRealName().isEmpty()) score += 10;
        if (profile.getIdCard() != null && !profile.getIdCard().isEmpty()) score += 10;
        if (profile.getHeight() != null && profile.getHeight() > 0) score += 5;
        if (profile.getWeight() != null && profile.getWeight() > 0) score += 5;
        if (profile.getStar() != null && !profile.getStar().isEmpty()) score += 5;
        if (profile.getAnimal() != null && !profile.getAnimal().isEmpty()) score += 5;
        
        // 学业工作信息（30分）
        if (profile.getEducationLevel() != null && profile.getEducationLevel() > 0) score += 10;
        if (profile.getSchoolName() != null && !profile.getSchoolName().isEmpty()) score += 5;
        if (profile.getCompany() != null && !profile.getCompany().isEmpty()) score += 10;
        if (profile.getJobTitle() != null && !profile.getJobTitle().isEmpty()) score += 5;
        
        // 认证状态（30分）
        if (profile.getIsRealNameVerified() != null && profile.getIsRealNameVerified() == 1) score += 10;
        if (profile.getIsEducationVerified() != null && profile.getIsEducationVerified() == 1) score += 10;
        if (profile.getIsWorkVerified() != null && profile.getIsWorkVerified() == 1) score += 5;
        if (profile.getIsMaritalVerified() != null && profile.getIsMaritalVerified() == 1) score += 5;
        
        return Math.min(score, 100);
    }
    
    /**
     * 创建默认的用户扩展资料
     */
    private UserProfile createDefaultProfile(Long userId, User user) {
        try {
            UserProfile profile = new UserProfile();
            profile.setUserId(userId);
            profile.setGender(user.getGender());
            
            // 从users表复制出生日期
            if (user.getBirthDate() != null) {
                profile.setBirthDate(java.sql.Date.valueOf(user.getBirthDate()));
            }
            
            // 设置默认认证状态
            profile.setIsRealNameVerified(0);
            profile.setIsEducationVerified(0);
            profile.setIsWorkVerified(0);
            profile.setIsMaritalVerified(0);
            profile.setAuthenticityScore(0);
            
            // 设置默认隐私设置
            profile.setPrivacySalary(0);
            profile.setPrivacyPhone(0);
            
            userProfileMapper.insert(profile);
            System.out.println("✅ 已为用户 " + userId + " 创建默认扩展资料");
            return profile;
        } catch (Exception e) {
            System.err.println("❌ 创建默认扩展资料失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 计算年龄（从Date类型）
     */
    private Integer calculateAge(Date birthDate) {
        if (birthDate == null) {
            return null;
        }

        // 将Date转换为LocalDate（需处理时区）
        LocalDate birthLocalDate = birthDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        LocalDate now = LocalDate.now();

        // 检查出生日期是否在未来
        if (birthLocalDate.isAfter(now)) {
            return 0;
        }

        // 计算年龄
        Period period = Period.between(birthLocalDate, now);
        return period.getYears();
    }
    
    /**
     * 计算年龄（从LocalDate类型）
     */
    private Integer calculateAgeFromLocalDate(LocalDate birthDate) {
        if (birthDate == null) {
            return null;
        }

        LocalDate now = LocalDate.now();

        // 检查出生日期是否在未来
        if (birthDate.isAfter(now)) {
            return 0;
        }

        // 计算年龄
        Period period = Period.between(birthDate, now);
        return period.getYears();
    }
    
    /**
     * 检查用户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;
        }
    }
}

