/**
 * 通知工具类
 * 支持钉钉、企业微信通知
 * 遵循阿里开发手册、大厂CI/CD标准
 * 
 * @param config 通知配置
 *   - type: 通知类型 (dingtalk/wecom)
 *   - webhook: 通知Webhook地址
 *   - title: 通知标题
 *   - message: 通知内容
 *   - status: 构建状态 (SUCCESS/FAILURE)
 */
def call(Map config = [:]) {
    // 默认配置
    def type = config.type ?: 'dingtalk'
    def webhook = config.webhook ?: env.NOTIFICATION_WEBHOOK
    def title = config.title ?: "构建通知"
    def message = config.message ?: ""
    def status = config.status ?: "UNKNOWN"
    
    if (!webhook) {
        echo "⚠️ 未配置通知Webhook，跳过通知"
        return
    }
    
    echo "📧 发送${type}通知..."
    
    if (type == 'dingtalk') {
        sendDingtalkNotification(webhook, title, message, status)
    } else if (type == 'wecom') {
        sendWecomNotification(webhook, title, message, status)
    } else {
        echo "⚠️ 不支持的通知类型: ${type}"
    }
}

/**
 * 发送钉钉通知
 */
def sendDingtalkNotification(String webhook, String title, String message, String status) {
    def statusEmoji = status == 'SUCCESS' ? '✅' : (status == 'FAILURE' ? '❌' : '⚠️')
    def statusColor = status == 'SUCCESS' ? '#00FF00' : (status == 'FAILURE' ? '#FF0000' : '#FFFF00')
    
    def payload = """
        {
            "msgtype": "markdown",
            "markdown": {
                "title": "${title}",
                "text": "## ${statusEmoji} ${title}\\n\\n**状态**: ${status}\\n\\n**构建号**: ${env.BUILD_NUMBER}\\n\\n**项目**: ${env.JOB_NAME}\\n\\n**时间**: ${new Date().format('yyyy-MM-dd HH:mm:ss')}\\n\\n**详情**: [查看日志](${env.BUILD_URL})\\n\\n**消息**: ${message}"
            },
            "at": {
                "isAtAll": ${status == 'FAILURE'}
            }
        }
    """
    
    sh """
        curl -X POST ${webhook} \
            -H 'Content-Type: application/json' \
            -d '${payload}'
    """
}

/**
 * 发送企业微信通知
 */
def sendWecomNotification(String webhook, String title, String message, String status) {
    def statusEmoji = status == 'SUCCESS' ? '✅' : (status == 'FAILURE' ? '❌' : '⚠️')
    
    def payload = """
        {
            "msgtype": "text",
            "text": {
                "content": "${statusEmoji} ${title}\\n状态: ${status}\\n构建号: ${env.BUILD_NUMBER}\\n项目: ${env.JOB_NAME}\\n时间: ${new Date().format('yyyy-MM-dd HH:mm:ss')}\\n消息: ${message}\\n详情: ${env.BUILD_URL}"
            }
        }
    """
    
    sh """
        curl -X POST ${webhook} \
            -H 'Content-Type: application/json' \
            -d '${payload}'
    """
}