package com.gxwebsoft.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.cms.entity.Article;
import com.gxwebsoft.cms.entity.ArticleCategory;
import com.gxwebsoft.cms.entity.ArticleContent;
import com.gxwebsoft.cms.param.ArticleParam;
import com.gxwebsoft.cms.service.ArticleCategoryService;
import com.gxwebsoft.cms.service.ArticleContentService;
import com.gxwebsoft.cms.service.ArticleService;
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 com.gxwebsoft.shop.entity.Goods;
import com.gxwebsoft.shop.param.GoodsParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章控制器
 *
 * @author 科技小王子
 * @since 2023-10-22 15:47:09
 */
@Api(tags = "文章")
@RestController
@RequestMapping("/api/cms/article")
public class ArticleController extends BaseController {
    @Resource
    private ArticleService articleService;
    @Resource
    private ArticleCategoryService articleCategoryService;
    @Resource
    private ArticleContentService articleContentService;

    @ApiOperation("分页查询文章")
    @GetMapping("/page")
    public ApiResult<PageResult<Article>> page(ArticleParam param) {
        // 使用关联查询
        return success(articleService.pageRel(param));
    }

    @ApiOperation("查询全部文章")
    @GetMapping()
    public ApiResult<List<Article>> list(ArticleParam param) {
        // 使用关联查询
        return success(articleService.listRel(param));
    }

    @ApiOperation("根据id查询文章")
    @GetMapping("/{id}")
    public ApiResult<Article> get(@PathVariable("id") Integer id) {
      // 使用关联查询
      Article article = articleService.getByIdRel(id);
      // 更新阅读数量
      article.setActualViews(article.getActualViews() + 1);
      articleService.updateById(article);
      // 附加文字内容
      ArticleContent content = articleContentService.getOne(new LambdaQueryWrapper<ArticleContent>().eq(ArticleContent::getArticleId,article.getArticleId()).last("limit 1"));
      if(content != null){
        article.setContent(content.getContent());
      }
      return success(article);
    }

    @ApiOperation("读取上一篇")
    @GetMapping("/getPrevious/{id}")
    public ApiResult<Article> getPrevious(@PathVariable("id") Integer id) {
      LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
      wrapper.lt(Article::getArticleId,id);
      wrapper.eq(Article::getStatus,0);
      wrapper.eq(Article::getType,0);
      wrapper.orderByDesc(Article::getArticleId);
      wrapper.last("limit 1");
      final Article article = articleService.getOne(wrapper);
      return success(article);
    }

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

    @PreAuthorize("hasAuthority('cms:article:save')")
    @ApiOperation("添加文章")
    @Transactional(rollbackFor = {Exception.class})
    @PostMapping()
    public ApiResult<?> save(@RequestBody Article article) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          article.setUserId(loginUser.getUserId());
        }
        // 同步类型
//        final ArticleCategory category = articleCategoryService.getById(article.getCategoryId());
//        article.setType(category.getType());
        if (articleService.save(article)) {
          // 保存文章内容
          final ArticleContent content = new ArticleContent();
          content.setArticleId(article.getArticleId());
          content.setContent(article.getContent());
          articleContentService.save(content);
          return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:article:update')")
    @ApiOperation("修改文章")
    @Transactional(rollbackFor = {Exception.class})
    @PutMapping()
    public ApiResult<?> update(@RequestBody Article article) {
        if (articleService.updateById(article)) {
            // 更新文章内容
            ArticleContent content = new ArticleContent();
            content.setArticleId(article.getArticleId());
            content.setContent(article.getContent());
            ArticleContent one = articleContentService.getOne(new LambdaQueryWrapper<ArticleContent>().eq(ArticleContent::getArticleId, article.getArticleId()).last("limit 1"));
            if(one != null){
              one.setContent(article.getContent());
              articleContentService.updateById(one);
            }else {
              articleContentService.save(content);
            }
            // 更新时间
            article.setUpdateTime(new Date());
            articleService.updateById(article);
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:article:remove')")
    @ApiOperation("删除文章")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (articleService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('cms:article:save')")
    @ApiOperation("批量添加文章")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Article> list) {
        if (articleService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:article:update')")
    @ApiOperation("批量修改文章")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Article> batchParam) {
        if (batchParam.update(articleService, "article_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:article:remove')")
    @ApiOperation("批量删除文章")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (articleService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

  @ApiOperation("统计信息")
  @GetMapping("/data")
  public ApiResult<Map<String, Integer>> data(ArticleParam param) {
    Map<String, Integer> data = new HashMap<>();
    final LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();

    if(param.getMerchantId() != null){
      wrapper.eq(Article::getMerchantId,param.getMerchantId());
    }

    Integer totalNum = articleService.count(
      wrapper.eq(Article::getDeleted,0).eq(Article::getStatus,0)
    );
    data.put("totalNum", totalNum);

    Integer totalNum2 = articleService.count(
      wrapper.eq(Article::getStatus,1)
    );
    data.put("totalNum2", totalNum2);

    Integer totalNum3 = articleService.count(
      wrapper.gt(Article::getStatus,1)
    );
    data.put("totalNum3", totalNum3);

    return success(data);
  }


}
