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.TrainingMain;
import com.rj.service.IKnowledgeBaseService;
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 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
 */
@RestController
@RequestMapping("/api/trainingMain")
@Tag(name = "陪练主表管理", description = "陪练主表相关接口")
public class TrainingMainController {

    @Autowired
    private ITrainingMainService trainingMainService;

    /**
     * 新增陪练主表记录
     */
    @PostMapping("/add")
    @Operation(summary = "新增陪练主表记录", description = "添加新的陪练主表记录")
    public ResponseEntity<Map<String, Object>> addTrainingMain(
            @Parameter(description = "陪练主表信息", required = true)
            @RequestBody TrainingMain trainingMain) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (trainingMain.getId() == null || trainingMain.getId().trim().isEmpty()) {
                trainingMain.setId(UUID.randomUUID().toString());
            }
            trainingMain.setFinishStatus(AudioManagementConstants.SERVICE_STATUS_IN_SERVICE);
//            trainingMain.setCreateTime(LocalDateTime.now());
            boolean success = trainingMainService.save(trainingMain);
            if (success) {
                result.put("success", true);
                result.put("message", "陪练主表记录添加成功");
                result.put("data", trainingMain);
                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>> getTrainingMainById(
            @Parameter(description = "陪练主表ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            TrainingMain trainingMain = trainingMainService.getById(id);
            if (trainingMain != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", trainingMain);
                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);
        }
    }

    /**
     * 分页查询陪练主表列表
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询陪练主表列表", description = "分页查询陪练主表信息列表")
    public ResponseEntity<Map<String, Object>> getTrainingMainList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String tenantId,
            @Parameter(description = "陪练标题（模糊查询）")
            @RequestParam(required = false) String title,
            @Parameter(description = "陪练的场景（模糊查询）")
            @RequestParam(required = false) String finishStatus,
            @Parameter(description = "参与人姓名（模糊查询）")
            @RequestParam(required = false) String participantName,
            @Parameter(description = "参与人电话（模糊查询）")
            @RequestParam(required = false) String participantPhone ) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<TrainingMain> page = new Page<>(current, size);
            LambdaQueryWrapper<TrainingMain> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (title != null && !title.trim().isEmpty()) {
                queryWrapper.like(TrainingMain::getTitle, title);
            }
            if (finishStatus != null && !finishStatus.trim().isEmpty()) {
                queryWrapper.eq(TrainingMain::getFinishStatus, finishStatus);
            }
            if (participantName != null && !participantName.trim().isEmpty()) {
                queryWrapper.like(TrainingMain::getParticipantName, participantName);
            }
            if (participantPhone != null && !participantPhone.trim().isEmpty()) {
                queryWrapper.like(TrainingMain::getParticipantPhone, participantPhone);
            }

            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(TrainingMain::getCreateTime);
            
            Page<TrainingMain> trainingMainPage = trainingMainService.page(page, queryWrapper);

            // 隐藏场景内容，不返回给前端
            trainingMainPage.getRecords().forEach(item -> item.setScenario(null));

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

    /**
     * 按条件不分页查询陪练主表列表
     */
    @GetMapping("/listAll")
    @Operation(summary = "按条件不分页查询陪练主表列表", description = "按条件查询所有陪练主表信息列表（不分页）")
    public ResponseEntity<Map<String, Object>> getAllTrainingMainList(
            @Parameter(description = "租户ID（精确查询）")
            @RequestParam(required = false) String tenantId,
            @Parameter(description = "陪练标题（模糊查询）")
            @RequestParam(required = false) String title,
            @Parameter(description = "陪练的场景（模糊查询）")
            @RequestParam(required = false) String scenario,
            @Parameter(description = "参与人姓名（模糊查询）")
            @RequestParam(required = false) String participantName,
            @Parameter(description = "参与人电话（模糊查询）")
            @RequestParam(required = false) String participantPhone,
            @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,
            @Parameter(description = "结束开始时间", example = "2025-01-01 00:00:00")
            @RequestParam(required = false) String endStartTime,
            @Parameter(description = "结束结束时间", example = "2025-12-31 23:59:59")
            @RequestParam(required = false) String endEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<TrainingMain> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                queryWrapper.eq(TrainingMain::getTenantId, tenantId);
            }
            if (title != null && !title.trim().isEmpty()) {
                queryWrapper.like(TrainingMain::getTitle, title);
            }
            if (scenario != null && !scenario.trim().isEmpty()) {
                queryWrapper.like(TrainingMain::getScenario, scenario);
            }
            if (participantName != null && !participantName.trim().isEmpty()) {
                queryWrapper.like(TrainingMain::getParticipantName, participantName);
            }
            if (participantPhone != null && !participantPhone.trim().isEmpty()) {
                queryWrapper.like(TrainingMain::getParticipantPhone, participantPhone);
            }
            
            // 添加时间范围查询条件
            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(TrainingMain::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(TrainingMain::getCreateTime, endTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (endStartTime != null && !endStartTime.trim().isEmpty()) {
                try {
                    LocalDateTime startTime = LocalDateTime.parse(endStartTime, formatter);
                    queryWrapper.ge(TrainingMain::getEndTime, startTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "结束开始时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (endEndTime != null && !endEndTime.trim().isEmpty()) {
                try {
                    LocalDateTime endTime = LocalDateTime.parse(endEndTime, formatter);
                    queryWrapper.le(TrainingMain::getEndTime, endTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "结束结束时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(TrainingMain::getCreateTime);
            
            List<TrainingMain> trainingMainList = trainingMainService.list(queryWrapper);

            // 隐藏场景内容，不返回给前端
            trainingMainList.forEach(item -> item.setScenario(null));

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", trainingMainList);
            result.put("count", trainingMainList.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新陪练主表信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新陪练主表信息", description = "更新陪练主表详细信息")
    public ResponseEntity<Map<String, Object>> updateTrainingMain(
            @Parameter(description = "陪练主表信息", required = true)
            @RequestBody TrainingMain trainingMain) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (trainingMain.getId() == null || trainingMain.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "陪练主表ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = trainingMainService.updateById(trainingMain);
            
            if (success) {
                result.put("success", true);
                result.put("message", "陪练主表信息更新成功");
                result.put("data", trainingMain);
                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>> deleteTrainingMain(
            @Parameter(description = "陪练主表ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = trainingMainService.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>> batchDeleteTrainingMains(
            @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 = trainingMainService.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);
        }
    }
}

