package org.jeecg.modules.database.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.database.entity.*;
import org.jeecg.modules.database.service.*;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

/**
 * @Description: 知识库
 * @Author: jeecg-boot
 * @Date: 2024-08-21
 * @Version: V1.0
 */
@Tag(name = "知识库")
@RestController
@RequestMapping("/library/documentLibrary")
@Slf4j
public class DocumentLibraryController extends JeecgController<DocumentLibrary, IDocumentLibraryService> {
    @Autowired
    private IDocumentLibraryService      documentLibraryService;
    @Autowired
    private IDocumentFavoritesService    documentFavoritesService;
    @Autowired
    private ISysUserService              userService;
    @Autowired
    private IDocumentVisitHistoryService documentVisitHistoryService;

    @Operation(summary = "知识库-首页查询")
    @GetMapping(value = "/home")
    public Result<DocumentHome> home(HttpServletRequest request) {

        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);

        DocumentHome home = new DocumentHome();
        home.setFavorite(documentFavoritesService.getTopFavoritesByUserId(userByName.getId()));
        home.setLatest(documentLibraryService.getLatest());
        home.setRecently(documentVisitHistoryService.getRecently(userByName.getId()));
        home.setTotal(documentLibraryService.getTotal());
        home.setToday(documentLibraryService.getToday());
        home.setCategory(documentLibraryService.getCategory());
        return Result.OK(home);
    }

    @Operation(summary = "知识库-首页搜索")
    @GetMapping(value = "/search")
    public Result<List<DocumentLibrary>> search(@RequestParam(name = "keyWord") String keyWord, HttpServletRequest request) {
        LambdaQueryWrapper<DocumentLibrary> queryWrapper = Wrappers.lambdaQuery(DocumentLibrary.class);
        queryWrapper.like(DocumentLibrary::getTitle, keyWord);
        queryWrapper.or().like(DocumentLibrary::getContent, keyWord);
        List<DocumentLibrary> pageList = documentLibraryService.list(queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param documentLibrary
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "知识库-分页列表查询")
    @Operation(summary = "知识库-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<DocumentLibrary>> queryPageList(DocumentLibrary documentLibrary,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<DocumentLibrary> queryWrapper = QueryGenerator.initQueryWrapper(documentLibrary, req.getParameterMap());
        Page<DocumentLibrary> page = new Page<DocumentLibrary>(pageNo, pageSize);
        IPage<DocumentLibrary> pageList = documentLibraryService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @Operation(summary = "知识库-文档树查询")
    @GetMapping(value = "/tree")
    public Result<List<DocumentLibrary>> tree(@RequestParam(name = "parentId") String parentId, HttpServletRequest req) {
        DocumentLibrary documentLibrary = new DocumentLibrary();
        if (StringUtils.isBlank(parentId)) {
            documentLibrary.setParentId(null);
        } else {
            documentLibrary.setParentId(parentId);
            DocumentLibrary parent = documentLibraryService.getById(parentId);
            if (StringUtils.equals(parent.getType(), "DOCUMENT")) {
                return Result.OK();
            }
        }
        QueryWrapper<DocumentLibrary> queryWrapper = QueryGenerator.initQueryWrapper(documentLibrary, req.getParameterMap());
        List<DocumentLibrary> pageList = documentLibraryService.list(queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param documentLibrary
     * @return
     */
    @AutoLog(value = "知识库-添加")
    @Operation(summary = "知识库-添加")
    @RequiresPermissions("library:document_library:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody DocumentLibrary documentLibrary, HttpServletRequest request) {
        documentLibraryService.save(documentLibrary);
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);

        if (StringUtils.equals(documentLibrary.getType(), "DOCUMENT")) {
            DocumentVisitHistory his = new DocumentVisitHistory();
            his.setDocumentId(documentLibrary.getId());
            his.setUserId(userByName.getId());
            his.setDocumentTitle(documentLibrary.getTitle());
            his.setVisitCount(1);
            documentVisitHistoryService.save(his);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param documentLibrary
     * @return
     */
    @AutoLog(value = "知识库-编辑")
    @Operation(summary = "知识库-编辑")
    @RequiresPermissions("library:document_library:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody DocumentLibrary documentLibrary, HttpServletRequest request) {
        documentLibraryService.updateById(documentLibrary);

        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        if (StringUtils.equals(documentLibrary.getType(), "DOCUMENT")) {
            DocumentVisitHistory his = documentVisitHistoryService.findByUserAndDocId(userByName.getId(), documentLibrary.getId());
            his.setDocumentId(documentLibrary.getId());
            his.setDocumentTitle(documentLibrary.getTitle());
            his.setUserId(userByName.getId());
            his.addVisitCount();
            documentVisitHistoryService.saveOrUpdate(his);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "知识库-通过id删除")
    @Operation(summary = "知识库-通过id删除")
    @RequiresPermissions("library:document_library:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        documentLibraryService.removeById(id);
        documentVisitHistoryService.removeByDocId(id);
        documentFavoritesService.removeByDocId(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "知识库-批量删除")
    @Operation(summary = "知识库-批量删除")
    @RequiresPermissions("library:document_library:delete")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        this.documentLibraryService.removeByIds(list);
        list.forEach(id -> {
            documentVisitHistoryService.removeByDocId(id);
            documentFavoritesService.removeByDocId(id);
        });
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "知识库-通过id查询")
    @Operation(summary = "知识库-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<DocumentLibrary> queryById(@RequestParam(name = "id", required = true) String id, HttpServletRequest request) {
        DocumentLibrary documentLibrary = documentLibraryService.getById(id);
        if (documentLibrary == null) {
            return Result.error("未找到对应数据");
        }

        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);

        if (StringUtils.equals(documentLibrary.getType(), "DOCUMENT")) {
            DocumentVisitHistory his = documentVisitHistoryService.findByUserAndDocId(userByName.getId(), documentLibrary.getId());
            his.setDocumentId(documentLibrary.getId());
            his.setUserId(userByName.getId());
            his.addVisitCount();
            his.setDocumentTitle(documentLibrary.getTitle());
            documentVisitHistoryService.saveOrUpdate(his);
        }
        return Result.OK(documentLibrary);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param documentLibrary
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DocumentLibrary documentLibrary) {
        return super.exportXls(request, documentLibrary, DocumentLibrary.class, "知识库");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("library:document_library:add")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DocumentLibrary.class);
    }

}
