package com.rj.controller.biz;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.rj.controller.biz.dto.ConsultingScenarioRequest;
import com.rj.entity.bz.ConsultingScenario;
import com.rj.service.biz.IConsultingScenarioService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
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.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 咨询场景表 前端控制器
 * </p>
 *
 * @author lingma
 * @since 2025-09-02
 */
@RestController
@RequestMapping("/api/consultingScenario")
@Tag(name = "咨询的问题分类", description = "咨询场景相关接口")
@Slf4j
public class ConsultingScenarioController {

    @Autowired
    private IConsultingScenarioService consultingScenarioService;

    /**
     * 新增咨询场景
     */
    @PostMapping("/add")
    @Operation(summary = "新增咨询场景", description = "添加新的咨询场景信息")
    public ResponseEntity<Map<String, Object>> addConsultingScenario(
            @Parameter(description = "咨询场景信息", required = true)
            @RequestBody ConsultingScenario consultingScenario) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 设置UUID主键
            if (consultingScenario.getId() == null || consultingScenario.getId().isEmpty()) {
                consultingScenario.setId(UUID.randomUUID().toString());
            }
            consultingScenario.setCreatedAt(LocalDateTime.now());
            consultingScenario.setUpdatedAt(LocalDateTime.now());

            boolean isSaved = consultingScenarioService.save(consultingScenario);
            if (isSaved) {
                result.put("code", 200);
                result.put("message", "保存成功");
                result.put("data", consultingScenario);
            } else {
                result.put("code", 500);
                result.put("message", "保存失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "保存异常: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }



    /**
     * 处理咨询场景请求
     *
     * @return 处理结果
     */
    @PostMapping("/process")
    @Operation(summary = "处理咨询场景", description = "接收咨询场景相关参数并进行处理")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "处理成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Map<String, Object>> processConsultingScenario(  @RequestBody ConsultingScenarioRequest request) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 调用服务层处理逻辑
            Object processingResult = consultingScenarioService.processConsultingScenario(request);

            result.put("success", true);
            result.put("data", processingResult);
            result.put("message", "处理成功");

        } catch (Exception e) {
            result.put("success", false);
            result.put("data", null);
            result.put("message", "处理失败: " + e.getMessage());
            log.error("处理咨询场景时发生错误", e);
        }

        return ResponseEntity.ok(result);
    }
    /**
     * 修改咨询场景
     */
    @PostMapping("/update")
    @Operation(summary = "修改咨询场景", description = "修改咨询场景信息")
    public ResponseEntity<Map<String, Object>> updateConsultingScenario(
            @Parameter(description = "咨询场景信息", required = true)
            @RequestBody ConsultingScenario consultingScenario) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (consultingScenario.getId() == null || consultingScenario.getId().isEmpty()) {
                result.put("code", 400);
                result.put("message", "缺少主键ID");
                return ResponseEntity.badRequest().body(result);
            }

            consultingScenario.setUpdatedAt(LocalDateTime.now());
            boolean isUpdated = consultingScenarioService.updateById(consultingScenario);
            if (isUpdated) {
                result.put("code", 200);
                result.put("message", "更新成功");
                result.put("data", consultingScenario);
            } else {
                result.put("code", 500);
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新异常: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 删除咨询场景
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除咨询场景", description = "根据ID删除咨询场景信息")
    public ResponseEntity<Map<String, Object>> deleteConsultingScenario(
            @Parameter(description = "咨询场景ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean isRemoved = consultingScenarioService.removeById(id);
            if (isRemoved) {
                result.put("code", 200);
                result.put("message", "删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除异常: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 根据ID查询咨询场景
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "查询咨询场景", description = "根据ID查询咨询场景信息")
    public ResponseEntity<Map<String, Object>> getConsultingScenarioById(
            @Parameter(description = "咨询场景ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            ConsultingScenario consultingScenario = consultingScenarioService.getById(id);
            if (consultingScenario != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", consultingScenario);
            } else {
                result.put("code", 404);
                result.put("message", "未找到相关数据");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询异常: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 分页查询咨询场景列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询咨询场景", description = "分页查询咨询场景列表")
    public ResponseEntity<Map<String, Object>> listConsultingScenarios(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "主分类")
            @RequestParam(required = false) String mainCategory,
            @Parameter(description = "子分类")
            @RequestParam(required = false) String subCategory) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<ConsultingScenario> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<ConsultingScenario> queryWrapper = new LambdaQueryWrapper<>();

            if (mainCategory != null && !mainCategory.isEmpty()) {
                queryWrapper.like(ConsultingScenario::getMainCategory, mainCategory);
            }
            if (subCategory != null && !subCategory.isEmpty()) {
                queryWrapper.like(ConsultingScenario::getSubCategory, subCategory);
            }

            queryWrapper.orderByDesc(ConsultingScenario::getCreatedAt);
            Page<ConsultingScenario> pageResult = consultingScenarioService.page(page, queryWrapper);


            result.put("data", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            result.put("pages", pageResult.getPages());
            result.put("success", true);
            result.put("message", "查询成功");
            return ResponseEntity.ok(result);


        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询异常: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
}
