package com.lanyuanxiaoyao.digtal.market.sender

import cn.hutool.core.net.URLEncodeUtil
import cn.hutool.crypto.SecureUtil
import cn.hutool.http.HttpUtil
import cn.hutool.json.JSONUtil
import com.lanyuanxiaoyao.digtal.market.Article
import java.time.Instant
import org.slf4j.LoggerFactory

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

    private val token = "b94c298e2230e5a4931ad9b36052251229cebbc642af7b6360076cfb3d68b043"
    private val secret = "SECb2bcb67ef661cb3f11105eb79f67a721a6b480c7d2c60cb573501cb40c5263fa"

    override fun send(title: String, content: Map<String, Any>) {
        val timestamp = Instant
            .now()
            .toEpochMilli()
        val signText = "$timestamp\n$secret"
        val sign = URLEncodeUtil.encodeQuery(
            SecureUtil
                .hmacSha256(secret)
                .digestBase64(signText, Charsets.UTF_8, false), Charsets.UTF_8
        )
        logger.info("{}", sign)

        val articles = content["articles"] as List<Article>?
        if (articles.isNullOrEmpty()) {
            logger.warn("Articles is not found")
            return
        }
        val text = "# 要闻集合\n${articles.joinToString("\n") { "**[${it.title}](${it.url})**  \n> ${it.description}\n" }}"

        val response = HttpUtil
            .createPost("https://oapi.dingtalk.com/robot/send?access_token=${token}&timestamp=${timestamp}&sign=${sign}")
            .body(
                JSONUtil.toJsonStr(
                    mapOf(
                        "msgtype" to "markdown",
                        "markdown" to mapOf(
                            "title" to title,
                            "text" to text,
                        )
                    )
                )
            )
            .execute()
        if (response.isOk.not() || JSONUtil.parseObj(response.body()).getInt("errcode", -1) != 0) {
            throw RuntimeException(try {
                response.body()
            } catch (e: Exception) {
                e.message
            })
        }
    }
}