package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.AiQaMain;
import com.rj.service.IAiQaMainService;
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.List;
import java.util.Map;
import java.util.UUID;

/**
 * AI 问答主表 前端控制器
 *
 * <p>对应表：ai_qa_main</p>
 */
@Slf4j
@RestController
@RequestMapping("/api/aiQaMain")
@Tag(name = "AI问答主表", description = "AI问答主表增删改查与分页")
public class AiQaMainController {

    @Autowired
    private IAiQaMainService aiQaMainService;

    @PostMapping("/add")
    @Operation(summary = "新增", description = "新增 AI 问答主表记录")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体", required = true) @RequestBody AiQaMain 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 = aiQaMainService.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_qa_main 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 {
            AiQaMain one = aiQaMainService.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_qa_main 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 salesId,
            @RequestParam(required = false) String salesPhone,
            @RequestParam(required = false) String salesName ) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<AiQaMain> page = new Page<>(current, size);
            LambdaQueryWrapper<AiQaMain> q = new LambdaQueryWrapper<>();
            if (salesPhone != null && !salesPhone.trim().isEmpty()) {
                q.like(AiQaMain::getSalesPhone, salesPhone);
            }
            if (salesName != null && !salesName.trim().isEmpty()) {
                q.eq(AiQaMain::getSalesName, salesName);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            q.orderByDesc(AiQaMain::getCreateTime);
            Page<AiQaMain> data = aiQaMainService.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_qa_main 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 AiQaMain 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 = aiQaMainService.updateById(entity);
            if (ok) {
                result.put("success", true);
                result.put("message", "更新成功");
                result.put("data", aiQaMainService.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_qa_main 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 = aiQaMainService.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_qa_main delete error", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除")
    public ResponseEntity<Map<String, Object>> batchDelete(@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 ok = aiQaMainService.removeByIds(ids);
            if (ok) {
                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) {
            log.error("ai_qa_main batchDelete error", e);
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
