package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.LoveWhoIPairsHope;
import com.rj.service.ILoveWhoIPairsHopeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 择偶/恋爱期望画像表 前端控制器
 *
 * @author system
 * @since 2026-04-05
 */
@RestController
@RequestMapping("/api/loveWhoIPairsHope")
@Tag(name = "择偶期望画像", description = "love_whoI_pairs_hope 表 CRUD")
public class LoveWhoIPairsHopeController {

    @Autowired
    private ILoveWhoIPairsHopeService loveWhoIPairsHopeService;

    @PostMapping("/add")
    @Operation(summary = "新增", description = "新增一条择偶/恋爱期望画像")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体 JSON", required = true)
            @RequestBody LoveWhoIPairsHope body) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (body.getId() == null || body.getId().trim().isEmpty()) {
                body.setId(UUID.randomUUID().toString());
            }
            LocalDateTime now = LocalDateTime.now();
            body.setCreateTime(now);
            body.setUpdateTime(now);
            boolean success = loveWhoIPairsHopeService.save(body);
            if (success) {
                result.put("success", true);
                result.put("message", "添加成功");
                result.put("data", body);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "添加失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "按主键查询", description = "根据 id（UUID）查询")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "主键 UUID", required = true) @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            LoveWhoIPairsHope row = loveWhoIPairsHopeService.getById(id);
            if (row != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", row);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "记录不存在");
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/getByRelatedId")
    @Operation(summary = "按关联ID查询列表", description = "根据 relatedId 精确匹配，按修改时间倒序")
    public ResponseEntity<Map<String, Object>> getByRelatedId(
            @Parameter(description = "关联 UUID", required = true) @RequestParam String relatedId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<LoveWhoIPairsHope> qw = new LambdaQueryWrapper<>();
            qw.eq(LoveWhoIPairsHope::getRelatedId, relatedId);
            qw.orderByDesc(LoveWhoIPairsHope::getUpdateTime);
            List<LoveWhoIPairsHope> list = loveWhoIPairsHopeService.list(qw);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", list);
            result.put("count", list.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/list")
    @Operation(summary = "分页列表", description = "支持 tenantId、myPhone、relatedId、名字、性别、行业等条件")
    public ResponseEntity<Map<String, Object>> list(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "租户ID（精确）") @RequestParam(required = false) String tenantId,
            @Parameter(description = "手机号码（模糊）") @RequestParam(required = false) String myPhone,
            @Parameter(description = "关联ID（精确）") @RequestParam(required = false) String relatedId,
            @Parameter(description = "名字（模糊）") @RequestParam(required = false) String name,
            @Parameter(description = "性别（模糊）") @RequestParam(required = false) String gender,
            @Parameter(description = "行业（模糊）") @RequestParam(required = false) String industry,
            @Parameter(description = "创建开始时间 yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) String createStartTime,
            @Parameter(description = "创建结束时间 yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) String createEndTime,
            @Parameter(description = "修改开始时间 yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) String updateStartTime,
            @Parameter(description = "修改结束时间 yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) String updateEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<LoveWhoIPairsHope> page = new Page<>(current, size);
            LambdaQueryWrapper<LoveWhoIPairsHope> qw = new LambdaQueryWrapper<>();
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                qw.eq(LoveWhoIPairsHope::getTenantId, tenantId);
            }
            if (myPhone != null && !myPhone.trim().isEmpty()) {
                qw.like(LoveWhoIPairsHope::getMyPhone, myPhone);
            }
            if (relatedId != null && !relatedId.trim().isEmpty()) {
                qw.eq(LoveWhoIPairsHope::getRelatedId, relatedId);
            }
            if (name != null && !name.trim().isEmpty()) {
                qw.like(LoveWhoIPairsHope::getName, name);
            }
            if (gender != null && !gender.trim().isEmpty()) {
                qw.like(LoveWhoIPairsHope::getGender, gender);
            }
            if (industry != null && !industry.trim().isEmpty()) {
                qw.like(LoveWhoIPairsHope::getIndustry, industry);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createStartTime != null && !createStartTime.trim().isEmpty()) {
                try {
                    qw.ge(LoveWhoIPairsHope::getCreateTime, LocalDateTime.parse(createStartTime, formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建开始时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (createEndTime != null && !createEndTime.trim().isEmpty()) {
                try {
                    qw.le(LoveWhoIPairsHope::getCreateTime, LocalDateTime.parse(createEndTime, formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (updateStartTime != null && !updateStartTime.trim().isEmpty()) {
                try {
                    qw.ge(LoveWhoIPairsHope::getUpdateTime, LocalDateTime.parse(updateStartTime, formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "修改开始时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (updateEndTime != null && !updateEndTime.trim().isEmpty()) {
                try {
                    qw.le(LoveWhoIPairsHope::getUpdateTime, LocalDateTime.parse(updateEndTime, formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "修改结束时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            qw.orderByDesc(LoveWhoIPairsHope::getUpdateTime);
            Page<LoveWhoIPairsHope> p = loveWhoIPairsHopeService.page(page, qw);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", p.getRecords());
            result.put("total", p.getTotal());
            result.put("current", p.getCurrent());
            result.put("size", p.getSize());
            result.put("pages", p.getPages());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PutMapping("/update")
    @Operation(summary = "更新", description = "按主键 id 更新；修改时间由服务端刷新")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "实体 JSON（须含 id）", required = true)
            @RequestBody LoveWhoIPairsHope body) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (body.getId() == null || body.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "id 不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            body.setUpdateTime(LocalDateTime.now());
            boolean success = loveWhoIPairsHopeService.updateById(body);
            if (success) {
                result.put("success", true);
                result.put("message", "更新成功");
                result.put("data", body);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "更新失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除", description = "按主键删除")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键 UUID", required = true) @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = loveWhoIPairsHopeService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "删除失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除", description = "请求体为 id 字符串列表")
    public ResponseEntity<Map<String, Object>> batchDelete(
            @Parameter(description = "主键 UUID 列表", required = true) @RequestBody List<String> ids) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("success", false);
                result.put("message", "id 列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            boolean success = loveWhoIPairsHopeService.removeByIds(ids);
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共 " + ids.size() + " 条");
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "批量删除失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
