package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.LoveCheckItemChild;
import com.rj.service.ILoveCheckItemChildService;
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;

/**
 * 恋爱/择偶检查项子表 前端控制器（love_check_item_child）
 *
 * @author system
 * @since 2026-04-06
 */
@RestController
@RequestMapping("/api/loveCheckItemChild")
@Tag(name = "恋爱检查项子表", description = "love_check_item_child 表 CRUD")
public class LoveCheckItemChildController {

    @Autowired
    private ILoveCheckItemChildService loveCheckItemChildService;

    @PostMapping("/add")
    @Operation(summary = "新增", description = "新增一条子表记录")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体 JSON", required = true)
            @RequestBody LoveCheckItemChild 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 = loveCheckItemChildService.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 {
            LoveCheckItemChild row = loveCheckItemChildService.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("/list")
    @Operation(summary = "分页列表", description = "支持 parentId、项目名称、场景（模糊）及时间范围等条件")
    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 parentId,
            @Parameter(description = "项目名称（模糊）") @RequestParam(required = false) String projectName,
            @Parameter(description = "场景（模糊）") @RequestParam(required = false) String scenario,
            @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<LoveCheckItemChild> page = new Page<>(current, size);
            LambdaQueryWrapper<LoveCheckItemChild> qw = new LambdaQueryWrapper<>();
            if (parentId != null && !parentId.trim().isEmpty()) {
                qw.eq(LoveCheckItemChild::getParentId, parentId);
            }
            if (projectName != null && !projectName.trim().isEmpty()) {
                qw.like(LoveCheckItemChild::getProjectName, projectName);
            }
            if (scenario != null && !scenario.trim().isEmpty()) {
                qw.like(LoveCheckItemChild::getScenario, scenario);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createStartTime != null && !createStartTime.trim().isEmpty()) {
                try {
                    qw.ge(LoveCheckItemChild::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(LoveCheckItemChild::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(LoveCheckItemChild::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(LoveCheckItemChild::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(LoveCheckItemChild::getUpdateTime);
            Page<LoveCheckItemChild> p = loveCheckItemChildService.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 LoveCheckItemChild 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 = loveCheckItemChildService.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 = loveCheckItemChildService.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 = loveCheckItemChildService.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);
        }
    }
}
