package cn.novalon.gym.manage.groupcourse.handler;

import cn.novalon.gym.manage.groupcourse.domain.CourseLabel;
import cn.novalon.gym.manage.groupcourse.service.ICourseLabelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Tag(name = "团课标签管理", description = "团课标签相关操作")
public class CourseLabelHandler {

    private final ICourseLabelService courseLabelService;

    public CourseLabelHandler(ICourseLabelService courseLabelService) {
        this.courseLabelService = courseLabelService;
    }

    @Operation(summary = "获取所有标签", description = "获取系统中所有标签列表")
    public Mono<ServerResponse> getAllLabels(ServerRequest request) {
        return ServerResponse.ok()
                .body(courseLabelService.findAll(), CourseLabel.class);
    }

    @Operation(summary = "根据ID获取标签", description = "根据ID获取标签详情")
    public Mono<ServerResponse> getLabelById(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        return courseLabelService.findById(id)
                .flatMap(label -> ServerResponse.ok().bodyValue(label))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    @Operation(summary = "搜索标签", description = "根据关键词搜索标签")
    public Mono<ServerResponse> searchLabels(ServerRequest request) {
        String keyword = request.queryParam("keyword").orElse("");
        return ServerResponse.ok()
                .body(courseLabelService.findByKeyword(keyword), CourseLabel.class);
    }

    @Operation(summary = "创建标签", description = "创建新的标签")
    public Mono<ServerResponse> createLabel(ServerRequest request) {
        return request.bodyToMono(CourseLabel.class)
                .flatMap(courseLabel -> {
                    if (courseLabel.getLabelName() == null || courseLabel.getLabelName().isEmpty()) {
                        Map<String, Object> error = new HashMap<>();
                        error.put("success", false);
                        error.put("message", "标签名称不能为空");
                        return ServerResponse.badRequest().bodyValue(error);
                    }
                    
                    if (courseLabel.getLabelName().length() > 50) {
                        Map<String, Object> error = new HashMap<>();
                        error.put("success", false);
                        error.put("message", "标签名称不能超过50个字符");
                        return ServerResponse.badRequest().bodyValue(error);
                    }
                    
                    if (courseLabel.getColor() == null || courseLabel.getColor().isEmpty()) {
                        courseLabel.setColor("#1890ff");
                    }
                    
                    return courseLabelService.create(courseLabel)
                            .flatMap(label -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "标签创建成功");
                                response.put("data", label);
                                return ServerResponse.ok().bodyValue(response);
                            })
                            .onErrorResume(error -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", false);
                                response.put("message", error.getMessage());
                                return ServerResponse.badRequest().bodyValue(response);
                            });
                });
    }

    @Operation(summary = "更新标签", description = "更新指定标签信息")
    public Mono<ServerResponse> updateLabel(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        
        return request.bodyToMono(CourseLabel.class)
                .flatMap(courseLabel -> {
                    if (courseLabel.getLabelName() != null && courseLabel.getLabelName().length() > 50) {
                        Map<String, Object> error = new HashMap<>();
                        error.put("success", false);
                        error.put("message", "标签名称不能超过50个字符");
                        return ServerResponse.badRequest().bodyValue(error);
                    }
                    
                    return courseLabelService.update(id, courseLabel)
                            .flatMap(label -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "标签更新成功");
                                response.put("data", label);
                                return ServerResponse.ok().bodyValue(response);
                            })
                            .onErrorResume(error -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", false);
                                response.put("message", error.getMessage());
                                return ServerResponse.badRequest().bodyValue(response);
                            });
                });
    }

    @Operation(summary = "删除标签", description = "删除指定标签（软删除）")
    public Mono<ServerResponse> deleteLabel(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        
        return courseLabelService.delete(id)
                .then(Mono.defer(() -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "标签删除成功");
                    return ServerResponse.ok().bodyValue(response);
                }))
                .onErrorResume(error -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", error.getMessage());
                    return ServerResponse.badRequest().bodyValue(response);
                });
    }

    @Operation(summary = "获取类型的标签", description = "获取指定团课类型的所有标签")
    public Mono<ServerResponse> getLabelsByTypeId(ServerRequest request) {
        Long typeId = Long.valueOf(request.pathVariable("typeId"));
        return courseLabelService.findByTypeId(typeId)
                .collectList()
                .flatMap(list -> ServerResponse.ok().bodyValue(list));
    }

    @Operation(summary = "为类型添加标签", description = "为指定团课类型添加标签")
    public Mono<ServerResponse> addLabelsToType(ServerRequest request) {
        Long typeId = Long.valueOf(request.pathVariable("typeId"));
        
        return request.bodyToMono(Map.class)
                .flatMap(body -> {
                    @SuppressWarnings("unchecked")
                    List<Integer> labelIdsInt = (List<Integer>) body.get("labelIds");
                    
                    if (labelIdsInt == null || labelIdsInt.isEmpty()) {
                        Map<String, Object> error = new HashMap<>();
                        error.put("success", false);
                        error.put("message", "labelIds不能为空");
                        return ServerResponse.badRequest().bodyValue(error);
                    }
                    
                    List<Long> labelIds = labelIdsInt.stream()
                            .map(Integer::longValue)
                            .collect(java.util.stream.Collectors.toList());
                    
                    return courseLabelService.addLabelsToType(typeId, labelIds)
                            .then(Mono.defer(() -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "标签添加成功");
                                return ServerResponse.ok().bodyValue(response);
                            }))
                            .onErrorResume(error -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", false);
                                response.put("message", error.getMessage());
                                return ServerResponse.badRequest().bodyValue(response);
                            });
                });
    }

    @Operation(summary = "从类型移除标签", description = "从指定团课类型移除标签")
    public Mono<ServerResponse> removeLabelFromType(ServerRequest request) {
        Long typeId = Long.valueOf(request.pathVariable("typeId"));
        Long labelId = Long.valueOf(request.pathVariable("labelId"));
        
        return courseLabelService.removeLabelFromType(typeId, labelId)
                .then(Mono.defer(() -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "标签移除成功");
                    return ServerResponse.ok().bodyValue(response);
                }))
                .onErrorResume(error -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", error.getMessage());
                    return ServerResponse.badRequest().bodyValue(response);
                });
    }

    @Operation(summary = "清空类型标签", description = "清空指定团课类型的所有标签")
    public Mono<ServerResponse> clearLabelsFromType(ServerRequest request) {
        Long typeId = Long.valueOf(request.pathVariable("typeId"));
        
        return courseLabelService.clearLabelsFromType(typeId)
                .then(Mono.defer(() -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "标签清空成功");
                    return ServerResponse.ok().bodyValue(response);
                }))
                .onErrorResume(error -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", error.getMessage());
                    return ServerResponse.badRequest().bodyValue(response);
                });
    }
}