package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.AiPrompts;
import com.rj.service.IAiPromptsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
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.Map;
import java.util.UUID;

/**
 * 表 ai_prompts 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/aiPrompts")
@Tag(name = "AI提示词配置(ai_prompts)", description = "增删改查与分页")
public class AiPromptsController {

    @Autowired
    private IAiPromptsService aiPromptsService;

    @PostMapping("/add")
    @Operation(summary = "新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体", required = true) @RequestBody AiPrompts entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getId() == null || entity.getId().trim().isEmpty()) {
                entity.setId(UUID.randomUUID().toString());
            }
            LocalDateTime now = LocalDateTime.now();
            if (entity.getCreateTime() == null) {
                entity.setCreateTime(now);
            }
            entity.setUpdateTime(now);
            boolean ok = aiPromptsService.save(entity);
            if (ok) {
                result.put("success", true);
                result.put("message", "添加成功");
                result.put("data", entity);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "添加失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("ai_prompts add error", e);
            result.put("success", false);
            result.put("message", "添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "按ID查询")
    public ResponseEntity<Map<String, Object>> getById(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            AiPrompts one = aiPromptsService.getById(id);
            if (one != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", one);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "记录不存在");
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("ai_prompts get error, id={}", id, e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String scenarioCode,
            @RequestParam(required = false) String categoryCode,
            @RequestParam(required = false) String fieldCode,
            @RequestParam(required = false) String promptType,
            @RequestParam(required = false) String promptKeyword,
            @RequestParam(required = false) String createStartTime,
            @RequestParam(required = false) String createEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<AiPrompts> page = new Page<>(current, size);
            LambdaQueryWrapper<AiPrompts> q = new LambdaQueryWrapper<>();
            if (scenarioCode != null && !scenarioCode.trim().isEmpty()) {
                q.eq(AiPrompts::getScenarioCode, scenarioCode);
            }
            if (categoryCode != null && !categoryCode.trim().isEmpty()) {
                q.eq(AiPrompts::getCategoryCode, categoryCode);
            }
            if (fieldCode != null && !fieldCode.trim().isEmpty()) {
                q.eq(AiPrompts::getFieldCode, fieldCode);
            }
            if (promptType != null && !promptType.trim().isEmpty()) {
                q.eq(AiPrompts::getPromptType, promptType);
            }
            if (promptKeyword != null && !promptKeyword.trim().isEmpty()) {
                q.like(AiPrompts::getPromptText, promptKeyword);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createStartTime != null && !createStartTime.trim().isEmpty()) {
                try {
                    q.ge(AiPrompts::getCreateTime, LocalDateTime.parse(createStartTime, formatter));
                } catch (Exception ex) {
                    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 {
                    q.le(AiPrompts::getCreateTime, LocalDateTime.parse(createEndTime, formatter));
                } catch (Exception ex) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            q.orderByDesc(AiPrompts::getCreateTime);
            Page<AiPrompts> data = aiPromptsService.page(page, q);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", data.getRecords());
            result.put("total", data.getTotal());
            result.put("current", data.getCurrent());
            result.put("size", data.getSize());
            result.put("pages", data.getPages());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("ai_prompts list error", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PutMapping("/update")
    @Operation(summary = "更新")
    public ResponseEntity<Map<String, Object>> update(@RequestBody AiPrompts entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getId() == null || entity.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            entity.setUpdateTime(LocalDateTime.now());
            boolean ok = aiPromptsService.updateById(entity);
            if (ok) {
                result.put("success", true);
                result.put("message", "更新成功");
                result.put("data", aiPromptsService.getById(entity.getId()));
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "更新失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("ai_prompts update error", e);
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean ok = aiPromptsService.removeById(id);
            if (ok) {
                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) {
            log.error("ai_prompts delete error", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
