package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.common.AudioManagementConstants;
import com.rj.entity.KnowledgeBase;
import com.rj.entity.TrainingItem;
import com.rj.entity.TrainingMain;
import com.rj.service.IKnowledgeBaseService;
import com.rj.service.ITrainingItemService;
import com.rj.service.ITrainingMainService;
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;

/**
 * <p>
 * 陪练子表 前端控制器
 * </p>
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@RestController
@RequestMapping("/api/trainingItem")
@Tag(name = "陪练子表管理", description = "陪练子表相关接口")
public class TrainingItemController {

    @Autowired
    private ITrainingItemService trainingItemService;

    @Autowired
    private IKnowledgeBaseService knowledgeBaseService;
    @Autowired
    private ITrainingMainService trainingMainService;


    /**
     * 新增陪练子表记录
     */
    @PostMapping("/add")
    @Operation(summary = "新增陪练子表记录", description = "添加新的陪练子表记录")
    public ResponseEntity<Map<String, Object>> addTrainingItem(
            @Parameter(description = "陪练子表信息", required = true)
            @RequestBody TrainingItem trainingItem) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (trainingItem.getId() == null || trainingItem.getId().trim().isEmpty()) {
                trainingItem.setId(UUID.randomUUID().toString());
            }
            trainingItem.setCreateTime(LocalDateTime.now());
            boolean success = trainingItemService.save(trainingItem);
            if (success) {
                result.put("success", true);
                result.put("message", "陪练子表记录添加成功");
                result.put("data", trainingItem);
                return ResponseEntity.ok(result);
            } else {
                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);
        }
    }

    /**
     * 根据ID查询陪练子表记录
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询陪练子表记录", description = "根据陪练子表ID获取详细信息")
    public ResponseEntity<Map<String, Object>> getTrainingItemById(
            @Parameter(description = "陪练子表ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            TrainingItem trainingItem = trainingItemService.getById(id);
            if (trainingItem != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", trainingItem);
                return ResponseEntity.ok(result);
            } else {
                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);
        }
    }

    /**
     * 根据父ID查询陪练子表列表
     */
    @GetMapping("/getByParentId")
    @Operation(summary = "根据父ID查询陪练子表", description = "根据父ID查询子陪练子表列表")
    public ResponseEntity<Map<String, Object>> getTrainingItemsByParentId(
            @Parameter(description = "父ID", required = true)
            @RequestParam String parentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<TrainingItem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TrainingItem::getParentId, parentId);
            queryWrapper.orderByDesc(TrainingItem::getCreateTime);
            List<TrainingItem> trainingItems = trainingItemService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", trainingItems);
            result.put("count", trainingItems.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 分页查询陪练子表列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询陪练子表列表", description = "分页查询陪练子表信息列表")
    public ResponseEntity<Map<String, Object>> getTrainingItemList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "父ID（精确查询）")
            @RequestParam(required = false) String parentId,
            @Parameter(description = "租户ID（精确查询）")
            @RequestParam(required = false) String tenantId,
            @Parameter(description = "题目（模糊查询）")
            @RequestParam(required = false) String question,
            @Parameter(description = "题目答案（模糊查询）")
            @RequestParam(required = false) String answer,
            @Parameter(description = "创建开始时间", example = "2025-01-01 00:00:00")
            @RequestParam(required = false) String createStartTime,
            @Parameter(description = "创建结束时间", example = "2025-12-31 23:59:59")
            @RequestParam(required = false) String createEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<TrainingItem> page = new Page<>(current, size);
            LambdaQueryWrapper<TrainingItem> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (parentId != null && !parentId.trim().isEmpty()) {
                queryWrapper.eq(TrainingItem::getParentId, parentId);
            }
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                queryWrapper.eq(TrainingItem::getTenantId, tenantId);
            }
            if (question != null && !question.trim().isEmpty()) {
                queryWrapper.like(TrainingItem::getQuestion, question);
            }
            if (answer != null && !answer.trim().isEmpty()) {
                queryWrapper.like(TrainingItem::getAnswer, answer);
            }
            
            // 添加时间范围查询条件
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createStartTime != null && !createStartTime.trim().isEmpty()) {
                try {
                    LocalDateTime startTime = LocalDateTime.parse(createStartTime, formatter);
                    queryWrapper.ge(TrainingItem::getCreateTime, startTime);
                } 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 {
                    LocalDateTime endTime = LocalDateTime.parse(createEndTime, formatter);
                    queryWrapper.le(TrainingItem::getCreateTime, endTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(TrainingItem::getCreateTime);
            
            Page<TrainingItem> trainingItemPage = trainingItemService.page(page, queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", trainingItemPage.getRecords());
            result.put("total", trainingItemPage.getTotal());
            result.put("current", trainingItemPage.getCurrent());
            result.put("size", trainingItemPage.getSize());
            result.put("pages", trainingItemPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    /**
     * 按条件不分页查询陪练子表列表
     */
    @PostMapping("/listAll")
    @Operation(summary = "按条件不分页查询陪练子表列表", description = "按条件查询所有陪练子表信息列表（不分页）")
    public ResponseEntity<Map<String, Object>> getAllTrainingItemList(
            @Parameter(description = "父ID（精确查询）")
            @RequestParam(required = false) String parentId,
            @Parameter(description = "租户ID（精确查询）")
            @RequestParam(required = false) String tenantId,
            @Parameter(description = "题目（模糊查询）")
            @RequestParam(required = false) String question,
            @Parameter(description = "题目答案（模糊查询）")
            @RequestParam(required = false) String answer,
            @Parameter(description = "创建开始时间", example = "2025-01-01 00:00:00")
            @RequestParam(required = false) String createStartTime,
            @Parameter(description = "创建结束时间", example = "2025-12-31 23:59:59")
            @RequestParam(required = false) String createEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<TrainingItem> queryTrainingItemWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (parentId != null && !parentId.trim().isEmpty()) {
                queryTrainingItemWrapper.eq(TrainingItem::getParentId, parentId);
            }
            if (question != null && !question.trim().isEmpty()) {
                queryTrainingItemWrapper.like(TrainingItem::getQuestion, question);
            }
            if (answer != null && !answer.trim().isEmpty()) {
                queryTrainingItemWrapper.like(TrainingItem::getAnswer, answer);
            }
            
            // 添加时间范围查询条件
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createStartTime != null && !createStartTime.trim().isEmpty()) {
                try {
                    LocalDateTime startTime = LocalDateTime.parse(createStartTime, formatter);
                    queryTrainingItemWrapper.ge(TrainingItem::getCreateTime, startTime);
                } 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 {
                    LocalDateTime endTime = LocalDateTime.parse(createEndTime, formatter);
                    queryTrainingItemWrapper.le(TrainingItem::getCreateTime, endTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            
            // 按创建时间倒序排列
            queryTrainingItemWrapper.orderByDesc(TrainingItem::getCreateTime);

            List<TrainingItem> trainingItemList = trainingItemService.list(queryTrainingItemWrapper);

            if (trainingItemList.size()==0){
                LambdaQueryWrapper<TrainingMain> queryMainWrapper = new LambdaQueryWrapper<>();
                queryMainWrapper.eq(TrainingMain::getId, parentId);
                TrainingMain trainingMain = trainingMainService.getOne(queryMainWrapper);

                LambdaQueryWrapper<KnowledgeBase> queryScenarioWrapper = new LambdaQueryWrapper<>();
                queryScenarioWrapper.eq(KnowledgeBase::getId, trainingMain.getScenarioId());
                KnowledgeBase one1 = knowledgeBaseService.getOne(queryScenarioWrapper);
                log.info(one1.getRemark());
                String[] split = one1.getRemark().split(",");
                for (String s : split) {
                    log.info(s);
                    TrainingItem item = new TrainingItem();
                    item.setQuestion(s);
                    item.setParentId(trainingMain.getId());
                    item.setTenantId(trainingMain.getTenantId());
                    item.setStatus("init");
                    trainingItemService.save(item);
                }
            }
            // 每次只查询一条记录
            queryTrainingItemWrapper.last("LIMIT 1");
            trainingItemList = trainingItemService.list(queryTrainingItemWrapper);
             
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", trainingItemList);
            result.put("count", trainingItemList.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新陪练子表信息
     */
    @PostMapping("/traningNext")
    @Operation(summary = "更新陪练子表信息", description = "更新陪练子表详细信息")
    public ResponseEntity<Map<String, Object>> updateTrainingItem(
            @Parameter(description = "陪练子表信息", required = true)
            @RequestBody TrainingItem trainingItem) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (trainingItem.getId() == null || trainingItem.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "陪练子表ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            TrainingItem item = new TrainingItem();
            item.setId(trainingItem.getId());
            item.setAnswer(trainingItem.getAnswer());
            item.setStatus("finished");
            item.setAnswerTime( LocalDateTime.now());
            boolean success = trainingItemService.updateById(item);


            LambdaQueryWrapper<TrainingItem> queryTrainingItemWrapper = new LambdaQueryWrapper<>();
            queryTrainingItemWrapper.eq(TrainingItem::getParentId, trainingItem.getParentId());
            queryTrainingItemWrapper.eq(TrainingItem::getStatus, "init");

            // 每次只查询一条记录
            queryTrainingItemWrapper.last("LIMIT 1");
            List<TrainingItem>  trainingItemList = trainingItemService.list(queryTrainingItemWrapper);

            result.put("data", trainingItemList);
            if (success) {
                result.put("success", true);
                result.put("message", "成功");
                return ResponseEntity.ok(result);
            } else {
                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);
        }
    }

    /**
     * 更新陪练子表信息
     */
    @PostMapping("/traningFinish")
    @Operation(summary = "更新陪练zhu表信息", description = "更新陪练主表详细信息")
    public ResponseEntity<Map<String, Object>> traningFinish(
            @Parameter(description = "陪练主表信息", required = true)
            @RequestBody TrainingItem trainingItem) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (trainingItem.getParentId() == null || trainingItem.getParentId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "父ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            TrainingMain trainingMain = new TrainingMain();
            trainingMain.setId(trainingItem.getParentId());
            trainingMain.setFinishStatus(AudioManagementConstants.SERVICE_STATUS_SERVICE_FINISH);
            trainingMain.setEndTime( LocalDateTime.now());
            boolean success = trainingMainService.updateById(trainingMain);

            if (success) {
                result.put("success", true);
                result.put("message", "成功");
                return ResponseEntity.ok(result);
            } else {
                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);
        }
    }



    /**
     * 根据ID删除陪练子表记录
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除陪练子表记录", description = "根据陪练子表ID删除陪练子表信息")
    public ResponseEntity<Map<String, Object>> deleteTrainingItem(
            @Parameter(description = "陪练子表ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = trainingItemService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "陪练子表记录删除成功");
                return ResponseEntity.ok(result);
            } else {
                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>> batchDeleteTrainingItems(
            @Parameter(description = "陪练子表ID列表", 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 = trainingItemService.removeByIds(ids);
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共删除 " + ids.size() + " 条记录");
                return ResponseEntity.ok(result);
            } else {
                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);
        }
    }
}

