package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.TodoItem;
import com.rj.service.ITodoItemService;
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/todoItem")
@Tag(name = "待办事项管理", description = "待办事项相关接口")
public class TodoItemController {

    @Autowired
    private ITodoItemService todoItemService;

    /**
     * 新增待办事项
     */
    @PostMapping("/add")
    @Operation(summary = "新增待办事项", description = "添加新的待办事项")
    public ResponseEntity<Map<String, Object>> addTodoItem(
            @Parameter(description = "待办事项信息", required = true)
            @RequestBody TodoItem todoItem) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (todoItem.getId() == null || todoItem.getId().trim().isEmpty()) {
                todoItem.setId(UUID.randomUUID().toString());
            }
            // 如果待处理日期为空，则设置为当前时间加3天
            if (todoItem.getPendingDate() == null) {
                todoItem.setPendingDate(LocalDateTime.now().plusDays(3));
            }
            todoItem.setCreateTime(LocalDateTime.now());
            todoItem.setUpdateTime(LocalDateTime.now());
            boolean success = todoItemService.save(todoItem);
            if (success) {
                result.put("success", true);
                result.put("message", "待办事项添加成功");
                result.put("data", todoItem);
                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>> getTodoItemById(
            @Parameter(description = "待办事项ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            TodoItem todoItem = todoItemService.getById(id);
            if (todoItem != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", todoItem);
                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>> getTodoItemsByParentId(
            @Parameter(description = "父ID", required = true)
            @RequestParam String parentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<TodoItem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TodoItem::getParentId, parentId);
            queryWrapper.orderByDesc(TodoItem::getCreateTime);
            List<TodoItem> todoItems = todoItemService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", todoItems);
            result.put("count", todoItems.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>> getTodoItemList(
            @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 = "状态（模糊查询）")
            @RequestParam(required = false) String status,
            @Parameter(description = "待办事项简称（模糊查询）")
            @RequestParam(required = false) String todoTitle,
            @Parameter(description = "所属人姓名（模糊查询）")
            @RequestParam(required = false) String ownerName,
            @Parameter(description = "所属人电话（模糊查询）")
            @RequestParam(required = false) String ownerPhone,
            @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 updateStartTime,
            @Parameter(description = "修改结束时间", example = "2025-12-31 23:59:59")
            @RequestParam(required = false) String updateEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<TodoItem> page = new Page<>(current, size);
            LambdaQueryWrapper<TodoItem> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (parentId != null && !parentId.trim().isEmpty()) {
                queryWrapper.eq(TodoItem::getParentId, parentId);
            }
            if (status != null && !status.trim().isEmpty()) {
                queryWrapper.like(TodoItem::getStatus, status);
            }
            if (todoTitle != null && !todoTitle.trim().isEmpty()) {
                queryWrapper.like(TodoItem::getTodoTitle, todoTitle);
            }
            if (ownerName != null && !ownerName.trim().isEmpty()) {
                queryWrapper.like(TodoItem::getOwnerName, ownerName);
            }
            if (ownerPhone != null && !ownerPhone.trim().isEmpty()) {
                queryWrapper.like(TodoItem::getOwnerPhone, ownerPhone);
            }
            
            // 添加时间范围查询条件
            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(TodoItem::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(TodoItem::getCreateTime, endTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (updateStartTime != null && !updateStartTime.trim().isEmpty()) {
                try {
                    LocalDateTime startTime = LocalDateTime.parse(updateStartTime, formatter);
                    queryWrapper.ge(TodoItem::getUpdateTime, startTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "修改开始时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (updateEndTime != null && !updateEndTime.trim().isEmpty()) {
                try {
                    LocalDateTime endTime = LocalDateTime.parse(updateEndTime, formatter);
                    queryWrapper.le(TodoItem::getUpdateTime, endTime);
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "修改结束时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            
            // 按修改时间倒序排列
            queryWrapper.orderByDesc(TodoItem::getUpdateTime);
            
            Page<TodoItem> todoItemPage = todoItemService.page(page, queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", todoItemPage.getRecords());
            result.put("total", todoItemPage.getTotal());
            result.put("current", todoItemPage.getCurrent());
            result.put("size", todoItemPage.getSize());
            result.put("pages", todoItemPage.getPages());
            
            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>> updateTodoItem(
            @Parameter(description = "待办事项信息", required = true)
            @RequestBody TodoItem todoItem) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (todoItem.getId() == null || todoItem.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "待办事项ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            todoItem.setUpdateTime(LocalDateTime.now());
            boolean success = todoItemService.updateById(todoItem);
            
            if (success) {
                result.put("success", true);
                result.put("message", "待办事项信息更新成功");
                result.put("data", todoItem);
                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>> deleteTodoItem(
            @Parameter(description = "待办事项ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = todoItemService.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>> batchDeleteTodoItems(
            @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 = todoItemService.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);
        }
    }

    /**
     * 更新待办事项状态为已完成
     */
    @PostMapping("/updateTodoStatus")
    @Operation(summary = "更新待办事项状态为已完成", description = "根据ID将待办事项状态修改为已完成")
    public ResponseEntity<Map<String, Object>> updateTodoStatus(
            @Parameter(description = "包含id的请求体，格式：{\"id\": \"待办事项ID\"}", required = true)
            @RequestBody Map<String, String> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String id = request.get("id");
            if (id == null || id.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "待办事项ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            TodoItem todoItem = todoItemService.getById(id);
            if (todoItem == null) {
                result.put("success", false);
                result.put("message", "待办事项不存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            todoItem.setStatus("已完成");
            todoItem.setUpdateTime(LocalDateTime.now());
            boolean success = todoItemService.updateById(todoItem);
            
            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("/delayProcessTodo")
    @Operation(summary = "延期处理待办事项", description = "根据ID将待办事项的待处理日期延期3天")
    public ResponseEntity<Map<String, Object>> delayProcessTodo(
            @Parameter(description = "包含id的请求体，格式：{\"id\": \"待办事项ID\"}", required = true)
            @RequestBody Map<String, String> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String id = request.get("id");
            if (id == null || id.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "待办事项ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            TodoItem todoItem = todoItemService.getById(id);
            if (todoItem == null) {
                result.put("success", false);
                result.put("message", "待办事项不存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 计算延期3天后的日期
            LocalDateTime newPendingDate;
            if (todoItem.getPendingDate() != null) {
                // 如果已有待处理日期，则在原日期基础上延期3天
                newPendingDate = todoItem.getPendingDate().plusDays(3);
            } else {
                // 如果没有待处理日期，则设置为当前日期+3天
                newPendingDate = LocalDateTime.now().plusDays(3);
            }
            
            todoItem.setPendingDate(newPendingDate);
            todoItem.setUpdateTime(LocalDateTime.now());
            boolean success = todoItemService.updateById(todoItem);
            
            if (success) {
                result.put("success", true);
                result.put("message", "延期处理成功，待处理日期已更新为：" + newPendingDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                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);
        }
    }

    /**
     * 获取待办事项统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取待办事项统计信息", description = "获取待办事项总数等统计信息")
    public ResponseEntity<Map<String, Object>> getTodoItemStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = todoItemService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalTodoItems", totalCount);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}

