package com.lesingle.edu.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.annotation.RequireRole;
import com.lesingle.edu.common.enums.CourseStatus;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.dto.request.CourseCollectionPageQueryRequest;
import com.lesingle.edu.dto.request.CourseCollectionRejectRequest;
import com.lesingle.edu.dto.response.CourseCollectionResponse;
import com.lesingle.edu.entity.CourseCollection;
import com.lesingle.edu.service.CourseCollectionService;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程套餐控制器（超管端）- 三层架构规范
 */
@RestController
@RequestMapping("/api/v1/admin/collections")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "超管端 - 课程套餐管理")
public class AdminCourseCollectionController {

    private final CourseCollectionService collectionService;

    @GetMapping
    @Operation(summary = "分页查询课程套餐")
    public Result<PageResult<CourseCollectionResponse>> page(CourseCollectionPageQueryRequest request) {
        Page<CourseCollectionResponse> page = collectionService.pageCollections(
                request.getPageNum(),
                request.getPageSize(),
                request.getStatus(),
                request.getGradeLevels()
        );
        return Result.success(PageResult.of(page));
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询课程套餐详情")
    public Result<CourseCollectionResponse> findOne(@PathVariable Long id) {
        CourseCollectionResponse response = collectionService.getCollectionDetail(id);
        return Result.success(response);
    }

    @PostMapping
    @Operation(summary = "创建课程套餐")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.CREATE, description = "创建课程套餐")
    @RequireRole(UserRole.ADMIN)
    public Result<CourseCollectionResponse> create(@Valid @RequestBody CreateCollectionRequest request) {
        CourseCollectionResponse response = collectionService.createCollection(
                request.getName(),
                request.getDescription(),
                request.getPrice(),
                request.getDiscountPrice(),
                request.getDiscountType(),
                request.getGradeLevels()
        );
        return Result.success(response);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新课程套餐")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "更新课程套餐")
    @RequireRole(UserRole.ADMIN)
    public Result<CourseCollectionResponse> update(
            @PathVariable Long id,
            @RequestBody CreateCollectionRequest request) {
        CourseCollectionResponse response = collectionService.updateCollection(
                id,
                request.getName(),
                request.getDescription(),
                request.getPrice(),
                request.getDiscountPrice(),
                request.getDiscountType(),
                request.getGradeLevels()
        );
        return Result.success(response);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除课程套餐")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.DELETE, description = "删除课程套餐")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> delete(@PathVariable Long id) {
        collectionService.deleteCollection(id);
        return Result.success();
    }

    @PutMapping("/{id}/packages")
    @Operation(summary = "设置套餐课程包")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "设置套餐课程包")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> setPackages(
            @PathVariable Long id,
            @RequestBody List<Long> packageIds) {
        collectionService.setCollectionPackages(id, packageIds);
        return Result.success();
    }

    @PostMapping("/{id}/publish")
    @Operation(summary = "发布套餐")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "发布套餐")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> publish(@PathVariable Long id) {
        collectionService.publishCollection(id);
        return Result.success();
    }

    @PostMapping("/{id}/archive")
    @Operation(summary = "下架套餐")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "下架套餐")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> archive(@PathVariable Long id) {
        collectionService.archiveCollection(id);
        return Result.success();
    }

    @PostMapping("/{id}/republish")
    @Operation(summary = "重新发布套餐")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "重新发布套餐")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> republish(@PathVariable Long id) {
        collectionService.republishCollection(id);
        return Result.success();
    }

    @PostMapping("/{id}/withdraw")
    @Operation(summary = "撤销审核")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "撤销审核")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> withdraw(@PathVariable Long id) {
        collectionService.withdrawCollection(id);
        return Result.success();
    }

    @PostMapping("/{id}/submit")
    @Operation(summary = "提交审核")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "提交审核")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> submit(@PathVariable Long id) {
        collectionService.submitCollection(id);
        return Result.success();
    }

    @PostMapping("/{id}/reject")
    @Operation(summary = "审核驳回")
    @Log(module = LogModule.COURSE_COLLECTION, type = LogOperationType.UPDATE, description = "审核驳回")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> reject(@PathVariable Long id, @Valid @RequestBody CourseCollectionRejectRequest request) {
        collectionService.rejectCollection(id, request.getComment());
        return Result.success();
    }

    @GetMapping("/all")
    @Operation(summary = "获取所有已发布的课程套餐")
    public Result<List<CourseCollectionResponse>> getAllPublishedCollections() {
        log.info("获取所有已发布的课程套餐");
        List<CourseCollection> collections = this.collectionService.list(
                new LambdaQueryWrapper<CourseCollection>()
                        .eq(CourseCollection::getStatus, CourseStatus.PUBLISHED.getCode())
                        .orderByDesc(CourseCollection::getPackageCount));
        List<CourseCollectionResponse> responseList = collections.stream()
                .map(collection -> collectionService.getCollectionDetail(collection.getId()))
                .collect(Collectors.toList());
        return Result.success(responseList);
    }

    /**
     * 授权课程套餐请求
     */
    @Data
    public static class GrantCollectionRequest {
        @Schema(description = "租户ID")
        private Long tenantId;

        @Schema(description = "结束日期（ISO格式，如：2024-12-31）")
        private String endDate;

        @Schema(description = "支付价格（分）")
        private Long pricePaid;
    }

    /**
     * 创建课程套餐请求
     */
    @Data
    public static class CreateCollectionRequest {
        @Schema(description = "名称")
        private String name;

        @Schema(description = "描述")
        private String description;

        @Schema(description = "价格（分）")
        private Long price;

        @Schema(description = "折扣价格（分）")
        private Long discountPrice;

        @Schema(description = "折扣类型")
        private String discountType;

        @Schema(description = "年级标签")
        private String[] gradeLevels;
    }
}
