package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ArticleClassify;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ss.articleClassify.service.IArticleClassifyService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 分类信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/article/classify")
public class ArticleClassifyController extends BaseController
{
    @Resource
    private IArticleClassifyService asArticleClassifyService;

    /**
     * 获取分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:articleClassify:list')")
    @GetMapping("/list")
    public AjaxResult list(ArticleClassify asArticleClassify)
    {
        List<ArticleClassify> asArticleClassifies = asArticleClassifyService.selectClassifyListWithIsolate(asArticleClassify);
        return success(asArticleClassifies);
    }

    /**
     * 查询分类列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:articleClassify:list')")
    @GetMapping("/list/exclude/{classifyId}")
    public AjaxResult excludeChild(@PathVariable(value = "classifyId", required = false) Long classifyId)
    {
        List<ArticleClassify> articleClassifies = asArticleClassifyService.selectClassifyListWithIsolate(new ArticleClassify());
        articleClassifies.removeIf(d -> d.getClassifyId().intValue() == classifyId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), classifyId + ""));
        return success(articleClassifies);
    }

    /**
     * 查询分类列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:articleClassify:list')")
    @GetMapping("/list/excludes/{classifyIds}")
    public AjaxResult excludeChild(@PathVariable(value = "classifyIds", required = false) List<Long> classifyIds)
    {
        List<ArticleClassify> articleClassifies = asArticleClassifyService.selectClassifyListWithIsolate(new ArticleClassify());
        if (classifyIds != null && !classifyIds.isEmpty()) {
            for (Long classifyId:classifyIds) {
                articleClassifies.removeIf(d -> d.getClassifyId().intValue() == classifyId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), classifyId + ""));
            }
        }
        return success(articleClassifies);
    }

    /**
     * 根据分类编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:articleClassify:query')")
    @GetMapping(value = "/{classifyId}")
    public AjaxResult getInfo(@PathVariable Long classifyId)
    {
        asArticleClassifyService.checkClassifyDataScope(classifyId);
        return success(asArticleClassifyService.selectClassifyById(classifyId));
    }

    /**
     * 新增分类
     */
    @PreAuthorize("@ss.hasPermi('system:articleClassify:add')")
    @Log(title = "分类管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ArticleClassify classify)
    {
        if (!asArticleClassifyService.checkClassifyNameUnique(classify))
        {
            return error("新增分类'" + classify.getClassifyName() + "'失败，分类名称已存在");
        }
        classify.setCreateBy(getUsername());
//        classify.setAgentId(getAgentId());
        return toAjax(asArticleClassifyService.insertClassify(classify));
    }

    /**
     * 修改分类
     */
    @PreAuthorize("@ss.hasPermi('system:articleClassify:edit')")
    @Log(title = "分类管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ArticleClassify articleClassify)
    {
        Long classifyId = articleClassify.getClassifyId();
        asArticleClassifyService.checkClassifyDataScope(classifyId);
        if (!asArticleClassifyService.checkClassifyNameUnique(articleClassify))
        {
            return error("修改分类'" + articleClassify.getClassifyName() + "'失败，分类名称已存在");
        }
        else if (articleClassify.getParentId().equals(classifyId))
        {
            return error("修改分类'" + articleClassify.getClassifyName() + "'失败，上级分类不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, articleClassify.getStatus()) && asArticleClassifyService.selectNormalChildrenClassifyById(classifyId) > 0)
        {
            return error("该分类包含未停用的子分类！");
        }
        articleClassify.setUpdateBy(getUsername());
        return toAjax(asArticleClassifyService.updateClassify(articleClassify));
    }

    /**
     * 删除分类
     */
    @PreAuthorize("@ss.hasPermi('system:articleClassify:remove')")
    @Log(title = "分类管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{classifyId}")
    public AjaxResult remove(@PathVariable Long classifyId)
    {
        if (asArticleClassifyService.hasChildByclassifyId(classifyId))
        {
            return warn("存在下级分类,不允许删除");
        }
        if (asArticleClassifyService.checkClassifyExistArticle(classifyId))
        {
            return warn("分类存在文章,不允许删除");
        }
        asArticleClassifyService.checkClassifyDataScope(classifyId);
        return toAjax(asArticleClassifyService.deleteClassifyById(classifyId));
    }
}
