package com.cclotus.cms.controller.wxapp

import com.cclotus.cms.domain.CmsPost
import com.cclotus.cms.domain.CmsTerm
import com.cclotus.cms.service.CmsPostService
import com.cclotus.cms.service.CmsTermService
import com.cclotus.cms.util.CmsConstant
import com.cclotus.cms.vo.CmsPostFormReq
import com.ruoyi.common.core.domain.AjaxResult
import com.ruoyi.common.core.page.TableDataInfo
import com.ruoyi.common.reqParam.PageParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.util.Assert
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

@Suppress("NAME_SHADOWING")
@RestController
@RequestMapping("/cms")
class CmsController {

    @Autowired
    lateinit var cmsTermService: CmsTermService

    @Autowired
    lateinit var cmsPostService: CmsPostService

    /**
     * 查询菜单列表
     *
     * @param taxonomy 分类系统
     * @param paging    是否分页，默认分页
     * @param cmsTerm   过滤条件
     */
    @GetMapping("/{taxonomy:wxAppMenu|catalog|tag}/list")
    fun listMenu(
        @PathVariable("taxonomy") taxonomy: String,
        cmsTerm: CmsTerm,
        paging: Boolean?,
        pageParam: PageParam?,
    ): TableDataInfo? {
        var pageParam = pageParam
        if (paging != null && !paging) pageParam = null

        cmsTerm.taxonomy = taxonomy
        return cmsTermService.list(cmsTerm, pageParam)
    }

    /**
     * 根据分类别名或Id获取分类详情
     *
     * @param taxonomy 分类系统
     * @param term 分类标识
     * @return 分类详细信息
     */
    @GetMapping("/{taxonomy:wxAppMenu|catalog|tag}/{term}")
    fun detail(
        @PathVariable("taxonomy") taxonomy: String,
        @PathVariable("term") term: String,
    ): AjaxResult {
        return AjaxResult.success(cmsTermService.detail(taxonomy, term))
    }

    /**
     * 查询发布内容列表
     *
     * @param contentType 内容类型
     * @param termAlias 栏目别名
     * @param paging    是否分页，默认分页
     * @param deep      是否显示栏目下子栏目的文章
     * @param post      过滤条件
     * @param scope     列表范围 null：查询所有列表，myself：查询自己创建的列表
     * @param userId    用户ID
     */
    @GetMapping(path = ["/{contentType:article|page|video|picture|custom}/{termAlias}/list", "/{contentType:article|page|video|picture|custom}/list"])
    fun listPost(
        @PathVariable("contentType") contentType: String,
        @PathVariable(name = "termAlias", required = false) termAlias: String?,
        paging: Boolean?,
        deep: Boolean?,
        post: CmsPost,
        pageParam: PageParam?,
        content: Boolean?,
        scope: String?,
        userId: String?,
        @RequestParam(required = false) query: Map<String, String>?,
    ): TableDataInfo? {
        var pageParam = pageParam
        if (paging != null && !paging) pageParam = null
        // 根据查询范围构建查询条件
        when (scope) {
            "myself" -> { // 查询自己的发布内容
                Assert.hasText(userId, "用户ID不可为空")
                post.createBy = userId
            }

            else -> { // 默认查询所有已审核的发布内容
                post.review = "1"
            }
        }
        // 提取扩展属性查询条件
        val meta = query?.filterKeys { it.startsWith(prefix = CmsConstant.META_QUERY_PREFIX, ignoreCase = true) }
            ?.mapKeys { it.key.removePrefix(CmsConstant.META_QUERY_PREFIX) }
        // 默认查询显示和发布的文章内容
        post.visible = "1"
        post.status = "0"
        post.contentType = contentType
        return cmsPostService.list(termAlias, deep ?: false, post, pageParam, content ?: false, meta)
    }

    /**
     * 获取文章详情信息
     *
     * @return
     */
    @GetMapping("/{contentType:article|page|video|picture|custom}/{post}")
    fun detailPost(
        @PathVariable("contentType") contentType: String,
        @PathVariable("post") post: String,
    ): AjaxResult {
        return AjaxResult.success(cmsPostService.detail(contentType, post))
    }

    /**
     * 新增发布内容
     *
     * @param contentType 内容类型 custom
     * @param cmsPostFormReq 内容详情
     * @param termAlias 类型别名
     * @param userId 创建用户ID
     * @return 创建结果
     */
    @PostMapping("/{contentType:custom}/{termAlias}")
    fun add(
        @PathVariable("contentType") contentType: String,
        @PathVariable("termAlias") termAlias: String,
        @Validated @RequestBody cmsPostFormReq: CmsPostFormReq,
        userId: String?,
    ): AjaxResult {
        Assert.hasText(userId, "用户ID不可为空")
        cmsPostFormReq.contentType = contentType
        // 文章审核状态为待审核
        cmsPostFormReq.review = "0"
        // 处理默认状态值
        cmsPostFormReq.status = "0"
        cmsPostFormReq.topStatus = 0
        cmsPostFormReq.visible = "1"
        cmsPostFormReq.origin = "user"
        // 创建文章
        cmsPostService.createByTermAlias(cmsPostFormReq, userId!!, termAlias)
        return AjaxResult.success()
    }

    /**
     * 修改发布内容
     *
     * @param contentType 内容类型
     * @param cmsPostFormReq 内容详情
     * @param userId 用户ID
     * @return 修改结果
     */
    @PutMapping("/{contentType:custom}/{termAlias}")
    fun edit(
        @PathVariable("contentType") contentType: String,
        @PathVariable(name = "termAlias", required = false) termAlias: String?,
        @Validated @RequestBody cmsPostFormReq: CmsPostFormReq,
        userId: String?,
    ): AjaxResult {
        Assert.hasText(userId, "用户ID不可为空")
        cmsPostFormReq.contentType = contentType
        // 文章审核状态为待审核
        cmsPostFormReq.review = "0"
        // 处理默认状态值
        cmsPostFormReq.status = "0"
        cmsPostFormReq.topStatus = 0
        cmsPostFormReq.visible = "1"
        cmsPostService.update(cmsPostFormReq, userId!!)
        return AjaxResult.success()
    }
}
