package com.zhentao.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.pojo.MatchmakerApply;
import com.zhentao.service.MatchmakerApplyService;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 红娘申请控制器
 */
@RestController
@RequestMapping("/api/matchmaker-apply")
@CrossOrigin(origins = "*")
public class MatchmakerApplyController {
    
    @Autowired
    private MatchmakerApplyService matchmakerApplyService;
    
    /**
     * 提交红娘申请
     * @param matchmakerApply 申请信息（包含userId和表单数据）
     * @return 申请结果
     */
    /**
     * 提交红娘申请 - 使用Map接收原始数据
     */
    @PostMapping("/submit")
    public Result<String> submitApply(@RequestBody Map<String, Object> requestData, HttpServletRequest request) {
        try {
            // 打印接收到的原始数据
            System.out.println("========== 红娘申请提交 ==========");
            System.out.println("原始请求数据: " + requestData);
            System.out.println("userId字段: " + requestData.get("userId"));
            System.out.println("userId类型: " + (requestData.get("userId") != null ? requestData.get("userId").getClass().getName() : "null"));
            System.out.println("==================================");
            
            // 手动转换为 MatchmakerApply 对象
            ObjectMapper mapper = new ObjectMapper();
            MatchmakerApply matchmakerApply = mapper.convertValue(requestData, MatchmakerApply.class);
            
            System.out.println("转换后的对象: " + matchmakerApply);
            System.out.println("转换后userId: " + matchmakerApply.getUserId());
            System.out.println("==================================");
            
            // 验证必填字段
            if (matchmakerApply.getUserId() == null) {
                System.err.println("❌ 用户ID为空！");
                return Result.error("用户ID不能为空");
            }
            
            if (matchmakerApply.getName() == null || matchmakerApply.getName().trim().isEmpty()) {
                return Result.error("姓名不能为空");
            }
            
            if (matchmakerApply.getPhone() == null || matchmakerApply.getPhone().trim().isEmpty()) {
                return Result.error("手机号不能为空");
            }
            
            if (matchmakerApply.getEmail() == null || matchmakerApply.getEmail().trim().isEmpty()) {
                return Result.error("邮箱不能为空");
            }
            
            if (matchmakerApply.getAge() == null) {
                return Result.error("年龄不能为空");
            }
            
            if (matchmakerApply.getGender() == null) {
                return Result.error("性别不能为空");
            }
            
            if (matchmakerApply.getArea() == null || matchmakerApply.getArea().trim().isEmpty()) {
                return Result.error("所在地区不能为空");
            }
            
            if (matchmakerApply.getExperience() == null || matchmakerApply.getExperience().trim().isEmpty()) {
                return Result.error("婚姻介绍经验不能为空");
            }
            
            if (matchmakerApply.getServerTime() == null || matchmakerApply.getServerTime().trim().isEmpty()) {
                return Result.error("可服务时间不能为空");
            }
            
            if (matchmakerApply.getIntroduction() == null || matchmakerApply.getIntroduction().trim().isEmpty()) {
                return Result.error("个人简介不能为空");
            }
            
            // 提交申请
            boolean success = matchmakerApplyService.submitApply(matchmakerApply);
            
            if (success) {
                return Result.success("申请提交成功，请等待审核");
            } else {
                return Result.error("申请提交失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("申请提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询用户的红娘申请状态
     * @param userId 用户ID
     * @return 申请状态信息
     */
    @GetMapping("/status")
    public Result<Map<String, Object>> getApplyStatus(@RequestParam("userId") Long userId) {
        try {
            System.out.println("========== 查询红娘申请状态 ==========");
            System.out.println("userId: " + userId);
            
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }
            
            // 查询申请记录
            MatchmakerApply apply = matchmakerApplyService.getApplyByUserId(userId);
            
            Map<String, Object> result = new HashMap<>();
            if (apply == null) {
                // 没有申请记录，status为null
                result.put("status", null);
                result.put("hasApplied", false);
                System.out.println("未找到申请记录");
            } else {
                // 有申请记录，返回status值
                result.put("status", apply.getStatus());
                result.put("hasApplied", true);
                result.put("applyId", apply.getApplyId());
                result.put("createTime", apply.getCreateTime());
                System.out.println("找到申请记录，status: " + apply.getStatus());
            }
            
            System.out.println("返回结果: " + result);
            System.out.println("=====================================");
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询申请状态失败：" + e.getMessage());
        }
    }
}