package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.PageResult;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.entity.KnowledgeBasePath;
import top.tqx.demo_1.entity.User;
import top.tqx.demo_1.mapper.KnowledgeBasePathMapper;
import top.tqx.demo_1.service.DepartmentService;
import top.tqx.demo_1.vo.CollectionVO;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Tag(name = "知识库访问控制", description = "查询collection表中的记录，获取用户可访问的知识库列表")
@RestController
@RequestMapping("/collection-access")
@Slf4j
public class CollectionAccessController extends BaseController {

    @Autowired
    private KnowledgeBasePathMapper knowledgeBasePathMapper;

    @Autowired
    private DepartmentService departmentService;

    @Operation(summary = "分页查询知识库列表", description = "分页获取知识库列表，支持条件过滤")
    @GetMapping("/page")
    public Result<PageResult<KnowledgeBasePath>> pageCollections(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "知识库名称") @RequestParam(required = false) String name,
            @Parameter(description = "部门") @RequestParam(required = false) String department,
            @Parameter(description = "所有者类型") @RequestParam(required = false) String ownerType,
            @Parameter(description = "可见性") @RequestParam(required = false) String visibility,
            HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                return error("用户未登录");
            }

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<KnowledgeBasePath> page =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);

            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<KnowledgeBasePath> wrapper =
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();

            if (name != null && !name.isEmpty()) {
                wrapper.like(KnowledgeBasePath::getName, name);
            }
            if (department != null && !department.isEmpty()) {
                wrapper.eq(KnowledgeBasePath::getDepartment, department);
            }
            if (ownerType != null && !ownerType.isEmpty()) {
                wrapper.eq(KnowledgeBasePath::getOwnerType, ownerType);
            }
            if (visibility != null && !visibility.isEmpty()) {
                wrapper.eq(KnowledgeBasePath::getVisibility, visibility);
            }

            wrapper.orderByDesc(KnowledgeBasePath::getCreateTime);

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<KnowledgeBasePath> resultPage =
                    knowledgeBasePathMapper.selectPage(page, wrapper);

            PageResult<KnowledgeBasePath> pageResult = PageResult.of(
                    resultPage.getRecords(),
                    resultPage.getTotal(),
                    resultPage.getSize(),
                    resultPage.getCurrent()
            );

            return success(pageResult);
        } catch (Exception e) {
            log.error("分页查询知识库列表失败", e);
            return error("分页查询知识库列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取知识库详情", description = "根据ID获取知识库详细信息")
    @GetMapping("/{id}")
    public Result<KnowledgeBasePath> getCollectionById(
            @Parameter(description = "知识库ID", required = true) @PathVariable Long id,
            HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                return error("用户未登录");
            }

            KnowledgeBasePath knowledgeBasePath = knowledgeBasePathMapper.selectById(id);
            if (knowledgeBasePath == null) {
                return error("知识库不存在");
            }

            return success(knowledgeBasePath);
        } catch (Exception e) {
            log.error("获取知识库详情失败", e);
            return error("获取知识库详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户可访问的知识库列表", description = "获取当前用户可访问的所有知识库")
    @GetMapping("/accessible")
    public Result<Map<String, Object>> getAccessibleCollections(HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                return error("用户未登录");
            }

            User user = authService.validateToken(request.getHeader("Authorization").substring(7));
            if (user == null) {
                return error("用户信息获取失败");
            }

            List<KnowledgeBasePath> knowledgeBases;

            if (top.tqx.demo_1.constant.CommonConstant.RoleType.SUPER_ADMIN.equals(user.getUserType())) {
                knowledgeBases = knowledgeBasePathMapper.selectList(null);
                log.info("超级管理员获取所有知识库: userId={}, 数量={}", userId, knowledgeBases.size());
            } else {
                String deptName = getDeptName(user);

                com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<KnowledgeBasePath> wrapper =
                        new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();

                wrapper.and(w -> w.eq(KnowledgeBasePath::getOwnerType, "department")
                        .and(w1 -> w1.eq(KnowledgeBasePath::getDepartment, deptName)
                                .or().eq(KnowledgeBasePath::getDepartment, "公共部门"))
                        .eq(KnowledgeBasePath::getVisibility, "public")
                        .or()
                        .eq(KnowledgeBasePath::getOwnerType, "personal")
                        .eq(KnowledgeBasePath::getUploader, userId.toString()));

                knowledgeBases = knowledgeBasePathMapper.selectList(wrapper);
            }

            List<CollectionVO> collections = knowledgeBases.stream()
                    .map(kb -> {
                        CollectionVO vo = new CollectionVO();
                        vo.setName(kb.getName());
                        vo.setDisplayName(kb.getDisplayName() != null ? kb.getDisplayName() : kb.getName());
                        vo.setDepartment(kb.getDepartment());
                        vo.setDescription(kb.getDescription());
                        vo.setCreateTime(kb.getCreateTime());
                        return vo;
                    })
                    .collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("collections", collections);
            result.put("total", collections.size());

            return success(result);
        } catch (Exception e) {
            log.error("获取用户可访问知识库失败", e);
            return error("获取用户可访问知识库失败: " + e.getMessage());
        }
    }

    private String getDeptName(User user) {
        if (user.getDeptId() == null) {
            return "公共部门";
        }
        try {
            var dept = departmentService.getDepartmentById(user.getDeptId());
            return dept != null ? dept.getDeptName() : "公共部门";
        } catch (Exception e) {
            log.warn("获取部门信息失败: deptId={}", user.getDeptId());
            return "公共部门";
        }
    }
}