<?php
/**
 * 智能全能转链工具（京东+淘宝）
 * 自动识别消息类型，调用相应API，返回转换后的消息
 */

// 京东API配置（京品库）
$jd_config = [
    'api_url' => 'https://api.jingpinku.com/get_atip_link/api',
    'appid' => '2501202338186703',
    'appkey' => '1AFfGo6zZl1Mh8AzFgw7Qy2Hvq43u3Xb',
    'union_id' => '2035327602'
];

// 淘宝API配置（折淘客）
$tb_config = [
    'api_url' => 'https://api.zhetaoke.com:10001/api/open_gaoyongzhuanlian_tkl_piliang.ashx',
    'appkey' => '3d0ab606c44b40798b184e7c6c37b692',
    'sid' => '182920',
    'pid' => 'mm_5982833652_3185450118_115865050350',
    'unionId' => '' // 京东联盟ID，淘宝可为空
];

// 处理表单提交
$originalMessage = '';
$processedMessage = '';
$error = '';
$conversionType = ''; // 记录转换类型：jd、tb 或 none
$conversionDetails = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $originalMessage = trim($_POST['message']);
    
    if (!empty($originalMessage)) {
        
        // ========== 京东转链函数 ==========
        function callJdApi($message, $config) {
            $params = [
                'appid' => $config['appid'],
                'appkey' => $config['appkey'],
                'union_id' => $config['union_id'],
                'content' => $message
            ];
            
            $apiUrl = $config['api_url'] . '?' . http_build_query($params);
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $apiUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_TIMEOUT => 8,
                CURLOPT_USERAGENT => 'Mozilla/5.0'
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode != 200) {
                return ['success' => false, 'error' => "京东API请求失败 (HTTP $httpCode)"];
            }
            
            $result = json_decode($response, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return ['success' => false, 'error' => '京东API返回了无效JSON'];
            }
            
            // 检查并返回content字段
            if (isset($result['content']) && is_string($result['content']) && !empty(trim($result['content']))) {
                $content = trim($result['content']);
                return ['success' => true, 'content' => $content, 'raw' => $result];
            }
            
            return ['success' => false, 'error' => '京东API未返回有效content'];
        }
        
        // ========== 淘宝转链函数 ==========
        function callTbApi($message, $config) {
            $params = [
                'appkey' => $config['appkey'],
                'sid' => $config['sid'],
                'pid' => $config['pid'],
                'unionId' => $config['unionId'],
                'tkl' => $message
            ];
            
            $apiUrl = $config['api_url'] . '?' . http_build_query($params);
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $apiUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_TIMEOUT => 8,
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode != 200) {
                return ['success' => false, 'error' => "淘宝API请求失败 (HTTP $httpCode)"];
            }
            
            $result = json_decode($response, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return ['success' => false, 'error' => '淘宝API返回了无效JSON'];
            }
            
            // 处理括号合并
            function mergeParenthesis($str) {
                $result = '';
                $prev = '';
                for ($i = 0; $i < strlen($str); $i++) {
                    $c = $str[$i];
                    if ($c === '(' || $c === ')') {
                        if ($prev === $c) {
                            continue;
                        } else {
                            $prev = $c;
                            $result = str_replace('()', '', $result) . $c;
                        }
                    } else {
                        $prev = '';
                        $result .= $c;
                    }
                }
                return str_replace('()', '', $result);
            }
            
            // 检查并返回content字段
            if (isset($result['content']) && is_string($result['content'])) {
                $apiContent = $result['content'];
                
                // 检查是否包含错误信息
                if (strpos($apiContent, '转链失败') !== false || strpos($apiContent, '请填写准确的') !== false) {
                    return ['success' => false, 'error' => '淘宝转链失败: ' . substr($apiContent, 0, 50)];
                }
                
                $content = mergeParenthesis($apiContent);
                return ['success' => true, 'content' => $content, 'raw' => $result];
            }
            
            return ['success' => false, 'error' => '淘宝API未返回有效content'];
        }
        
        // ========== 智能判断函数 ==========
        // 比较两个结果，选择最可能正确的一个
        function smartSelectResult($original, $jdResult, $tbResult, &$type, &$details) {
            $details = ['jd' => $jdResult, 'tb' => $tbResult];
            
            // 情况1: 只有京东成功
            if ($jdResult['success'] && !$tbResult['success']) {
                $type = 'jd';
                return $jdResult['content'];
            }
            
            // 情况2: 只有淘宝成功
            if (!$jdResult['success'] && $tbResult['success']) {
                $type = 'tb';
                return $tbResult['content'];
            }
            
            // 情况3: 两个都成功，需要智能判断
            if ($jdResult['success'] && $tbResult['success']) {
                $jdContent = $jdResult['content'];
                $tbContent = $tbResult['content'];
                
                // 计算与原始消息的相似度（简单版：比较字符变化）
                $jdSimilarity = similar_text($original, $jdContent);
                $tbSimilarity = similar_text($original, $tbContent);
                
                // 计算变化程度（变化越大，说明转链可能越成功）
                $jdChange = strlen($jdContent) - strlen($original);
                $tbChange = strlen($tbContent) - strlen($original);
                
                // 启发式判断：
                // 1. 如果京东结果包含典型京东链接模式
                if (preg_match('/https:\/\/(u\.jd\.com|item\.jd\.com|union-click\.jd\.com)/', $jdContent)) {
                    $type = 'jd';
                    $details['reason'] = '检测到京东链接模式';
                    return $jdContent;
                }
                
                // 2. 如果淘宝结果包含典型淘宝链接或口令模式
                if (preg_match('/https:\/\/(s\.click\.taobao\.com|uland\.taobao\.com)/', $tbContent) || 
                    preg_match('/[￥¥€][a-zA-Z0-9]{8,}[￥¥€]/', $tbContent)) {
                    $type = 'tb';
                    $details['reason'] = '检测到淘宝链接/口令模式';
                    return $tbContent;
                }
                
                // 3. 默认选择变化更大的（绝对值）
                if (abs($jdChange) > abs($tbChange)) {
                    $type = 'jd';
                    $details['reason'] = '京东结果变化更大';
                    return $jdContent;
                } else {
                    $type = 'tb';
                    $details['reason'] = '淘宝结果变化更大';
                    return $tbContent;
                }
            }
            
            // 情况4: 两个都失败
            $type = 'none';
            $details['error'] = '京东和淘宝API均未返回有效结果';
            return $original;
        }
        
        // ========== 主处理流程 ==========
        // 并行调用两个API
        $jdResult = callJdApi($originalMessage, $jd_config);
        $tbResult = callTbApi($originalMessage, $tb_config);
        
        // 智能选择结果
        $processedMessage = smartSelectResult($originalMessage, $jdResult, $tbResult, $conversionType, $conversionDetails);
        
        // 如果没有变化，返回原始消息
        if ($processedMessage === $originalMessage) {
            $conversionType = 'none';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能全能转链工具（京东+淘宝）</title>
    <style>
        body { font-family: 'Microsoft YaHei', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0; padding: 20px; min-height: 100vh; }
        .container { max-width: 1000px; margin: 20px auto; background: white; border-radius: 15px; box-shadow: 0 20px 40px rgba(0,0,0,0.15); overflow: hidden; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px 35px; text-align: center; }
        .header h1 { margin: 0; font-size: 28px; font-weight: 600; }
        .header p { margin: 10px 0 0; opacity: 0.95; font-size: 16px; }
        .content { padding: 35px; }
        
        /* 平台标识样式 */
        .platform-badge { display: inline-block; padding: 6px 15px; border-radius: 20px; font-size: 14px; font-weight: bold; margin-left: 10px; }
        .platform-jd { background: #e4393c; color: white; }
        .platform-tb { background: #ff4400; color: white; }
        .platform-none { background: #95a5a6; color: white; }
        
        .config-display { background: #f8f9fa; border-radius: 10px; padding: 25px; margin: 25px 0; border: 1px solid #e9ecef; }
        .config-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 15px; }
        .config-item { background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .config-label { font-size: 13px; color: #6c757d; margin-bottom: 5px; }
        .config-value { font-weight: 600; word-break: break-all; }
        
        .form-group { margin-bottom: 30px; }
        label { display: block; margin-bottom: 12px; font-weight: 600; color: #343a40; font-size: 16px; }
        textarea { width: 100%; min-height: 200px; padding: 18px; border: 2px solid #dee2e6; border-radius: 10px; font-size: 15px; line-height: 1.6; resize: vertical; transition: all 0.3s; }
        textarea:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        
        .btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 15px 40px; border-radius: 10px; font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s; display: block; width: 100%; }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3); }
        .center { text-align: center; margin: 30px 0; }
        
        .result-container { margin-top: 30px; }
        .result-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .result-type { font-size: 18px; font-weight: 600; color: #343a40; }
        
        .result-box { background: #f8f9fa; border: 2px solid #e9ecef; border-radius: 10px; padding: 25px; white-space: pre-wrap; word-wrap: break-word; font-size: 15px; line-height: 1.7; min-height: 150px; }
        .copy-btn { background: linear-gradient(135deg, #4cd964 0%, #5ac8fa 100%); margin-top: 20px; }
        .copy-btn:hover { background: linear-gradient(135deg, #44b854 0%, #4ab0e6 100%); }
        
        .status-box { padding: 20px; border-radius: 10px; margin: 25px 0; }
        .status-success { background: #d4edda; border: 1px solid #c3e6cb; color: #155724; }
        .status-info { background: #d1ecf1; border: 1px solid #bee5eb; color: #0c5460; }
        .status-warning { background: #fff3cd; border: 1px solid #ffeaa7; color: #856404; }
        
        .api-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 25px; }
        .api-result-item { background: white; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; }
        .api-result-title { font-weight: 600; margin-bottom: 10px; color: #495057; }
        .api-status { display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: bold; }
        .status-ok { background: #d4edda; color: #155724; }
        .status-error { background: #f8d7da; color: #721c24; }
        
        @media (max-width: 768px) {
            .container { margin: 10px; }
            .content { padding: 25px; }
            .config-grid { grid-template-columns: 1fr; }
            .api-results { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 智能全能转链工具</h1>
            <p>自动识别京东/淘宝消息，智能选择最佳转链结果</p>
        </div>
        
        <div class="content">
            <div class="config-display">
                <h3 style="margin-top: 0; color: #495057;">🔧 当前配置</h3>
                <div class="config-grid">
                    <div class="config-item">
                        <div class="config-label">京东联盟ID</div>
                        <div class="config-value"><?php echo htmlspecialchars($jd_config['union_id']); ?></div>
                    </div>
                    <div class="config-item">
                        <div class="config-label">淘宝PID</div>
                        <div class="config-value"><?php echo htmlspecialchars($tb_config['pid']); ?></div>
                    </div>
                </div>
                <div style="margin-top: 15px; font-size: 14px; color: #6c757d;">
                    💡 工具会自动调用京东和淘宝API，并智能选择正确的转链结果。
                </div>
            </div>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label>📝 粘贴需要转链的消息（京东或淘宝）</label>
                    <textarea name="message" placeholder="请粘贴包含京东或淘宝推广链接/口令的完整消息...

京东示例：
【15点】生鲜馆
生鲜馆（每天10点/15点/20点）
https://u.jd.com/ZGNrO38    
活动页面商品四选一领券抢购 
鸡蛋/果冻橙/烟薯/玉米粒

淘宝示例：
王小卤虎皮凤爪分享装520g，领礼金
详情页进入淘宝秒杀页面加购
合理凑单用59-9红包
拍1件vip+金币+10福袋【18.47】 
¥evzufuCJ2v8)/ MU918" required><?php echo htmlspecialchars($originalMessage); ?></textarea>
                </div>
                
                <div class="center">
                    <button type="submit" class="btn">🚀 开始智能转链</button>
                </div>
            </form>
            
            <?php if ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
                <div class="result-container">
                    
                    <!-- API调用结果 -->
                    <div class="api-results">
                        <div class="api-result-item">
                            <div class="api-result-title">京东API调用结果</div>
                            <div>
                                <span class="api-status <?php echo isset($conversionDetails['jd']) && $conversionDetails['jd']['success'] ? 'status-ok' : 'status-error'; ?>">
                                    <?php echo isset($conversionDetails['jd']) && $conversionDetails['jd']['success'] ? '成功' : '失败'; ?>
                                </span>
                                <?php if (isset($conversionDetails['jd']) && !$conversionDetails['jd']['success']): ?>
                                    <div style="margin-top: 10px; color: #721c24; font-size: 13px;">
                                        <?php echo htmlspecialchars($conversionDetails['jd']['error'] ?? '未知错误'); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="api-result-item">
                            <div class="api-result-title">淘宝API调用结果</div>
                            <div>
                                <span class="api-status <?php echo isset($conversionDetails['tb']) && $conversionDetails['tb']['success'] ? 'status-ok' : 'status-error'; ?>">
                                    <?php echo isset($conversionDetails['tb']) && $conversionDetails['tb']['success'] ? '成功' : '失败'; ?>
                                </span>
                                <?php if (isset($conversionDetails['tb']) && !$conversionDetails['tb']['success']): ?>
                                    <div style="margin-top: 10px; color: #721c24; font-size: 13px;">
                                        <?php echo htmlspecialchars($conversionDetails['tb']['error'] ?? '未知错误'); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 智能选择结果 -->
                    <?php if ($conversionType !== 'none'): ?>
                        <div class="status-box status-success">
                            <div style="display: flex; align-items: center; justify-content: space-between;">
                                <div>
                                    <strong>✅ 智能转链成功！</strong>
                                    <p>工具已自动识别为
                                        <?php if ($conversionType === 'jd'): ?>
                                            <span class="platform-badge platform-jd">京东</span>
                                        <?php elseif ($conversionType === 'tb'): ?>
                                            <span class="platform-badge platform-tb">淘宝</span>
                                        <?php endif; ?>
                                        消息并完成转链
                                    </p>
                                    <?php if (isset($conversionDetails['reason'])): ?>
                                        <p><small>判断依据：<?php echo htmlspecialchars($conversionDetails['reason']); ?></small></p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <div class="result-header">
                                <span class="result-type">📄 转换后的消息</span>
                                <?php if ($conversionType === 'jd'): ?>
                                    <span class="platform-badge platform-jd">京东</span>
                                <?php elseif ($conversionType === 'tb'): ?>
                                    <span class="platform-badge platform-tb">淘宝</span>
                                <?php endif; ?>
                            </div>
                            <div class="result-box" id="resultMessage"><?php echo htmlspecialchars($processedMessage); ?></div>
                        </div>
                        
                        <div class="center">
                            <button class="btn copy-btn" onclick="copyMessage()">📋 复制消息</button>
                        </div>
                        
                    <?php elseif ($conversionType === 'none'): ?>
                        <div class="status-box status-warning">
                            <strong>⚠️ 未检测到有效转链</strong>
                            <p>京东和淘宝API均未能成功转换此消息，已返回原始内容。</p>
                            <p><small>可能原因：消息中不包含有效的京东/淘宝链接，或API暂时不可用。</small></p>
                        </div>
                        
                        <div class="form-group">
                            <label>原始消息（未转换）：</label>
                            <div class="result-box"><?php echo htmlspecialchars($originalMessage); ?></div>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function copyMessage() {
            const resultElement = document.getElementById('resultMessage');
            const textToCopy = resultElement.textContent;
            
            navigator.clipboard.writeText(textToCopy).then(() => {
                const btn = event.target;
                const originalText = btn.textContent;
                btn.textContent = '✅ 已复制到剪贴板';
                btn.style.opacity = '0.9';
                
                setTimeout(() => {
                    btn.textContent = originalText;
                    btn.style.opacity = '1';
                }, 2000);
            }).catch(err => {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = textToCopy;
                document.body.appendChild(textArea);
                textArea.select();
                
                try {
                    document.execCommand('copy');
                    const btn = event.target;
                    const originalText = btn.textContent;
                    btn.textContent = '✅ 已复制到剪贴板';
                    btn.style.opacity = '0.9';
                    
                    setTimeout(() => {
                        btn.textContent = originalText;
                        btn.style.opacity = '1';
                    }, 2000);
                } catch (err) {
                    alert('复制失败，请手动选择文本复制。');
                }
                
                document.body.removeChild(textArea);
            });
        }
        
        // 自动调整文本框高度
        const textarea = document.querySelector('textarea[name="message"]');
        if (textarea) {
            textarea.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = (this.scrollHeight) + 'px';
            });
            // 初始调整
            setTimeout(() => {
                textarea.style.height = 'auto';
                textarea.style.height = (textarea.scrollHeight) + 'px';
            }, 100);
        }
    </script>
</body>
</html>