package com.gxwebsoft.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.cms.entity.Article;
import com.gxwebsoft.cms.entity.ArticleCategory;
import com.gxwebsoft.cms.entity.Navigation;
import com.gxwebsoft.cms.param.ArticleCategoryParam;
import com.gxwebsoft.cms.param.ArticleParam;
import com.gxwebsoft.cms.param.NavigationParam;
import com.gxwebsoft.cms.service.ArticleCategoryService;
import com.gxwebsoft.cms.service.ArticleService;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.*;
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/article-category")
public class ArticleCategoryController extends BaseController {
    @Resource
    private ArticleCategoryService articleCategoryService;
    @Resource
    private ArticleService articleService;
    @Resource
    private RedisUtil redisUtil;

    @ApiOperation("分页查询文章分类表")
    @GetMapping("/page")
    public ApiResult<PageResult<ArticleCategory>> page(ArticleCategoryParam param) {
        PageParam<ArticleCategory, ArticleCategoryParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc,create_time asc");
        return success(articleCategoryService.page(page, page.getWrapper()));
    }

    @ApiOperation("查询全部文章分类表")
    @GetMapping()
    public ApiResult<List<ArticleCategory>> list(ArticleCategoryParam param) {
      // 使用关联查询
      List<ArticleCategory> categoryList = articleCategoryService.listRel(param);
      // 是否读取新闻列表
      if (param.getSceneType() != null && param.getSceneType().equals("showArticle")) {
        categoryList.forEach(d->{
          final ArticleParam articleParam = new ArticleParam();
          articleParam.setCategoryId(d.getCategoryId());
          articleParam.setDeleted(0);
          if(param.getLimit() != null){
            articleParam.setLimit(param.getLimit());
          }
          final PageResult<Article> articlePageResult = articleService.pageRel(articleParam);
          d.setArticleList(articlePageResult.getList());
        });
      }
      return success(categoryList);
    }

    @ApiOperation("根据id查询文章分类表")
    @GetMapping("/{id}")
    public ApiResult<ArticleCategory> get(@PathVariable("id") Integer id) {
      // 使用关联查询
      ArticleCategory category = articleCategoryService.getByIdRel(id);
      if(category != null){
        if (!category.getParentId().equals(0)) {
          final ArticleCategory parentCategory = articleCategoryService.getById(category.getParentId());
          category.setParentName(parentCategory.getTitle());
        }
      }
      return success(category);
    }

    @PreAuthorize("hasAuthority('cms:articleCategory:save')")
    @ApiOperation("添加文章分类表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ArticleCategory articleCategory) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          articleCategory.setUserId(loginUser.getUserId());
        }
        if (articleCategoryService.save(articleCategory)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:articleCategory:update')")
    @ApiOperation("修改文章分类表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ArticleCategory articleCategory) {
        if (articleCategoryService.updateById(articleCategory)) {
          // 同步分类状态
          final List<ArticleCategory> list = articleCategoryService.list(new LambdaQueryWrapper<ArticleCategory>().eq(ArticleCategory::getParentId, articleCategory.getCategoryId()));
          list.forEach(d -> {
            d.setStatus(articleCategory.getStatus());
          });
          articleCategoryService.updateBatchById(list);
          return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:articleCategory:remove')")
    @ApiOperation("删除文章分类表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (articleService.count(new LambdaQueryWrapper<Article>().eq(Article::getCategoryId,id)) > 0) {
          return fail("请先删除栏目下的文章");
        }
        if (articleCategoryService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

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

    @PreAuthorize("hasAuthority('cms:articleCategory:update')")
    @ApiOperation("批量修改文章分类表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ArticleCategory> batchParam) {
        if (batchParam.update(articleCategoryService, "category_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:articleCategory:remove')")
    @ApiOperation("批量删除文章分类表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
      final int count = articleService.count(new LambdaQueryWrapper<Article>().in(Article::getCategoryId, ids));
      System.out.println("count = " + count);
      if (articleService.count(new LambdaQueryWrapper<Article>().in(Article::getCategoryId,ids)) > 0) {
          return fail("请先删除栏目下的文章");
        }
        if (articleCategoryService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("检查分类是否存在")
    @GetMapping("/existence")
    public ApiResult<?> existence(ExistenceParam<ArticleCategory> param) {
      if (param.isExistence(articleCategoryService, ArticleCategory::getUserId)) {
        return success(param.getValue() + "已存在");
      }
      return fail(param.getValue() + "不存在");
    }

    @ApiOperation("获取树形结构数据")
    @GetMapping("/tree")
    public ApiResult<List<ArticleCategory>> tree(ArticleCategoryParam param) {
      param.setHide(0);
      final List<ArticleCategory> categoryList = articleCategoryService.listRel(param);
      return success(CommonUtil.toTreeData(categoryList, 0, ArticleCategory::getParentId, ArticleCategory::getCategoryId, ArticleCategory::setChildren));
    }
}
