package cn.sh.stc.sict.theme.common.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.sh.stc.sict.cloud.common.core.constant.Constant;
import cn.sh.stc.sict.cloud.common.core.util.NumberUtil;
import cn.sh.stc.sict.cloud.common.core.util.R;
import cn.sh.stc.sict.theme.common.dto.ArticleDTO;
import cn.sh.stc.sict.theme.common.dto.ArticleParam;
import cn.sh.stc.sict.theme.common.model.HphyArticle;
import cn.sh.stc.sict.theme.common.service.HphyArticleService;
import cn.sh.stc.sict.theme.common.service.HphyAttachmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javassist.expr.NewArray;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 科普文章
 * 文章编辑：富文本，上传（视频，图片），打标签
 * 个性推荐
 *
 * @author F_xh。
 * @date 2020-12-23 15:30:34
 */
@RestController
@RequestMapping("/hphyarticle")
@AllArgsConstructor
@Slf4j
@Api(tags = "[B]科普文章")
public class HphyArticleController {

    private HphyArticleService hphyArticleService;
    private HphyAttachmentService hphyAttachmentService;

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @return
     */
    @ApiOperation("分页查询 黄浦-科普文章")
    @GetMapping("/page")
    public R getHphyArticlePage(Page page, ArticleParam params) {
        LambdaQueryWrapper<HphyArticle> wrapper = new LambdaQueryWrapper<>();
        if (null != params) {
            if (null != params.getIsPublished()) {
                wrapper.eq(HphyArticle::getIsPublished, params.getIsPublished());
            }
            if (StrUtil.isNotBlank(params.getTitle())) {
                wrapper.like(HphyArticle::getTitle, params.getTitle());
            }
            if (params.getStartTime() != null && params.getEndTime() != null) {
                wrapper.ge(HphyArticle::getUpdateTime, params.getEndTime()).le(HphyArticle::getUpdateTime, params.getStartTime());
            }
            if (params.getType() != null) {
                wrapper.like(HphyArticle::getType, params.getType());
            }
            if (StrUtil.isNotBlank(params.getTags())) {
                List<String> tags = Arrays.asList(params.getTags().split(StringPool.SEMICOLON));
                if (CollUtil.isNotEmpty(tags)) {
                    wrapper.and(i -> {
                        tags.forEach(t -> {
                            i.like(HphyArticle::getTags, t);
                        });
                    });
                }
            }
        }
        wrapper.select(HphyArticle.class, i -> (!i.getColumn().equals("content")))
                .orderByDesc(HphyArticle::getCreateTime);
        page = hphyArticleService.page(page, wrapper);

        if (NumberUtil.isNotNullOrZero(params.getWithPic())) {
            Page<ArticleDTO> dtoPage = hphyAttachmentService.getVO(page);
            return new R(dtoPage);
        }

        return new R<>(page);
    }

    /**
     * 新增黄浦-科普文章
     *
     * @param dto 黄浦-科普文章
     * @return R
     */
    @ApiOperation("新增黄浦-科普文章")
    @PostMapping
    public R save(@RequestBody ArticleDTO dto) {
        return new R<>(hphyArticleService.save(dto));
    }

    /**
     * 发布，取消发布
     *
     * @return
     */
    @ApiOperation("发布状态取反")
    @PostMapping("/publish")
    public R publish(@RequestParam("id") Long id) {
        // 已发布不可删除
        HphyArticle old = hphyArticleService.getById(id);
        if (old == null) {
            return new R().error("未找到目标文章！");
        }
        HphyArticle update = new HphyArticle();
        update.setId(id);
        update.setIsPublished(Constant.BYTE_NO);
        if (NumberUtil.isNullOrZero(old.getIsPublished())) {
            update.setIsPublished(Constant.BYTE_YES);
        }
        hphyArticleService.updateById(update);

        return new R();
    }

    /**
     * 通过id查询黄浦-科普文章
     *
     * @param id id
     * @return R
     */
    @ApiOperation("通过id查询 黄浦-科普文章")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id) {
        HphyArticle article = hphyArticleService.getById(id);
        if (article != null) {
            ArticleDTO dto = new ArticleDTO();
            dto.setArticle(article);
            dto.setAttachmentList(hphyAttachmentService.getByBizId(id));
            return new R(dto);
        }
        return new R<>().error("未找到文章！");
    }

    /**
     * 通过id删除黄浦-科普文章
     *
     * @param id id
     * @return R
     */
    @ApiOperation("删除黄浦-科普文章")
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public R removeById(@PathVariable Long id) {
        // 已发布不可删除
        HphyArticle old = hphyArticleService.getById(id);
        if (old == null) {
            return new R().error("未找到目标文章！");
        }
        if (Constant.BYTE_YES.equals(old.getIsPublished())) {
            return new R().error("已发布文章不可删除！");
        }
        // 虚拟删除?
        hphyAttachmentService.removeByBizId(id);
        hphyArticleService.removeById(id);
        return new R<>();
    }

}
