package cclotus.cloud.gateway.web

import cclotus.cloud.gateway.util.TemplateManager
import com.cclotus.cms.service.CmsPostService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import java.time.format.DateTimeFormatter

/**
 * 模板页面
 */
@Controller
class TemplateController {

    @Autowired
    lateinit var cmsPostService: CmsPostService

    @Autowired
    lateinit var templateManager: TemplateManager

    /**
     *	@param type:    栏目类别，不可为空
     *	@param catalog: 栏目别名，可以为空
     *	@param post: 	 内容Id或别名，不可为空
     *						以_开头标识Id，
     *						以@开头标识别名，
     *						不以_或@开头，则判断是否为纯数字，是则为Id，否则为别名
     *	@param view:	模板名称
     **/
    @GetMapping(path = ["/post/{type}/{catalog}/{post}", "/post/{type}/{post}"])
    fun getTemplatePage(
        @PathVariable("type") type: String,
        @PathVariable(name = "catalog", required = false) catalog: String?,
        @PathVariable("post") post: String,
        view: String?,
        model: Model,
    ): String? {
        // 获取postEntity
        val postEntity = parsePostPathVariable(post).let {
            cmsPostService.getPostInfoEx(catalog, type, it.id, it.alias)
        }

        if (postEntity.content == null) {
            postEntity.content = ""
        }

        // 设置模板参数
        model.apply {
            addAttribute("article", postEntity)
            addAttribute("publishTime", formatter.format(postEntity.createTime))
        }

        // 不传递栏目别名参数时，尝试获取与文章绑定的主栏目别名
        val catalogAlias = catalog ?: postEntity.catalogs[0].alias

        // 返回模板
        return templateManager.getTemplate(type, catalogAlias, postEntity.postId.toString(), postEntity.alias, view)
    }

    private fun parsePostPathVariable(post: String): PostPathVariable {
        return when (post[0]) {
            '_' -> {
                PostPathVariable(post.substring(1).toInt(), null)
            }

            '@' -> {
                PostPathVariable(null, post.substring(1))
            }

            else -> {
                if (("^[0-9]*$").toRegex().matches(post)) PostPathVariable(post.toInt(), null)
                else PostPathVariable(null, post)
            }
        }
    }

    class PostPathVariable(val id: Int?, val alias: String?)

    companion object {
        private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    }
}
