package com.gxwebsoft.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.cms.entity.Docs;
import com.gxwebsoft.cms.entity.DocsBook;
import com.gxwebsoft.cms.entity.DocsContent;
import com.gxwebsoft.cms.param.DocsBookParam;
import com.gxwebsoft.cms.param.DocsContentParam;
import com.gxwebsoft.cms.param.DocsParam;
import com.gxwebsoft.cms.service.DocsBookService;
import com.gxwebsoft.cms.service.DocsContentService;
import com.gxwebsoft.cms.service.DocsService;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 文档管理记录表控制器
 *
 * @author 科技小王子
 * @since 2023-10-22 15:47:09
 */
@Api(tags = "文档")
@RestController
@RequestMapping("/api/cms/docs")
public class DocsController extends BaseController {
    @Resource
    private DocsService docsService;
    @Resource
    private DocsContentService contentService;
    @Resource
    private DocsBookService bookService;

    @ApiOperation("分页查询文档管理记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Docs>> page(DocsParam param) {
        // 使用关联查询
        return success(docsService.pageRel(param));
    }

    @ApiOperation("查询全部文档管理记录表")
    @GetMapping()
    public ApiResult<List<Docs>> list(DocsParam param) {
        // 通过书籍标识查询所有的目录章节
        if(param.getCode() != null){
          final DocsBookParam bookParam = new DocsBookParam();
          bookParam.setCode(param.getCode());
          final List<DocsBook> books = bookService.listRel(bookParam);
          final DocsBook book = CommonUtil.listGetOne(books);
          param.setBookId(book.getBookId());
          return success(docsService.listRel(param));
        }
        // 使用关联查询
        return success(docsService.listRel(param));
    }

    @ApiOperation("根据id查询文档管理记录表")
    @GetMapping("/{id}")
    public ApiResult<Docs> get(@PathVariable("id") Integer id) {
        final Docs docs = docsService.getByIdRel(id);
        final DocsContentParam param = new DocsContentParam();
        param.setDocsId(id);
        final List<DocsContent> list = contentService.listRel(param);
        DocsContent content = CommonUtil.listGetOne(list);
        docs.setContent(content.getContent());
        docs.setContentId(content.getId());
        // 更新阅读数量
        docs.setActualViews(docs.getActualViews() + 1);
        docsService.updateById(docs);
        return success(docs);
    }
    @ApiOperation("读取上一篇")
    @GetMapping("/getPrevious/{id}")
    public ApiResult<Docs> getPrevious(@PathVariable("id") Integer id) {
      LambdaQueryWrapper<Docs> wrapper = new LambdaQueryWrapper<>();
      wrapper.lt(Docs::getDocsId,id);
      wrapper.eq(Docs::getStatus,0);
      wrapper.orderByDesc(Docs::getDocsId);
      wrapper.last("limit 1");
      final Docs article = docsService.getOne(wrapper);
      return success(article);
    }

    @ApiOperation("读取下一篇")
    @GetMapping("/getNext/{id}")
    public ApiResult<Docs> getNext(@PathVariable("id") Integer id) {
      LambdaQueryWrapper<Docs> wrapper = new LambdaQueryWrapper<>();
      wrapper.gt(Docs::getDocsId,id);
      wrapper.eq(Docs::getStatus,0);
      wrapper.orderByAsc(Docs::getDocsId);
      wrapper.last("limit 1");
      final Docs article = docsService.getOne(wrapper);
      return success(article);
    }

    @PreAuthorize("hasAuthority('cms:docs:save')")
    @ApiOperation("添加文档管理记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Docs docs) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          docs.setUserId(loginUser.getUserId());
        }
        if (docsService.save(docs)) {
          final DocsContent content = new DocsContent();
          content.setDocsId(docs.getDocsId());
          contentService.save(content);
          return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:docs:update')")
    @ApiOperation("修改文档管理记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Docs docs) {
        if (docsService.updateById(docs)) {
          final DocsContent content = contentService.getOne(new LambdaQueryWrapper<DocsContent>().eq(DocsContent::getDocsId, docs.getDocsId()).last("limit 1"));
          if(docs.getContent() != null){
            content.setContent(docs.getContent());
          }
          contentService.saveOrUpdate(content);
            return success("保存成功");
        }
        return fail("保存失败");
    }

    @PreAuthorize("hasAuthority('cms:docs:remove')")
    @ApiOperation("删除文档管理记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (docsService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('cms:docs:update')")
    @ApiOperation("批量添加文档管理记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Docs> list) {
        if (docsService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:docs:update')")
    @ApiOperation("批量修改文档管理记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Docs> batchParam) {
        if (batchParam.update(docsService, "docs_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:docs:remove')")
    @ApiOperation("批量删除文档管理记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (docsService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
