package com.gxwebsoft.cms.controller;

import com.alipay.api.domain.Article;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.cms.entity.CmsArticleContent;
import com.gxwebsoft.cms.param.CmsNavigationParam;
import com.gxwebsoft.cms.service.CmsArticleContentService;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.cms.service.CmsArticleService;
import com.gxwebsoft.cms.entity.CmsArticle;
import com.gxwebsoft.cms.param.CmsArticleParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章控制器
 *
 * @author 科技小王子
 * @since 2024-09-10 20:47:57
 */
@Api(tags = "文章管理")
@RestController
@RequestMapping("/api/cms/cms-article")
public class CmsArticleController extends BaseController {
    @Resource
    private CmsArticleService cmsArticleService;
    @Resource
    private CmsArticleContentService articleContentService;
    @Resource
    private UserService userService;

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

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

    @ApiOperation("根据id查询文章")
    @GetMapping("/{id}")
    public ApiResult<CmsArticle> get(@PathVariable("id") Integer id) {
      // 使用关联查询
      CmsArticle article = cmsArticleService.getByIdRel(id);
      // 更新阅读数量
      article.setActualViews(article.getActualViews() + 1);
      cmsArticleService.updateById(article);
      // 附加文字内容
      CmsArticleContent content = articleContentService.getOne(new LambdaQueryWrapper<CmsArticleContent>().eq(CmsArticleContent::getArticleId,article.getArticleId()).last("limit 1"));
      if(content != null){
        article.setContent(content.getContent());
      }
      return success(article);
    }
    @PreAuthorize("hasAuthority('cms:cmsArticle:save')")
    @ApiOperation("添加文章")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CmsArticle article) {
      // 记录当前登录用户id
      User loginUser = getLoginUser();
      if (loginUser != null) {
        article.setUserId(loginUser.getUserId());
        article.setAuthor(loginUser.getNickname());
        article.setMerchantId(loginUser.getMerchantId());
      }
      // 是否密码可见
      if(article.getPermission() == 2){
        article.setPassword(userService.encodePassword(article.getPassword()));
      }
      if (cmsArticleService.save(article)) {
        // 保存文章内容
        final CmsArticleContent content = new CmsArticleContent();
        content.setArticleId(article.getArticleId());
        content.setContent(article.getContent());
        articleContentService.save(content);
        return success("添加成功");
      }
      return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:cmsArticle:update')")
    @ApiOperation("修改文章")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CmsArticle cmsArticle) {
        // 是否密码可见
        if(cmsArticle.getPermission() == 2){
          cmsArticle.setPassword(userService.encodePassword(cmsArticle.getPassword()));
        }
        if (cmsArticleService.updateById(cmsArticle)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

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

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

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

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

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

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

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

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

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

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

    return success(data);
  }

  @ApiOperation("密码校验")
  @GetMapping("/checkArticlePassword")
  public ApiResult<?> checkArticlePassword(CmsArticle param) {
    if (!userService.comparePassword(param.getPassword(), param.getPassword2())) {
      return fail("密码不正确");
    }
    return success("密码正确");
  }

}
