package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.entity.MarrApply;
import com.zhentao.entity.Matchmaker;
import com.zhentao.entity.Users;
import com.zhentao.service.MarrApplyService;
import com.zhentao.mapper.MarrApplyMapper;
import com.zhentao.mapper.MatchmakerMapper;
import com.zhentao.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.entity.Province;
import com.zhentao.entity.City;
import com.zhentao.entity.Area;
import com.zhentao.mapper.ProvinceMapper;
import com.zhentao.mapper.CityMapper;
import com.zhentao.mapper.AreaMapper;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 联想
* @description 针对表【marr_apply(红娘申请表)】的数据库操作Service实现
* @createDate 2025-12-08 16:36:04
*/
@Service
public class MarrApplyServiceImpl extends ServiceImpl<MarrApplyMapper, MarrApply>
    implements MarrApplyService{

    @Autowired
    private UsersMapper usersMapper;
    
    @Autowired
    private MatchmakerMapper matchmakerMapper;
    
    @Autowired
    private ProvinceMapper provinceMapper;
    
    @Autowired
    private CityMapper cityMapper;
    
    @Autowired
    private AreaMapper areaMapper;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    // websocket 服务的 IM 接口地址
    private static final String IM_SERVICE_URL = "http://localhost:1004/api/im";

    @Override
    public Page<MarrApply> pageQuery(Integer pageNum, Integer pageSize, String name, String phone) {
        Page<MarrApply> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        String nameKeyword = StringUtils.hasText(name) ? name.trim() : null;
        String phoneKeyword = StringUtils.hasText(phone) ? phone.trim() : null;
        this.baseMapper.selectPageByCondition(page, nameKeyword, phoneKeyword);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean approve(Long applyId, Integer userId, Boolean approved, String reason) {
        System.out.println("========== 开始审核红娘申请 ==========");
        System.out.println("申请ID: " + applyId + ", 用户ID: " + userId + ", 审核结果: " + (approved ? "同意" : "不同意") + ", 原因: " + reason);
        
        // 1. 查询申请信息
        MarrApply apply = this.getById(applyId);
        if (apply == null) {
            throw new RuntimeException("申请记录不存在");
        }
        
        // 2. 检查申请状态，只有待审核（status=2）的记录才能被审核
        if (apply.getStatus() == null || apply.getStatus() != 2) {
            throw new RuntimeException("该申请不是待审核状态，无法进行审核操作。当前状态: " + 
                (apply.getStatus() == null ? "未设置" : 
                 apply.getStatus() == 0 ? "已同意" : 
                 apply.getStatus() == 1 ? "已不同意" : "未知"));
        }
        
        // 3. 更新申请记录的审核原因、状态、更新人和更新时间
        apply.setReason(reason);
        apply.setUpdateTime(new Date());
        apply.setUpdateMan("系统");
        
        if (approved) {
            // 同意：继续原有流程
            // 3. 查询用户是否存在
            Users user = usersMapper.selectById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            
            // 4. 更新用户的isMatchmaker为1
            Users updateUser = new Users();
            updateUser.setUserId(userId);
            updateUser.setIsMatchmaker(1);
            int userUpdateResult = usersMapper.updateById(updateUser);
            if (userUpdateResult <= 0) {
                throw new RuntimeException("更新用户红娘状态失败");
            }
            System.out.println("✅ 已更新 users 表，is_matchmaker = 1");
            
            // 5. 创建或更新 matchmakers 记录
            QueryWrapper<Matchmaker> matchmakerWrapper = new QueryWrapper<>();
            matchmakerWrapper.eq("user_id", apply.getUserId());
            Matchmaker existingMatchmaker = matchmakerMapper.selectOne(matchmakerWrapper);
            
            Matchmaker matchmaker;
            boolean isUpdate = false;
            
            if (existingMatchmaker != null) {
                matchmaker = existingMatchmaker;
                isUpdate = true;
                System.out.println("⚠️ 该用户已存在红娘记录，将更新现有记录，matchmaker_id = " + matchmaker.getMatchmakerId());
            } else {
                matchmaker = new Matchmaker();
                matchmaker.setCreateTime(LocalDateTime.now());
            }
            
            matchmaker.setUserId(apply.getUserId());
            matchmaker.setRealName(apply.getName());
            matchmaker.setPhone(apply.getPhone());
            matchmaker.setEmail(apply.getEmail());
            matchmaker.setGender(apply.getGender());
            matchmaker.setProfile(apply.getExperience());
            
            parseAreaToIds(apply.getArea(), matchmaker);
            
            String baseUsername = user.getNickname() != null ? user.getNickname() : user.getPhone();
            if (!isUpdate || matchmaker.getUsername() == null || !baseUsername.equals(matchmaker.getUsername())) {
                String finalUsername = generateUniqueUsername(baseUsername, matchmaker.getUserId());
                matchmaker.setUsername(finalUsername);
            }
            
            matchmaker.setPassword(user.getPassword());
            matchmaker.setBirthDate(user.getBirthDate());
            
            if (apply.getGender() != null && apply.getGender() == 1) {
                matchmaker.setAvatarUrl("http://115.190.125.125:9000/dynamic-comments/dynamics/5c645152-9940-41d3-83a9-69ee6e0c0aaa.png");
            } else {
                matchmaker.setAvatarUrl("http://115.190.125.125:9000/dynamic-comments/dynamics/c7fb04d7-ee4d-4b3d-bcef-f246da9c841f.png");
            }
            
            if (!isUpdate) {
                matchmaker.setMatchmakerType(1);
                matchmaker.setLevel(1);
                matchmaker.setSuccessCouples(0);
            }
            matchmaker.setStatus(1);
            matchmaker.setUpdateTime(LocalDateTime.now());
            
            int result;
            if (isUpdate) {
                result = matchmakerMapper.updateById(matchmaker);
                if (result <= 0) {
                    throw new RuntimeException("更新红娘记录失败");
                }
                System.out.println("✅ 已更新 matchmakers 记录，matchmaker_id = " + matchmaker.getMatchmakerId());
            } else {
                result = matchmakerMapper.insert(matchmaker);
                if (result <= 0) {
                    throw new RuntimeException("创建红娘记录失败");
                }
                System.out.println("✅ 已创建 matchmakers 记录，matchmaker_id = " + matchmaker.getMatchmakerId());
            }
            
            // 6. 导入到腾讯云 IM
            String imUserId = "m_" + matchmaker.getMatchmakerId();
            try {
                Map<String, String> imParams = new HashMap<>();
                imParams.put("userId", imUserId);
                imParams.put("nickname", matchmaker.getRealName());
                if (matchmaker.getAvatarUrl() != null && !matchmaker.getAvatarUrl().isEmpty()) {
                    imParams.put("faceUrl", matchmaker.getAvatarUrl());
                }
                
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, String>> request = new HttpEntity<>(imParams, headers);
                
                restTemplate.postForObject(IM_SERVICE_URL + "/importUser", request, Map.class);
                System.out.println("✅ 已导入到腾讯云 IM: imUserId = " + imUserId);
            } catch (Exception e) {
                System.err.println("❌ 导入到 IM 失败: " + e.getMessage());
                e.printStackTrace();
            }
            
            // 7. 更新申请状态为审核通过（从2变成0）
            apply.setStatus(0); // 0-同意
        } else {
            // 不同意：只更新审核原因和状态（从2变成1）
            apply.setStatus(1); // 1-不同意
        }
        
        this.updateById(apply);
        System.out.println("========== 审核完成 ==========");
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchApprove(List<Long> applyIds, Boolean approved, String reason) {
        if (applyIds == null || applyIds.isEmpty()) {
            throw new RuntimeException("申请ID列表不能为空");
        }
        
        System.out.println("========== 开始批量审核红娘申请 ==========");
        System.out.println("申请数量: " + applyIds.size() + ", 审核结果: " + (approved ? "同意" : "不同意") + ", 原因: " + reason);
        
        int successCount = 0;
        int failCount = 0;
        
        for (Long applyId : applyIds) {
            try {
                // 查询申请信息获取userId
                MarrApply apply = this.getById(applyId);
                if (apply == null) {
                    System.err.println("❌ 申请ID " + applyId + " 不存在，跳过");
                    failCount++;
                    continue;
                }
                
                if (apply.getUserId() == null) {
                    System.err.println("❌ 申请ID " + applyId + " 的用户ID为空，跳过");
                    failCount++;
                    continue;
                }
                
                // 调用单个审核方法
                approve(applyId, apply.getUserId(), approved, reason);
                successCount++;
            } catch (Exception e) {
                System.err.println("❌ 审核申请ID " + applyId + " 失败: " + e.getMessage());
                e.printStackTrace();
                failCount++;
            }
        }
        
        System.out.println("========== 批量审核完成 ==========");
        System.out.println("成功: " + successCount + ", 失败: " + failCount);
        
        if (failCount > 0) {
            throw new RuntimeException("批量审核完成，成功 " + successCount + " 条，失败 " + failCount + " 条");
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long applyId) {
        // 逻辑删除：将 idStatus 设置为 "1"（禁止状态）
        MarrApply marrApply = new MarrApply();
        marrApply.setApplyId(applyId);
        marrApply.setIdStatus("1"); // 1-禁止（逻辑删除）
        return this.updateById(marrApply);
    }
    
    /**
     * 解析地区字符串，将省市区名称转换为对应的ID
     * area 格式可能是："北京市 北京市 朝阳区" 或 "北京市 北京市 朝阳区"（用空格分隔）
     * 
     * @param area 地区字符串
     * @param matchmaker 红娘对象，用于设置 provinceId, cityId, areaId
     */
    private void parseAreaToIds(String area, Matchmaker matchmaker) {
        if (area == null || area.trim().isEmpty()) {
            System.out.println("⚠️ 地区信息为空，跳过解析");
            return;
        }
        
        try {
            // 按空格分割地区字符串
            String[] areaParts = area.trim().split("\\s+");
            
            if (areaParts.length >= 1 && provinceMapper != null) {
                // 解析省份
                String provinceName = areaParts[0].trim();
                QueryWrapper<Province> provinceWrapper = new QueryWrapper<>();
                provinceWrapper.eq("name", provinceName);
                Province province = provinceMapper.selectOne(provinceWrapper);
                if (province != null) {
                    matchmaker.setProvinceId(province.getId());
                    System.out.println("✅ 解析省份: " + provinceName + " -> " + province.getId());
                } else {
                    System.out.println("⚠️ 未找到省份: " + provinceName);
                }
            }
            
            if (areaParts.length >= 2 && cityMapper != null && matchmaker.getProvinceId() != null) {
                // 解析城市
                String cityName = areaParts[1].trim();
                QueryWrapper<City> cityWrapper = new QueryWrapper<>();
                cityWrapper.eq("name", cityName);
                cityWrapper.eq("province_id", matchmaker.getProvinceId());
                City city = cityMapper.selectOne(cityWrapper);
                if (city != null) {
                    matchmaker.setCityId(city.getId());
                    System.out.println("✅ 解析城市: " + cityName + " -> " + city.getId());
                } else {
                    System.out.println("⚠️ 未找到城市: " + cityName);
                }
            }
            
            if (areaParts.length >= 3 && areaMapper != null && matchmaker.getCityId() != null) {
                // 解析区域
                String areaName = areaParts[2].trim();
                QueryWrapper<Area> areaWrapper = new QueryWrapper<>();
                areaWrapper.eq("name", areaName);
                areaWrapper.eq("city_id", matchmaker.getCityId());
                Area areaObj = areaMapper.selectOne(areaWrapper);
                if (areaObj != null) {
                    matchmaker.setAreaId(areaObj.getId());
                    System.out.println("✅ 解析区域: " + areaName + " -> " + areaObj.getId());
                } else {
                    System.out.println("⚠️ 未找到区域: " + areaName);
                }
            }
            
            if (areaParts.length < 3) {
                System.out.println("⚠️ 地区信息不完整，只有 " + areaParts.length + " 部分: " + area);
            }
        } catch (Exception e) {
            System.err.println("❌ 解析地区信息失败: " + e.getMessage());
            e.printStackTrace();
            // 解析失败不影响审核流程，只记录日志
        }
    }
    
    /**
     * 生成唯一的用户名
     * 如果用户名已存在，则添加后缀（_1, _2, ...）直到找到不存在的用户名
     * 
     * @param baseUsername 基础用户名
     * @param currentUserId 当前用户ID（如果更新现有记录，排除自己）
     * @return 唯一的用户名
     */
    private String generateUniqueUsername(String baseUsername, Integer currentUserId) {
        if (baseUsername == null || baseUsername.trim().isEmpty()) {
            baseUsername = "user_" + System.currentTimeMillis();
        }
        
        String username = baseUsername.trim();
        int suffix = 0;
        
        while (true) {
            QueryWrapper<Matchmaker> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            // 如果当前用户ID不为空，排除自己的记录（用于更新场景）
            if (currentUserId != null) {
                wrapper.ne("user_id", currentUserId);
            }
            
            Matchmaker existing = matchmakerMapper.selectOne(wrapper);
            
            if (existing == null) {
                // 用户名不存在，可以使用
                if (suffix > 0) {
                    System.out.println("⚠️ 用户名 '" + baseUsername + "' 已存在，使用新用户名: " + username);
                }
                return username;
            }
            
            // 用户名已存在，添加后缀
            suffix++;
            username = baseUsername + "_" + suffix;
        }
    }
}




