package com.gxwebsoft.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.cms.entity.Article;
import com.gxwebsoft.cms.entity.ArticleLike;
import com.gxwebsoft.cms.param.ArticleLikeParam;
import com.gxwebsoft.cms.service.ArticleLikeService;
import com.gxwebsoft.cms.service.ArticleService;
import com.gxwebsoft.common.core.annotation.OperationLog;
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-07-07 13:00:03
 */
@Api(tags = "点赞文章管理")
@RestController
@RequestMapping("/api/cms/article-like")
public class ArticleLikeController extends BaseController {
    @Resource
    private ArticleLikeService articleLikeService;
    @Resource
    private ArticleService articleService;

    @PreAuthorize("hasAuthority('cms:articleLike:list')")
    @OperationLog
    @ApiOperation("分页查询点赞文章")
    @GetMapping("/page")
    public ApiResult<PageResult<ArticleLike>> page(ArticleLikeParam param) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
          param.setUserId(loginUser.getUserId());
        }
        return success(articleLikeService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('cms:articleLike:list')")
    @OperationLog
    @ApiOperation("查询全部点赞文章")
    @GetMapping()
    public ApiResult<List<ArticleLike>> list(ArticleLikeParam param) {
        // 使用关联查询
        return success(articleLikeService.listRel(param));
    }

    @PreAuthorize("hasAuthority('cms:articleLike:list')")
    @OperationLog
    @ApiOperation("根据id查询点赞文章")
    @GetMapping("/{id}")
    public ApiResult<ArticleLike> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(articleLikeService.getByIdRel(id));
    }

    @ApiOperation("添加点赞文章")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ArticleLike articleLike) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录",null);
        }
        // 获取文章
        Article article = articleService.getById(articleLike.getArticleId());
        // 我是否已点赞
        ArticleLike one = articleLikeService.getOne(new LambdaQueryWrapper<ArticleLike>()
                .eq(ArticleLike::getArticleId, articleLike.getArticleId())
                .eq(ArticleLike::getUserId, loginUser.getUserId()));

        articleLike.setUserId(loginUser.getUserId());

        if (!articleLike.getLiked() && one == null) {
            // 点赞行为
            articleLikeService.save(articleLike);
            // 更新点赞数量
            article.setLikes(article.getLikes() + 1);
            article.setLiked(true);
            articleService.updateById(article);
            return success("点赞成功",article);
        }else if(articleLike.getLiked() && one != null) {
            // 取消点赞
            articleLikeService.removeById(one.getId());
            // 更新点赞数量
            article.setLikes(article.getLikes() - 1);
            article.setLiked(false);
            articleService.updateById(article);
            return success("已取消点赞",article);
        }else {
            article.setLiked(!articleLike.getLiked());
            return success("操作失败",article);
        }
    }

    @PreAuthorize("hasAuthority('cms:articleLike:update')")
    @OperationLog
    @ApiOperation("修改点赞文章")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ArticleLike articleLike) {
        if (articleLikeService.updateById(articleLike)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

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

    @PreAuthorize("hasAuthority('cms:articleLike:update')")
    @OperationLog
    @ApiOperation("批量修改点赞文章")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ArticleLike> batchParam) {
        if (batchParam.update(articleLikeService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

}
