package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.pojo.PartnerRequirement;
import com.zhentao.service.PartnerRequirementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 择偶要求Controller
 */
@RestController
@RequestMapping("/api/partner-requirement")
public class PartnerRequirementController {
    
    @Autowired
    private PartnerRequirementService partnerRequirementService;
    
    /**
     * 获取用户的择偶要求
     * @param userId 用户ID
     * @return 择偶要求信息
     */
    @GetMapping("/{userId}")
    public Result<PartnerRequirement> getRequirement(@PathVariable Long userId) {
        try {
            PartnerRequirement requirement = partnerRequirementService.getByUserId(userId);
            if (requirement == null) {
                // 如果没有记录，返回一个空对象
                requirement = new PartnerRequirement();
                requirement.setUserId(userId);
            }
            return Result.success(requirement);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取择偶要求失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存或更新择偶要求
     * @param requirement 择偶要求信息
     * @return 操作结果
     */
    @PostMapping("/save")
    public Result<String> saveRequirement(@RequestBody PartnerRequirement requirement) {
        try {
            if (requirement.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }
            
            boolean success = partnerRequirementService.saveOrUpdateRequirement(requirement);
            if (success) {
                return Result.success("保存成功");
            } else {
                return Result.error("保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存择偶要求失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除择偶要求
     * @param userId 用户ID
     * @return 操作结果
     */
    @DeleteMapping("/{userId}")
    public Result<String> deleteRequirement(@PathVariable Long userId) {
        try {
            PartnerRequirement requirement = partnerRequirementService.getByUserId(userId);
            if (requirement != null) {
                boolean success = partnerRequirementService.removeById(requirement.getId());
                if (success) {
                    return Result.success("删除成功");
                } else {
                    return Result.error("删除失败");
                }
            }
            return Result.success("记录不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除择偶要求失败：" + e.getMessage());
        }
    }
}