package com.lanyuanxiaoyao.digtal.market.sender

import cn.hutool.http.HttpUtil
import cn.hutool.json.JSONUtil
import com.lanyuanxiaoyao.digtal.market.Article
import org.slf4j.LoggerFactory

class WxPusherSender : Sender {
    private val logger = LoggerFactory.getLogger(javaClass)

    override fun send(title: String, content: Map<String, Any>) {
        val articles = content["articles"] as List<Article>?
        if (articles.isNullOrEmpty()) {
            logger.warn("Articles is not found")
            return
        }
        val response = HttpUtil
            .createPost("https://wxpusher.zjiecode.com/api/send/message")
            .body(
                JSONUtil.toJsonStr(
                    mapOf(
                        "appToken" to "AT_7gtCYQ2bW2wlFYYdEZDdgsUcf1gSd7hR",
                        // language=HTML
                        "content" to "<h2>要闻集合</h2>\n${articles.joinToString("\n") { "<b><a href=\"${it.url}\">${it.title}</a></b><br/><div style=\"margin-top: 5px;padding-left: 5px;padding-bottom: 5px;border-left: 3px solid #0d0c0c\">${it.description}</div><br/>" }}",
                        "summary" to title,
                        "contentType" to 2,
                        "topicIds" to listOf("35482"),
                        "verifyPayType" to 0,
                    )
                )
            )
            .execute()
        if (response.isOk.not() || JSONUtil.parseObj(response.body()).getInt("code", -1) != 1000) {
            throw RuntimeException(try {
                response.body()
            } catch (e: Exception) {
                e.message
            })
        }
    }
}