package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.*;
import com.zhentao.mapper.*;
import com.zhentao.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/admin/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UsersMapper usersMapper;
    
    @Autowired
    private UserVipMapper userVipMapper;
    
    @Autowired
    private UserMatchmakerBindingMapper userMatchmakerBindingMapper;
    
    @Autowired
    private MatchmakerMapper matchmakerMapper;
    
    /**
     * 用户列表（分页）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer gender,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword) {
        
        try {
            Page<Users> pageInfo = new Page<>(page, pageSize);
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            
            // 性别筛选
            if (gender != null) {
                queryWrapper.eq("gender", gender);
            }
            
            // 状态筛选
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            // 关键词搜索
            if (keyword != null && !keyword.isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                        .like("nickname", keyword)
                        .or()
                        .like("phone", keyword)
                        .or()
                        .like("email", keyword));
            }
            
            // 按创建时间倒序
            queryWrapper.orderByDesc("created_at");
            
            Page<Users> result = usersMapper.selectPage(pageInfo, queryWrapper);
            
            // 转换为UserVO并填充VIP和红娘信息
            List<UserVO> userVOList = result.getRecords().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", userVOList);
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 将Users转换为UserVO并填充关联信息
     */
    private UserVO convertToUserVO(Users user) {
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        
        // 填充VIP信息
        fillVipInfo(vo, user.getUserId());
        
        // 填充红娘信息
        fillMatchmakerInfo(vo, user.getUserId());
        
        return vo;
    }
    
    /**
     * 填充VIP信息
     */
    private void fillVipInfo(UserVO vo, Integer userId) {
        try {
            // 查询生效中的VIP记录
            QueryWrapper<UserVip> vipWrapper = new QueryWrapper<>();
            vipWrapper.eq("user_id", userId)
                    .eq("status", 1)  // 状态：生效中
                    .gt("end_time", LocalDateTime.now())  // 未过期
                    .orderByDesc("end_time")
                    .last("LIMIT 1");
            
            UserVip userVip = userVipMapper.selectOne(vipWrapper);
            
            if (userVip != null) {
                vo.setIsVip(true);
                vo.setVipLevel("VIP会员");
                vo.setVipStartTime(userVip.getStartTime());
                vo.setVipEndTime(userVip.getEndTime());
                
                // 计算剩余天数
                long days = Duration.between(LocalDateTime.now(), userVip.getEndTime()).toDays();
                vo.setVipRemainingDays((int) days);
            } else {
                vo.setIsVip(false);
                vo.setVipLevel("普通用户");
                vo.setVipRemainingDays(0);
            }
        } catch (Exception e) {
            vo.setIsVip(false);
            vo.setVipLevel("普通用户");
            vo.setVipRemainingDays(0);
        }
    }
    
    /**
     * 填充红娘信息
     */
    private void fillMatchmakerInfo(UserVO vo, Integer userId) {
        try {
            // 查询红娘绑定关系
            QueryWrapper<UserMatchmakerBinding> bindingWrapper = new QueryWrapper<>();
            bindingWrapper.eq("user_id", userId)
                    .eq("status", 1)  // 状态：有效
                    .orderByDesc("bound_at")
                    .last("LIMIT 1");
            
            UserMatchmakerBinding binding = userMatchmakerBindingMapper.selectOne(bindingWrapper);
            
            if (binding != null) {
                vo.setMatchmakerId(binding.getMatchmakerId());
                vo.setBoundAt(binding.getBoundAt());
                
                // 查询红娘信息
                Matchmaker matchmaker = matchmakerMapper.selectById(binding.getMatchmakerId());
                if (matchmaker != null) {
                    vo.setMatchmakerName(matchmaker.getRealName());
                    vo.setMatchmakerPhone(matchmaker.getPhone());
                }
            }
        } catch (Exception e) {
            // 忽略异常，不影响主流程
        }
    }
    
    /**
     * 认证用户列表（资料完整的用户）
     */
    @GetMapping("/vip/list")
    public Result<Map<String, Object>> vipList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        try {
            Page<Users> pageInfo = new Page<>(page, pageSize);
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            
            // 只查询资料完整的用户
            queryWrapper.eq("is_profile_complete", 1);
            queryWrapper.orderByDesc("created_at");
            
            Page<Users> result = usersMapper.selectPage(pageInfo, queryWrapper);
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户详情
     */
    @GetMapping("/detail/{userId}")
    public Result<Users> detail(@PathVariable Integer userId) {
        try {
            Users user = usersMapper.selectById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/update/{userId}")
    public Result<String> updateStatus(@PathVariable Integer userId, @RequestBody Map<String, Object> params) {
        try {
            Users user = usersMapper.selectById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            if (params.containsKey("status")) {
                user.setStatus((Integer) params.get("status"));
                usersMapper.updateById(user);
            }
            
            return Result.success("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户统计
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> stats() {
        try {
            // 总用户数
            Long totalUsers = usersMapper.selectCount(null);
            
            // 资料完整用户数
            QueryWrapper<Users> completeWrapper = new QueryWrapper<>();
            completeWrapper.eq("is_profile_complete", 1);
            Long completeUsers = usersMapper.selectCount(completeWrapper);
            
            // 男性用户数
            QueryWrapper<Users> maleWrapper = new QueryWrapper<>();
            maleWrapper.eq("gender", 1);
            Long maleUsers = usersMapper.selectCount(maleWrapper);
            
            // 女性用户数
            QueryWrapper<Users> femaleWrapper = new QueryWrapper<>();
            femaleWrapper.eq("gender", 2);
            Long femaleUsers = usersMapper.selectCount(femaleWrapper);
            
            // 活跃用户数（最近7天登录）
            QueryWrapper<Users> activeWrapper = new QueryWrapper<>();
            activeWrapper.gt("last_login_at", java.time.LocalDateTime.now().minusDays(7));
            Long activeUsers = usersMapper.selectCount(activeWrapper);
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalUsers", totalUsers);
            stats.put("completeUsers", completeUsers);
            stats.put("maleUsers", maleUsers);
            stats.put("femaleUsers", femaleUsers);
            stats.put("activeUsers", activeUsers);
            
            return Result.success(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("统计失败：" + e.getMessage());
        }
    }
}

