package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.dto.AiQaCustomerAskRequestDto;
import com.rj.dto.AiQaCustomerAskResponseDto;
import com.rj.entity.AiQaItem;
import com.rj.service.IAiQaCustomerAskService;
import com.rj.service.IAiQaItemService;
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.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

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_item</p>
 */
@Slf4j
@RestController
@RequestMapping("/api/aiQaItem")
@Tag(name = "AI问答子表", description = "AI问答子表增删改查与分页")
public class AiQaItemController {

    @Autowired
    private IAiQaItemService aiQaItemService;

    @Autowired
    private IAiQaCustomerAskService aiQaCustomerAskService;

    @PostMapping("/askAI")
    @Operation(summary = "客户问答（大模型）", description = "接收客户问题，调用本地 OpenAI 兼容 Chat Completions，将回答返回给前端")
    public ResponseEntity<Map<String, Object>> askCustomer(
            @Parameter(description = "提问请求", required = true) @RequestBody AiQaCustomerAskRequestDto request) {
        Map<String, Object> result = new HashMap<>();
        try {
            AiQaCustomerAskResponseDto data = aiQaCustomerAskService.askCustomer(request);
            result.put("success", true);
            result.put("message", "回答生成成功");
            result.put("data", data);
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("ai_qa_item ask error", e);
            result.put("success", false);
            result.put("message", "调用大模型异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PostMapping(value = "/askAIStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "客户问答（大模型流式）", description = "流式返回大模型回答分片，流完成后自动落库")
    public Flux<String> askCustomerStream(
            @Parameter(description = "提问请求", required = true) @RequestBody AiQaCustomerAskRequestDto request) {
        return aiQaCustomerAskService.askCustomerStream(request);
    }

    @PostMapping("/add")
    @Operation(summary = "新增", description = "新增 AI 问答子表记录")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体", required = true) @RequestBody AiQaItem 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 = aiQaItemService.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_item 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 {
            AiQaItem one = aiQaItemService.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_item 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 parentId,
            @RequestParam(required = false) String tenantId,
            @RequestParam(required = false) String questSrc,
            @RequestParam(required = false) String createStartTime,
            @RequestParam(required = false) String createEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<AiQaItem> page = new Page<>(current, size);
            LambdaQueryWrapper<AiQaItem> q = new LambdaQueryWrapper<>();
            if (parentId != null && !parentId.trim().isEmpty()) {
                q.eq(AiQaItem::getParentId, parentId);
            }
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                q.eq(AiQaItem::getTenantId, tenantId);
            }
            if (questSrc != null && !questSrc.trim().isEmpty()) {
                q.like(AiQaItem::getQuestSrc, questSrc);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createStartTime != null && !createStartTime.trim().isEmpty()) {
                try {
                    q.ge(AiQaItem::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(AiQaItem::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(AiQaItem::getCreateTime);
            Page<AiQaItem> data = aiQaItemService.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_item list error", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/listByParentId")
    @Operation(summary = "按主表ID列表查询（不分页）")
    public ResponseEntity<Map<String, Object>> listByParentId(@RequestParam String parentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<AiQaItem> q = new LambdaQueryWrapper<>();
            q.eq(AiQaItem::getParentId, parentId);
            q.orderByDesc(AiQaItem::getCreateTime);
            List<AiQaItem> list = aiQaItemService.list(q);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", list);
            result.put("count", list.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("ai_qa_item listByParentId 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 AiQaItem 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 = aiQaItemService.updateById(entity);
            if (ok) {
                result.put("success", true);
                result.put("message", "更新成功");
                result.put("data", aiQaItemService.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_item 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 = aiQaItemService.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_item 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 = aiQaItemService.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_item batchDelete error", e);
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
