package com.seer.teach.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.seer.teach.admin.convert.AdminModificationLogConvert;
import com.seer.teach.admin.request.AddKnowledgePointUnitMappingReq;
import com.seer.teach.admin.request.AdminModificationLogPageReq;
import com.seer.teach.admin.request.KnowledgePointCheckReq;
import com.seer.teach.admin.request.KnowledgePointSimilarityCheckReq;
import com.seer.teach.admin.request.KnowledgePointSplitReq;
import com.seer.teach.admin.request.MergeKnowledgePointsReq;
import com.seer.teach.admin.request.KnowledgePointsPageQueryReq;
import com.seer.teach.admin.request.KnowledgePointsReq;
import com.seer.teach.admin.request.CheckAndScoreReq;
import com.seer.teach.admin.request.BatchCheckReq;
import com.seer.teach.admin.request.BatchSaveSplitKnowledgePointsReq;
import com.seer.teach.admin.response.AdminModificationLogResp;
import com.seer.teach.admin.response.KnowledgePointCheckResp;
import com.seer.teach.admin.response.KnowledgePointSimilarityCheckResp;
import com.seer.teach.admin.response.KnowledgePointSplitResp;
import com.seer.teach.admin.response.KnowledgePointsResp;
import com.seer.teach.admin.service.AdminKnowledgePointsService;
import com.seer.teach.admin.service.AdminModificationLogService;
import com.seer.teach.admin.service.KnowledgePointCheckService;
import com.seer.teach.admin.service.KnowledgePointSimilarityService;
import com.seer.teach.admin.service.KnowledgePointSplitService;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.teacher.module.entity.ModificationLogEntity;
import com.seer.teach.teacher.service.UnitKnowMappingService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * 知识点管理控制器
 * </p>
 *
 * @author ZS
 * @since 2025-10-24
 */
@RestController
@RequestMapping("/teacher/knowledge-point")
@RequiredArgsConstructor
@Tag(name = "管理端 - 知识点管理")
@Validated
public class AdminKnowledgePointController {

    private final AdminKnowledgePointsService adminKnowledgePointsService;
    private final KnowledgePointSplitService knowledgePointSplitService;
    private final KnowledgePointCheckService knowledgePointCheckService;
    private final KnowledgePointSimilarityService knowledgePointSimilarityService;
    private final UnitKnowMappingService unitKnowMappingService;
    private final AdminModificationLogService adminModificationLogService;

    @PostMapping("/page-list")
    @Operation(summary = "分页查询知识点列表")
    @SaCheckPermission("teacher:admin:knowledge-points:list")
    public ResultBean<PageListBean<KnowledgePointsResp>> pageKnowledgePoints(@RequestBody @Validated KnowledgePointsPageQueryReq req) {
        IPage<KnowledgePointsResp> page = adminKnowledgePointsService.pageKnowledgePoints(req);
        return ResultBean.success(new PageListBean<>(page));
    }

    @PostMapping("/unit/{unitId}/list")
    @Operation(summary = "查询指定单元中的知识点列表")
    @SaCheckPermission("teacher:admin:knowledge-points:list")
    public ResultBean<List<KnowledgePointsResp>> getKnowledgePointsByUnitId(@Parameter(description = "单元id") @PathVariable("unitId")  Integer unitId,
                                                                            @RequestBody KnowledgePointsPageQueryReq KnowledgePointQueryReq) {
        List<KnowledgePointsResp> data = adminKnowledgePointsService.getKnowledgePointsByUnitId(unitId,KnowledgePointQueryReq);
        return ResultBean.success(data);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取知识点详情")
    @SaCheckPermission("teacher:admin:knowledge-points:detail")
    public ResultBean<KnowledgePointsResp> getKnowledgePointById(@Parameter(description = "知识点ID") @PathVariable @NotNull(message = "知识点ID不能为空") Integer id) {
        KnowledgePointsResp knowledgePoint = adminKnowledgePointsService.getKnowledgePointById(id);
        return ResultBean.success(knowledgePoint);
    }

    @GetMapping("/unit/{unitId}/{knowId}")
    @Operation(summary = "根据ID获取知识点详情")
    @SaCheckPermission("teacher:admin:knowledge-points:detail")
    public ResultBean<KnowledgePointsResp> getKnowledgePointByUnitIdAndKnowId(@Parameter(description = "单元ID") @PathVariable("unitId")  Integer unitId,
            @Parameter(description = "知识点ID") @PathVariable("knowId") Integer knowId) {
        KnowledgePointsResp knowledgePoint = adminKnowledgePointsService.getKnowledgePointByUnitIdAndKnowId(unitId,knowId);
        return ResultBean.success(knowledgePoint);
    }

    @PostMapping
    @Operation(summary = "添加知识点")
    @SaCheckPermission("teacher:admin:knowledge-points:save")
    public ResultBean<Boolean> addKnowledgePoint(@Parameter(description = "知识点信息") @Valid @RequestBody KnowledgePointsReq req) {
        boolean result = adminKnowledgePointsService.addKnowledgePoint(req);
        return ResultBean.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新知识点信息")
    @SaCheckPermission("teacher:admin:knowledge-points:update")
    public ResultBean<Boolean> updateKnowledgePoint(@Parameter(description = "知识点ID") @PathVariable @NotNull(message = "知识点ID不能为空") Integer id,
                                                    @Parameter(description = "知识点信息") @Valid @RequestBody KnowledgePointsReq req) {
        boolean result = adminKnowledgePointsService.updateKnowledgePoint(id, req);
        return ResultBean.success(result);
    }

    /**
     * 更新知识点顺序
     *
     * @param knowId 知识点ID
     * @param unitId 单元id
     * @param order  排序
     * @return 更新结果
     */
    @PutMapping("/{unitId}/{knowId}/order")
    public ResultBean<Boolean> updateKnowledgePointOrder(
            @Parameter(description = "知识点ID") @PathVariable("unitId") Integer unitId,
            @Parameter(description = "单元id") @PathVariable("knowId")  Integer knowId,
            @RequestParam Integer order) {
        return ResultBean.success(unitKnowMappingService.updateKnowledgePointOrder(knowId, unitId, order));
    }

    /**
     * 更新知识点检查状态和评分
     *
     * @param id  知识点ID
     * @param req 检查状态和评分信息
     * @return 更新结果
     */
    @PutMapping("/{id}/check-and-score")
    @Operation(summary = "更新知识点检查状态和评分")
    @SaCheckPermission("teacher:admin:knowledge-points:check-and-score")
    public ResultBean<Boolean> updateKnowledgePointCheckAndScore(@Parameter(description = "知识点ID") @PathVariable @NotNull(message = "知识点ID不能为空") Integer id,
                                                                 @Parameter(description = "检查状态和评分信息") @Valid @RequestBody CheckAndScoreReq req) {
        boolean result = adminKnowledgePointsService.updateKnowledgePointCheckAndScore(id, req);
        return ResultBean.success(result);
    }

    /**
     * 批量更新知识点检查状态
     *
     * @param req 批量检查状态信息
     * @return 更新结果
     */
    @PutMapping("/batch-check")
    @Operation(summary = "批量更新知识点检查状态")
    @SaCheckPermission("teacher:admin:knowledge-points:batch-check")
    public ResultBean<Boolean> batchUpdateKnowledgePointCheck(@Parameter(description = "批量检查状态信息") @Valid @RequestBody BatchCheckReq req) {
        boolean result = adminKnowledgePointsService.batchUpdateKnowledgePointCheck(req.getIds(), req.getUnitId(),req.getIsChecked());
        return ResultBean.success(result);
    }


    /**
     * 删除知识点
     *
     * @param id 知识点ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除知识点")
    @SaCheckPermission("teacher:admin:knowledge-points:delete")
    public ResultBean<Boolean> deleteKnowledgePoint(@Parameter(description = "知识点ID") @PathVariable @NotNull(message = "知识点ID不能为空") Integer id,@RequestParam("unitId")Integer unitId) {
        boolean result = adminKnowledgePointsService.deleteKnowledgePoint(id,unitId);
        return ResultBean.success(result);
    }

    /**
     * 检查知识点内容是否正确和超纲
     *
     * @param req 知识点检查请求参数
     * @return 检查结果
     */
    @PostMapping("/check")
    @Operation(summary = "检查知识点内容是否正确和超纲")
    @SaCheckPermission("teacher:admin:knowledge-points:check")
    public ResultBean<KnowledgePointCheckResp> checkKnowledgePoint(@Parameter(description = "知识点ID") @Valid @RequestBody KnowledgePointCheckReq req) {
        KnowledgePointCheckResp result = knowledgePointCheckService.checkKnowledgePoint(req);
        return ResultBean.success(result);
    }

    /**
     * 检查知识点相似度
     *
     * @param req 知识点相似度检查请求参数
     * @return 检查结果
     */
    @PostMapping("/similarity-check")
    @Operation(summary = "检查知识点相似度")
    @SaCheckPermission("teacher:admin:knowledge-points:similarity-check")
    public ResultBean<KnowledgePointSimilarityCheckResp> checkKnowledgePointSimilarity(@Parameter(description = "知识点相似度检查请求参数") @Valid @RequestBody KnowledgePointSimilarityCheckReq req) {
        KnowledgePointSimilarityCheckResp result = knowledgePointSimilarityService.checkKnowledgePointSimilarity(req);
        return ResultBean.success(result);
    }

    /**
     * 合并知识点
     *
     * @param req 合并知识点请求参数
     * @return 合并结果
     */
    @PostMapping("/merge")
    @Operation(summary = "合并知识点")
    @SaCheckPermission("teacher:admin:knowledge-points:merge")
    public ResultBean<Boolean> mergeKnowledgePoint(@Parameter(description = "合并知识点请求参数") @Valid @RequestBody MergeKnowledgePointsReq req) {
        boolean result = knowledgePointSimilarityService.mergeKnowledgePoints(req);
        return ResultBean.success(result);
    }


    @PostMapping("/add-with-mapping")
    @Operation(summary = "添加知识点映射关系")
    @SaCheckPermission("teacher:admin:knowledge-points:save")
    public ResultBean<Boolean> addKnowledgePointUnitMappings(@Parameter(description = "知识点信息") @Valid @RequestBody AddKnowledgePointUnitMappingReq req) {
        boolean result = knowledgePointSimilarityService.addKnowledgePointUnitMappings(req);
        return ResultBean.success(result);
    }

    /**
     * 拆分知识点
     *
     * @param req 知识点拆分请求
     * @return 拆分后的知识点列表
     */
    @PostMapping("/split")
    @Operation(summary = "拆分知识点")
    public ResultBean<List<KnowledgePointSplitResp>> splitKnowledgePoint(@RequestBody @Validated KnowledgePointSplitReq req) {
        req.setUserId(StpUtil.getLoginIdAsInt());
        List<KnowledgePointSplitResp> result = knowledgePointSplitService.splitKnowledgePoint(req);
        return ResultBean.success(result);
    }

    /**
     * 批量保存拆分知识点
     *
     * @param req 批量保存拆分知识点请求参数
     * @return 保存结果
     */
    @PostMapping("/batch-save-split")
    @Operation(summary = "批量保存拆分知识点")
    @SaCheckPermission("teacher:admin:knowledge-points:save")
    public ResultBean<Boolean> batchSaveSplitKnowledgePoints(@RequestBody @Validated BatchSaveSplitKnowledgePointsReq req) {
        boolean result = knowledgePointSplitService.batchSaveSplitKnowledgePoints(req);
        return ResultBean.success(result);
    }

    /**
     * 分页查询修改日志
     *
     * @param pageReq 分页查询参数
     * @return 修改日志分页列表
     */
    @PostMapping("/modification-log-page")
    @Operation(summary = "分页查询修改日志")
    public ResultBean<PageListBean<AdminModificationLogResp>> pageLogs(@RequestBody AdminModificationLogPageReq pageReq) {
        IPage<ModificationLogEntity> result =
                adminModificationLogService.pageLogs(pageReq);
        return ResultBean.success(PageConverterUtils.convertPageListBean(result, AdminModificationLogConvert.INSTANCE::entityListToResponseList));
    }
}