<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拼多多智能定价计算器 v2.1 - 全链路利润与ROI分析 · 数据互推引擎</title>
    
    <!-- SEO Meta Tags -->
    <meta name="description" content="专为拼多多商家设计的终极定价工具。支持反向推导售价、计算真实ROI、预估退货损耗、优惠券/多多进宝/活动扣点、广告费上限，以及『已知部分数据互推其余数据』（售价/投产比/广告费/利润互相推算）。全链路成本核算精准控利润。">
    <meta name="keywords" content="拼多多定价计算器,电商利润计算,拼多多ROI计算,优惠券成本,多多进宝佣金,电商定价公式,拼多多运营工具,反向定价">
    <meta name="author" content="E-commerce Tools">
    <meta name="robots" content="index, follow">
    <meta name="baidu-site-verification" content="codeva-56OgjtKG9Z" />
    <style>
        :root {
            --primary: #e02e24; /* Pinduoduo Red */
            --primary-hover: #c5261d;
            --success: #00b578;
            --warning: #ff9f1c;
            --danger: #f53f3f;
            --bg: #f4f4f4;
            --card-bg: #ffffff;
            --text-main: #333333;
            --text-sub: #666666;
            --border: #eeeeee;
            --shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

        * { box-sizing: border-box; }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: var(--bg);
            color: var(--text-main);
            margin: 0;
            padding: 0;
            line-height: 1.6;
        }

        /* Header Section */
        header {
            background: linear-gradient(135deg, #e02e24 0%, #ff6b6b 100%);
            color: white;
            padding: 20px 0;
            text-align: center;
            box-shadow: 0 2px 10px rgba(224, 46, 36, 0.2);
        }

        header h1 { margin: 0; font-size: 24px; font-weight: 700; }
        header p { margin: 5px 0 0; font-size: 14px; opacity: 0.9; }

        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 15px;
            display: grid;
            grid-template-columns: 380px 1fr;
            gap: 20px;
            align-items: start;
        }

        @media (max-width: 900px) {
            .container { grid-template-columns: 1fr; }
        }

        /* Module Cards */
        .module-card {
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: var(--shadow);
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid var(--border);
        }

        .module-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border);
        }

        .module-icon {
            width: 32px;
            height: 32px;
            background: #fff0f0;
            color: var(--primary);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-size: 16px;
        }

        .module-title { font-size: 16px; font-weight: 600; color: var(--text-main); }

        /* Form Elements */
        .form-group { margin-bottom: 12px; }
        
        label {
            display: block;
            font-size: 13px;
            color: var(--text-sub);
            margin-bottom: 5px;
        }

        .input-wrapper { position: relative; display: flex; align-items: center; gap:10px; }

        input, select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.2s;
            outline: none;
        }

        input:focus, select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(224, 46, 36, 0.1);
        }

        .unit-select {
            width: 118px !important;
            flex-shrink:0;
        }

        .suffix {
            position: absolute;
            right: 12px;
            color: #999;
            font-size: 12px;
            pointer-events: none;
        }

        .auto-input {
            background-color: #f9f9f9;
            color: #666;
            cursor: not-allowed;
        }

        /* Tabs */
        .tabs-container {
            display: flex;
            background: #f0f0f0;
            padding: 4px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .tab-item {
            flex: 1;
            text-align: center;
            padding: 8px 0;
            font-size: 13px;
            cursor: pointer;
            border-radius: 6px;
            color: #666;
            transition: all 0.3s;
            font-weight: 500;
        }

        .tab-item.active {
            background: white;
            color: var(--primary);
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            font-weight: 600;
        }

        /* Results Area */
        .result-panel {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid var(--border);
        }

        .result-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-top: 10px;
        }

        .result-item {
            background: #fafafa;
            padding: 12px;
            border-radius: 8px;
            border: 1px solid #eee;
        }

        .result-label { font-size: 12px; color: #888; margin-bottom: 4px; }
        
        .result-value {
            font-size: 18px;
            font-weight: 700;
            font-family: 'SF Mono', Monaco, monospace;
        }

        .val-green { color: var(--success); }
        .val-red { color: var(--danger); }
        .val-primary { color: var(--primary); }
        .val-warning { color: var(--warning); }

        .big-result {
            grid-column: span 2;
            background: linear-gradient(to right, #fff0f0, #fff);
            border: 1px solid #ffccc7;
            text-align: center;
            padding: 15px;
        }

        .big-result .result-value { font-size: 28px; }

        /* Profit Status Banner */
        .profit-banner {
            display: flex; align-items: center; gap: 8px;
            border-radius: 8px; padding: 10px 14px; font-size: 13px; margin-bottom: 12px;
        }
        .profit-banner .pb-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
        .profit-ok { background: #e6f7ef; color: #00a05c; border: 1px solid #b7ebd2; }
        .profit-ok .pb-dot { background: #00a05c; }
        .profit-warn { background: #fff7e6; color: #d48806; border: 1px solid #ffe58f; }
        .profit-warn .pb-dot { background: #d48806; }
        .profit-bad { background: #fff1f0; color: #cf1322; border: 1px solid #ffa39e; }
        .profit-bad .pb-dot { background: #cf1322; }

        /* Cost Breakdown Bar */
        .cost-bar-container {
            margin-top: 20px;
            height: 8px;
            background: #eee;
            border-radius: 4px;
            overflow: hidden;
            display: flex;
        }
        .bar-segment { height: 100%; }
        
        .legend {
            display: flex;
            flex-wrap: wrap;
            gap:6px;
            justify-content: space-between;
            font-size: 11px;
            color: #999;
            margin-top: 5px;
        }

        /* Helper Text */
        .helper-text {
            font-size: 12px;
            color: #999;
            margin-top: 4px;
            line-height: 1.4;
        }

        /* Guide Section Styles */
        .guide-section {
            max-width: 1200px;
            margin: 40px auto;
            padding: 0 15px;
        }

        .guide-card {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: var(--shadow);
            border: 1px solid var(--border);
        }

        .guide-title {
            font-size: 20px;
            font-weight: 700;
            color: var(--text-main);
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid var(--bg);
            display: flex;
            align-items: center;
        }
        
        .guide-title::before {
            content: '';
            display: inline-block;
            width: 6px;
            height: 24px;
            background: var(--primary);
            margin-right: 10px;
            border-radius: 3px;
        }

        .guide-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 30px;
        }

        .guide-block h4 {
            font-size: 16px;
            color: var(--primary);
            margin-bottom: 10px;
            font-weight: 600;
        }

        .guide-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .guide-list li {
            font-size: 14px;
            color: var(--text-sub);
            margin-bottom: 8px;
            padding-left: 15px;
            position: relative;
        }

        .guide-list li::before {
            content: '•';
            color: var(--primary);
            position: absolute;
            left: 0;
            font-weight: bold;
        }

        .note-box {
            background: #fffbe6;
            border: 1px solid #ffe58f;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            font-size: 13px;
            color: #d48806;
        }

        footer {
            text-align: center;
            padding: 30px 0;
            color: #999;
            font-size: 12px;
            border-top: 1px solid #eee;
            margin-top: 40px;
        }

        /* V1.1 & V2.0 Specific Styles */
        .v11-section {
            margin-top: 40px; 
            border-top: 2px dashed #e02e24; 
            padding-top: 30px;
        }
        
        .v11-card {
            background: var(--card-bg);
            border-radius: 8px;
            padding: 20px;
            box-shadow: var(--shadow);
            border: 1px solid var(--border);
        }

        .v11-card.red-border { border-left: 4px solid #e02e24; }
        .v11-card.orange-border { border-left: 4px solid #f59e0b; }
        .v11-card.green-border { border-left: 4px solid #10b981; }
        .v11-card.blue-border { border-left: 4px solid #3b82f6; }
        .v11-card.teal-border { border-left: 4px solid #14b8a6; }
        .v11-card.purple-border { border-left: 4px solid #8b5cf6; }
        .v11-card.cyan-border { border-left: 4px solid #06b6d4; }

        .v11-result-box {
            background: #fafafa;
            border-radius: 4px;
            padding: 12px;
            margin-top: 15px;
            font-size: 14px;
        }

        /* Modal */
        .mask {
            display:none;
            position:fixed;
            top:0;left:0;right:0;bottom:0;
            background:rgba(0,0,0,0.5);
            z-index:99;
            align-items:center;
            justify-content:center;
        }
        .mask.show {display:flex;}
        .detail-modal {
            width:90%;max-width:500px;
            background:#fff;border-radius:12px;padding:20px;
        }
        .detail-item {display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #eee;}
        .modal-btn {
            margin-top:15px;width:100%;padding:10px;border:none;border-radius:6px;background:var(--primary);color:#fff;cursor:pointer;
        }
        .btn-view-detail {
            padding:6px 12px;border:1px solid var(--primary);background:#fff;color:var(--primary);border-radius:6px;cursor:pointer;margin-bottom:10px;
        }
    </style>
</head>
<body>

<header>
    <h1>拼多多智能定价计算器 v2.1</h1>
    <p>全链路成本核算 · 优惠券/多多进宝/广告/退货损耗 · 投产比实时分析 · 数据互推引擎</p>
</header>

<div class="container">
    <!-- Left Column: Inputs -->
    <div class="left-col">
        
        <!-- Module 1: Product Cost -->
        <div class="module-card">
            <div class="module-header">
                <div class="module-icon">📦</div>
                <div class="module-title">商品基础成本</div>
            </div>
            
            <div class="form-group">
                <label>商品单位规格</label>
                <div class="input-wrapper">
                    <input type="number" id="weight" value="1" step="0.01" min="0.01" oninput="calculateAll()">
                    <select id="weightUnit" class="unit-select" onchange="unitChangeSync()">
                        <option value="g">克(g)</option>
                        <option value="kg" selected>千克(kg)</option>
                        <option value="jin">斤</option>
                        <option value="piece">个</option>
                        <option value="slice">片</option>
                        <option value="bag">袋</option>
                        <option value="box">盒</option>
                        <option value="bottle">瓶</option>
                    </select>
                </div>
                <div class="helper-text">计件商品(个/片/袋)单份重量固定为1；计重商品填写实际克重/千克</div>
            </div>

            <div class="form-group">
                <label id="unitPriceLabel">货物单价 (元/kg)</label>
                <input type="number" id="unitPrice" value="20" step="0.1" min="0" oninput="calculateAll()">
            </div>

            <div class="form-group">
                <label>单件包材费 (元)</label>
                <input type="number" id="packagingCost" value="0.5" step="0.1" min="0" oninput="calculateAll()">
                <div class="helper-text">含纸箱、快递袋、胶带等费用</div>
            </div>

            <div class="form-group">
                <label>预计退货率 (%)</label>
                <input type="number" id="returnRate" value="5" step="1" min="0" max="100" oninput="calculateAll()">
                <div class="helper-text">自动分摊正向+逆向退货运费损耗</div>
            </div>

            <div class="form-group">
                <label>单件退货运费(逆向) (元)</label>
                <input type="number" id="returnShipFee" value="2.5" step="0.1" min="0" oninput="calculateAll()">
                <div class="helper-text">买家退货产生的快递成本，平摊到每单</div>
            </div>
        </div>

        <!-- Module 2: Logistics -->
        <div class="module-card">
            <div class="module-header">
                <div class="module-icon">🚚</div>
                <div class="module-title">快递运费设置</div>
            </div>
            
            <div class="form-group">
                <label>首重 (KG) / 价格 (元)</label>
                <div style="display: flex; gap: 10px;">
                    <input type="number" id="firstWeight" value="1" placeholder="首重" min="0.01" oninput="calculateShipping()">
                    <input type="number" id="firstPrice" value="3.5" placeholder="首重价" min="0" oninput="calculateShipping()">
                </div>
            </div>

            <div class="form-group">
                <label>续重 (元/KG)</label>
                <input type="number" id="extraPrice" value="1.5" step="0.1" min="0" oninput="calculateShipping()">
            </div>

            <div class="form-group">
                <label>偏远地区单件加价 (元)</label>
                <input type="number" id="remoteAdd" value="0" step="0.1" min="0" oninput="calculateShipping()">
                <div class="helper-text">新疆西藏等偏远平均加价，无则填0</div>
            </div>

            <div class="helper-text" id="shippingDetail" style="color: var(--primary);">
                当前基础发货运费: 0.00 元
            </div>
        </div>

        <!-- Module 3: Platform & Sales -->
        <div class="module-card">
            <div class="module-header">
                <div class="module-icon">⚙️</div>
                <div class="module-title">平台/活动/推广成本</div>
            </div>
            
            <div class="form-group">
                <label>平台技术服务费 (%)</label>
                <input type="number" id="platformFee" value="0.6" step="0.01" min="0" max="100" oninput="calculateAll()">
            </div>

            <div class="form-group">
                <label>多多进宝佣金比例 (%)</label>
                <input type="number" id="ddjbRate" value="0" step="0.1" min="0" max="100" oninput="calculateAll()">
                <div class="helper-text">达人分销佣金，无则填0</div>
            </div>

            <div class="form-group">
                <label>单件固定优惠券金额 (元)</label>
                <input type="number" id="couponPrice" value="0" step="0.1" min="0" oninput="calculateAll()">
                <div class="helper-text">店铺券/平台券，每单固定抵扣金额</div>
            </div>

            <div class="form-group">
                <label>活动满减平均分摊 (元/件)</label>
                <input type="number" id="promoCost" value="0" step="0.1" min="0" oninput="calculateAll()">
                <div class="helper-text">大促满减、秒杀折扣平均单件损耗</div>
            </div>

            <div class="form-group">
                <label>月销量预估 (件)</label>
                <input type="number" id="salesVolume" value="1000" min="1" oninput="calculateAll()">
            </div>
        </div>
    </div>

    <!-- Right Column: Engine -->
    <div class="right-col">
        <div class="module-card">
            <div class="module-header">
                <div class="module-icon">🧮</div>
                <div class="module-title">智能定价引擎</div>
            </div>

            <div class="tabs-container">
                <div class="tab-item active" onclick="setMode('profit')" id="tab-profit">算利润/ROI</div>
                <div class="tab-item" onclick="setMode('price')" id="tab-price">反推目标售价</div>
                <div class="tab-item" onclick="setMode('ad')" id="tab-ad">计算广告上限</div>
                <div class="tab-item" onclick="setMode('coupon')" id="tab-coupon">优惠券后定价</div>
            </div>

            <div id="dynamicInputs" style="margin-bottom: 20px;">
                <!-- Dynamic Inputs Injected Here -->
            </div>

            <button class="btn-view-detail" onclick="showCostDetail()">查看完整成本明细</button>

            <div class="result-panel">
                <h3 style="margin: 0 0 15px 0; font-size: 16px; color: #333;">📊 测算结果</h3>

                <div id="profitBanner" class="profit-banner profit-ok">
                    <span class="pb-dot"></span><span id="profitBannerText">加载中…</span>
                </div>

                <div class="result-grid">
                    <div class="big-result">
                        <div class="result-label">实际投产比（交易额 ÷ 成交花费）· 推广前台ROI</div>
                        <div class="result-value val-primary" id="res-sale-roi">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">商品标价(原价)</div>
                        <div class="result-value" id="res-price">-</div>
                    </div>
                    
                    <div class="result-item">
                        <div class="result-label">券后实收单价</div>
                        <div class="result-value val-warning" id="res-real-sale">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">单件毛利（未扣广告）</div>
                        <div class="result-value" id="res-gross-profit">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">单件净利润</div>
                        <div class="result-value" id="res-profit">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">净利润率</div>
                        <div class="result-value" id="res-margin">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">无广告保本价</div>
                        <div class="result-value" id="res-breakeven-noad">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">含广告保本价</div>
                        <div class="result-value" id="res-breakeven-ad">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">毛利净投产ROI（广告保本核心）</div>
                        <div class="result-value" id="res-net-roi">-</div>
                    </div>

                    <div class="result-item">
                        <div class="result-label">结算投产比（含退款，官方口径）</div>
                        <div class="result-value val-warning" id="res-settle-roi">-</div>
                    </div>
                </div>

                <!-- Visual Cost Breakdown -->
                <div style="margin-top: 20px;">
                    <div class="result-label">成本构成可视化（以标价为基数）</div>
                    <div class="cost-bar-container" id="costBar">
                        <!-- Segments injected by JS -->
                    </div>
                    <div class="legend">
                        <span>🟥 货款+包材</span>
                        <span>🟦 快递分摊</span>
                        <span>🟨 平台佣金</span>
                        <span>🟫 多多进宝</span>
                        <span>🟪 优惠券/活动</span>
                        <span>⬛ 广告</span>
                        <span>🟩 纯利润</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ========================================== -->
<!-- 【v1.1 新增区块开始】 高级运营场景测试模块 -->
<!-- ========================================== -->
<section class="guide-section v11-section">
    <h2 style="color: #e02e24; margin-bottom: 20px; font-size: 20px; font-weight: 700;">🚀 高级运营场景测试模块</h2>
    <p style="margin-bottom: 20px; color: #666; font-size: 14px;">以下模块直接引用左侧基础参数，实时联动计算。</p>
    
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
        
        <!-- 1. 全站推广反推定价 -->
        <div class="v11-card red-border">
            <h3 style="font-size: 16px; margin-bottom: 10px;">🎯 全站推广反推售价</h3>
            <p style="font-size: 12px; color: #666; margin-bottom: 15px;">已知目标ROI，计算建议售价<br>(已含退货损耗、优惠券、活动与平台扣点)</p>
            <div class="form-group">
                <label>目标 ROI (例如: 5)</label>
                <input type="number" id="v11-target-roi" value="5" step="0.1" oninput="calcV11_RoiPricing()">
            </div>
            <div class="form-group">
                <label>目标单件净利润 (元，保本填0)</label>
                <input type="number" id="v11-target-profit" value="0" step="0.1" oninput="calcV11_RoiPricing()">
            </div>
            <div class="v11-result-box" style="background: #fff5f5; border: 1px solid #ffccc7;">
                <div>建议标价: <strong id="v11-res-price" style="color:#e02e24; font-size: 18px;">-</strong></div>
                <div style="font-size:11px; color:#888; margin-top:5px;">
                    * 此时单件广告费 ≈ <span id="v11-res-ad">-</span> 元，广告费占交易额 <span id="v11-ad-ratio">-</span>%
                </div>
            </div>
        </div>

        <!-- 2. 保本投产比测算 -->
        <div class="v11-card orange-border">
            <h3 style="font-size: 16px; margin-bottom: 10px;">🛡️ 保本投产比测算</h3>
            <p style="font-size: 12px; color: #666; margin-bottom: 15px;">计算不亏钱的最低ROI阈值</p>
            <div class="form-group">
                <label>当前测试售价 (元)</label>
                <input type="number" id="v11-breakeven-price" value="39.9" step="0.1" oninput="calcV11_Breakeven()">
            </div>
            <div class="v11-result-box" style="background: #fffbeb; border: 1px solid #ffe58f;">
                <div>保本 ROI: <strong id="v11-res-breakeven" style="color:#f59e0b; font-size: 18px;">-</strong></div>
                <div style="font-size:11px; color:#888; margin-top:5px;">
                    * 实际ROI低于此值即亏损
                </div>
            </div>
        </div>

        <!-- 3. 批量盈亏模拟 -->
        <div class="v11-card green-border">
            <h3 style="font-size: 16px; margin-bottom: 10px;">📊 批量盈亏模拟</h3>
            <p style="font-size: 12px; color: #666; margin-bottom: 15px;">输入销量与实际ROI，测算总利润</p>
            <div class="form-group">
                <label>预计销量 (单)</label>
                <input type="number" id="v11-sales-vol" value="1000" step="100" oninput="calcV11_Batch()">
            </div>
            <div class="form-group">
                <label>实际达成 ROI</label>
                <input type="number" id="v11-actual-roi" value="5" step="0.1" oninput="calcV11_Batch()">
            </div>
            <div class="v11-result-box" style="background: #f0fdf4; border: 1px solid #bbf7d0;">
                <div>预估总净利润: <strong id="v11-res-profit" style="color:#10b981; font-size: 18px;">-</strong></div>
                <div style="font-size:11px; color:#888; margin-top:5px;">
                    * 已扣除退货损耗与广告花费
                </div>
            </div>
        </div>

    </div>
</section>

<!-- ========================================== -->
<!-- 【v2.1 新增区块】 数据互推引擎（部分数据 → 推算其余） -->
<!-- ========================================== -->
<section class="guide-section v11-section">
    <h2 style="color: #e02e24; margin-bottom: 10px; font-size: 20px; font-weight: 700;">🧮 数据互推引擎</h2>
    <p style="margin-bottom: 20px; color: #666; font-size: 14px;">
        只填你手头已有的部分数据，自动推算其余关联数据。口径与拼多多推广后台一致：<br>
        <strong>交易额</strong>=直接交易额+间接交易额（单件按券后实收估算）｜<strong>实际投产比</strong>=交易额÷成交花费｜<strong>结算投产比</strong>=（交易额-退款交易额）÷成交花费。
        以下模块实时联动左侧基础参数。
    </p>

    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">

        <!-- 互推① 已知目标投产比 → 求售价与广告费 -->
        <div class="v11-card blue-border">
            <h3 style="font-size: 16px; margin-bottom: 6px;">① 已知投产比 → 求售价+广告费</h3>
            <p style="font-size: 12px; color: #666; margin-bottom: 12px;">已知成本、运费、扣点与目标投产比，反推标价与广告费（知道成本+扣点+投产比 → 推算广告费与销售价）</p>
            <div class="form-group">
                <label>目标实际投产比 (例如: 4)</label>
                <input type="number" id="mt1-roi" value="4" step="0.1" oninput="calcMutual1()">
            </div>
            <div class="form-group">
                <label>目标单件净利润 (元，保本填0)</label>
                <input type="number" id="mt1-profit" value="0" step="0.1" oninput="calcMutual1()">
            </div>
            <div class="v11-result-box" style="background:#eff6ff;border:1px solid #bfdbfe;">
                <div>建议标价: <strong id="mt1-res-price" style="color:#2563eb;font-size:17px;">-</strong></div>
                <div style="font-size:12px;color:#555;margin-top:3px;">券后实收 <span id="mt1-res-real">-</span> 元</div>
                <div style="font-size:12px;color:#555;margin-top:3px;">单件广告费(成交花费) <span id="mt1-res-ad">-</span> 元</div>
                <div style="font-size:12px;color:#555;margin-top:3px;">结算投产比(含退货率) <span id="mt1-res-settle">-</span></div>
            </div>
        </div>

        <!-- 互推② 已知售价+目标利润 → 求所需投产比 -->
        <div class="v11-card teal-border">
            <h3 style="font-size: 16px; margin-bottom: 6px;">② 已知售价+利润 → 求投产比</h3>
            <p style="font-size: 12px; color: #666; margin-bottom: 12px;">已知标价与目标利润，推算要达标所需的实际投产比与广告费上限</p>
            <div class="form-group">
                <label>当前测试标价 (元)</label>
                <input type="number" id="mt2-price" value="39.9" step="0.1" oninput="calcMutual2()">
            </div>
            <div class="form-group">
                <label>目标单件净利润 (元)</label>
                <input type="number" id="mt2-profit" value="5" step="0.1" oninput="calcMutual2()">
            </div>
            <div class="v11-result-box" style="background:#f0fdfa;border:1px solid #99f6e4;">
                <div>所需实际投产比: <strong id="mt2-res-roi" style="color:#0d9488;font-size:17px;">-</strong></div>
                <div style="font-size:12px;color:#555;margin-top:3px;">单件广告费上限 <span id="mt2-res-ad">-</span> 元</div>
                <div style="font-size:12px;color:#555;margin-top:3px;">结算投产比(含退货率) <span id="mt2-res-settle">-</span></div>
            </div>
        </div>

        <!-- 互推③ 已知售价+广告费 → 求投产比与利润 -->
        <div class="v11-card purple-border">
            <h3 style="font-size: 16px; margin-bottom: 6px;">③ 已知售价+广告费 → 求利润</h3>
            <p style="font-size: 12px; color: #666; margin-bottom: 12px;">已知标价与实际广告费，测算当前实际投产比与真实净利润（经营诊断）</p>
            <div class="form-group">
                <label>当前标价 (元)</label>
                <input type="number" id="mt3-price" value="39.9" step="0.1" oninput="calcMutual3()">
            </div>
            <div class="form-group">
                <label>单件实际广告费 (元)</label>
                <input type="number" id="mt3-ad" value="6" step="0.1" oninput="calcMutual3()">
            </div>
            <div class="v11-result-box" style="background:#faf5ff;border:1px solid #ddd6fe;">
                <div>实际投产比: <strong id="mt3-res-roi" style="color:#7c3aed;font-size:17px;">-</strong></div>
                <div style="font-size:12px;color:#555;margin-top:3px;">单件净利润 <span id="mt3-res-profit">-</span> 元</div>
                <div style="font-size:12px;color:#555;margin-top:3px;">券后净利润率 <span id="mt3-res-margin">-</span></div>
                <div style="font-size:12px;color:#555;margin-top:3px;">结算投产比(含退货率) <span id="mt3-res-settle">-</span></div>
            </div>
        </div>

    </div>

    <div class="note-box" style="margin-top:20px;">
        <strong>💡 三引擎自洽校验：</strong>同一套成本下，互推①得到的「售价+广告费」代入互推③，应还原出你设定的目标投产比与利润；
        互推②得到「所需投产比」代入互推①（利润=目标利润），应还原出你输入的售价。三者共用同一成本模型，可交叉验算。
    </div>
</section>

<!-- Guide Section -->
<div class="guide-section">
    <div class="guide-card">
        <div class="guide-title">功能说明与使用指南</div>
        
        <div class="guide-grid">
            <!-- Block 1: Core Logic -->
            <div class="guide-block">
                <h4>💡 核心计算逻辑</h4>
                <ul class="guide-list">
                    <li><strong>多规格单位支持：</strong>新增g、个、片、袋、盒、瓶，计件商品自动简化重量计算，单价单位同步联动切换。</li>
                    <li><strong>标准ROI口径：</strong>
                        <br/>1. 销售额广告ROI = 券后实收 ÷ 广告花费（顶部大数字，后台推广页面直接看到的ROI，仅做曝光参考）
                        <br/>2. 毛利净投产ROI = 单件毛利 ÷ 广告花费（广告保本核心，≥1广告投放不亏）
                    </li>
                    <li><strong>双向退货损耗分摊：</strong>同时计算发货运费+买家逆向退货运费，按退货率平摊到每单。</li>
                    <li><strong>全链路成本全覆盖：</strong>货款、包材、正向快递、逆向退货、平台服务费、多多进宝、优惠券、满减活动、广告推广费全部纳入。</li>
                </ul>
            </div>

            <!-- Block 2: Mode Explanation -->
            <div class="guide-block">
                <h4>🛠️ 四种模式用法</h4>
                <ul class="guide-list">
                    <li><strong>算利润/ROI：</strong>已知标价、优惠券、广告花费，查看毛利、真实净利润、双ROI，日常监控推广投产。</li>
                    <li><strong>反推目标售价：</strong>设定目标净利润+广告预算，自动算出需要标价多少才能达标，新品定价专用。</li>
                    <li><strong>计算广告上限：</strong>固定标价、保底利润，算出单票最高可承受广告费，大促冲量控制出价上限。</li>
                    <li><strong>优惠券后定价：</strong>固定券后实收、目标利润，反推前端标价，适合设置店铺券、平台券场景。</li>
                </ul>
            </div>

            <!-- Block 3: Important Notes -->
            <div class="guide-block">
                <h4>⚠️ 注意事项</h4>
                <ul class="guide-list">
                    <li><strong>平台佣金：</strong>普通类目0.6%，生鲜、虚拟、特殊类目费率不同，按需修改。本工具按「券后实收」计扣，与平台口径一致。</li>
                    <li><strong>多多进宝：</strong>分销佣金按成交实收比例扣除，高佣金商品利润压缩明显。</li>
                    <li><strong>退货成本：</strong>大件、易碎品逆向运费高，务必填写真实退货快递费，避免定价低估亏损。</li>
                    <li><strong>投产判断标准：</strong>毛利净投产ROI≥1，广告投放不亏损；实际投产比(交易额/花费)需结合毛利净投产判断是否保本；结算投产比已含退款损耗，最贴近真实盈利。</li>
                    <li><strong>数据隐私：</strong>本工具纯前端运行，所有数据仅在您的浏览器本地计算，不会上传至任何服务器，请放心使用。</li>
                </ul>
            </div>
        </div>

        <div class="note-box">
            <strong>📢 温馨提示：</strong>计算结果仅供参考，实际经营中还可能涉及活动扣点、多多进宝佣金、仅退款损耗等隐性成本，建议在最终定价时预留 3%-5% 的安全边际。
        </div>
    </div>
</div>

<!-- 成本明细弹窗 -->
<div class="mask" id="detailMask">
    <div class="detail-modal">
        <h3>单件完整成本明细</h3>
        <div id="detailContent"></div>
        <button class="modal-btn" onclick="hideCostDetail()">关闭</button>
    </div>
</div>

<footer>
    <p>© 2026 拼多多智能定价计算器 | 仅供内部参考，数据不构成经营投资建议 | <A href="https://beian.miit.gov.cn/" target=_blank>豫ICP备14004758号-4</a></p>
</footer>

<script>
    // ==========================================
    // 全局状态管理 (Global State)
    // ==========================================
    const state = {
        currentMode: 'profit',
        baseShipFee: 0, // 基础正向发货运费（含偏远加价）
        weightKg: 0,    // 统一换算后重量(kg)
        unitMap:{
            g:{label:'元/g',isWeight:true,ratio:0.001},
            kg:{label:'元/kg',isWeight:true,ratio:1},
            jin:{label:'元/斤',isWeight:true,ratio:0.5},
            piece:{label:'元/个',isWeight:false,ratio:1},
            slice:{label:'元/片',isWeight:false,ratio:1},
            bag:{label:'元/袋',isWeight:false,ratio:1},
            box:{label:'元/盒',isWeight:false,ratio:1},
            bottle:{label:'元/瓶',isWeight:false,ratio:1}
        },
        // 统一成本模型，所有计算共用
        cost: {
            goods: 0,        // 货款成本
            pack: 0,         // 包材
            shipBase: 0,     // 单次发货运费
            shipReturn: 0,   // 单次逆向退货运费
            returnRate: 0,   // 退货率小数
            platformRate:0,  // 平台费率小数
            ddjbRate:0,      // 多多进宝费率小数
            coupon:0,        // 单件优惠券固定金额
            promo:0,         // 活动满减分摊
            ad:0             // 单件广告花费
        },
        res: {
            price:0,         // 商品标价S
            realSale:0,      // 券后实收
            totalFixedCost:0,// 固定硬成本（货款+包材+分摊运费）
            commission:0,    // 平台佣金
            ddjbFee:0,       // 多多进宝佣金
            grossProfit:0,   // 单件毛利（未扣广告）
            netProfit:0,     // 单件净利润 = 毛利 - 广告
            saleROI:0,       // 销售额广告ROI = 券后实收 /广告
            netROI:0,        // 毛利净投产ROI =毛利 /广告（保本）
            breakEvenNoAd:0, // 无广告保本价
            breakEvenAd:0    // 含广告保本价
        }
    };

    window.onload = function() {
        // 修复：必须先 setMode 渲染当前模式的输入框，否则 calculateAll()/unitChangeSync()
        // 内部调用 recalculateModel() 会因读取不存在的模式输入框(input-price)而抛错，导致页面初始化为空。
        setMode('profit');
        unitChangeSync();
        calculateAll();
    };

    // 单位切换同步更新单价label
    function unitChangeSync(){
        const unit = document.getElementById('weightUnit').value;
        const labelText = state.unitMap[unit].label;
        document.getElementById('unitPriceLabel').innerText = `货物单价 (${labelText})`;
        calculateAll();
    }

    // ==========================================
    // 核心数据获取函数 (供 v1.0/v1.1/v2.0 共用)
    // ==========================================
    function getCoreData() {
        const data = state.cost;
        const r = data.returnRate;
        // 分摊运费：(发货运费 + 退货运费*退货率) / (1 - r)
        const shipAvg = (data.shipBase + data.shipReturn * r) / (1 - r || 0.0001);
        
        return {
            goodsCost: data.goods,
            packagingCost: data.pack,
            shippingFee: data.shipBase,
            effectiveCostPerUnit: data.goods + data.pack + shipAvg, // 含退货损耗的有效硬成本
            platformFee: data.platformRate,
            ddjbRate: data.ddjbRate,
            coupon: data.coupon,
            promo: data.promo,
            returnRate: r,
            weightInKg: state.weightKg
        };
    }

    function calculateAll() {
        const unit = document.getElementById('weightUnit').value;
        const unitInfo = state.unitMap[unit];
        const weightVal = parseFloat(document.getElementById('weight').value) || 0;

        // 区分计重/计件
        if(unitInfo.isWeight){
            state.weightKg = weightVal * unitInfo.ratio;
        }else{
            state.weightKg = 1; // 计件商品统一重量1，不参与续重计算
        }

        // 2. 基础商品硬成本
        state.cost.goods = weightVal * (parseFloat(document.getElementById('unitPrice').value) || 0);
        state.cost.pack = parseFloat(document.getElementById('packagingCost').value) || 0;

        // 3. 退货参数
        state.cost.returnRate = (parseFloat(document.getElementById('returnRate').value) || 0) / 100;
        state.cost.shipReturn = parseFloat(document.getElementById('returnShipFee').value) || 0;

        // 4. 平台与活动费率
        state.cost.platformRate = (parseFloat(document.getElementById('platformFee').value) || 0) / 100;
        state.cost.ddjbRate = (parseFloat(document.getElementById('ddjbRate').value) || 0) / 100;
        state.cost.coupon = parseFloat(document.getElementById('couponPrice').value) || 0;
        state.cost.promo = parseFloat(document.getElementById('promoCost').value) || 0;

        // 5. 计算基础运费
        calculateShipping();
        
        // 6. 分模式核心测算
        recalculateModel();
        
        // 7. 触发 v1.1 模块计算 (联动)
        calcV11_RoiPricing();
        calcV11_Breakeven();
        calcV11_Batch();

        // 8. 触发 v2.1 数据互推引擎 (联动)
        calcMutual1();
        calcMutual2();
        calcMutual3();
    }

    // 运费计算优化：首重+续重向上取整+偏远加价
    function calculateShipping() {
        const w = state.weightKg;
        const firstW = parseFloat(document.getElementById('firstWeight').value) || 1;
        const firstP = parseFloat(document.getElementById('firstPrice').value) || 0;
        const extraP = parseFloat(document.getElementById('extraPrice').value) || 0;
        const remoteAdd = parseFloat(document.getElementById('remoteAdd').value) || 0;
        let fee = firstP;
        if(w > firstW) {
            const extraWeight = Math.ceil(w - firstW);
            fee = firstP + extraWeight * extraP;
        }
        state.baseShipFee = fee + remoteAdd;
        state.cost.shipBase = state.baseShipFee;
        document.getElementById('shippingDetail').innerText = `当前基础发货运费: ${state.baseShipFee.toFixed(2)} 元`;
    }

    // 切换计算模式，渲染对应输入框
    function setMode(mode) {
        state.currentMode = mode;
        document.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
        document.getElementById(`tab-${mode}`).classList.add('active');
        const container = document.getElementById('dynamicInputs');
        let html = '';
        switch(mode) {
            case 'profit':
                html = `
                    <div class="form-group">
                        <label>商品标价 (元)</label>
                        <input type="number" id="input-price" style="border-color:var(--primary); font-weight:bold;" step="0.1" min="0" oninput="recalculateModel()">
                    </div>
                    <div class="form-group">
                        <label>单件广告预算 (元)</label>
                        <input type="number" id="input-ad" value="0" step="0.1" min="0" oninput="recalculateModel()">
                    </div>`;
                break;
            case 'price':
                html = `
                    <div class="form-group">
                        <label>目标单件净利润 (元)</label>
                        <input type="number" id="input-target-profit" value="5" step="0.1" oninput="recalculateModel()">
                    </div>
                    <div class="form-group">
                        <label>单件广告预算 (元)</label>
                        <input type="number" id="input-ad-budget" value="3" step="0.1" min="0" oninput="recalculateModel()">
                        <div class="helper-text">每单愿意付出的广告成本</div>
                    </div>`;
                break;
            case 'ad':
                html = `
                    <div class="form-group">
                        <label>固定商品标价 (元)</label>
                        <input type="number" id="input-fixed-price" style="border-color:var(--primary); font-weight:bold;" step="0.1" min="0" oninput="recalculateModel()">
                    </div>
                    <div class="form-group">
                        <label>保底单件利润 (元)</label>
                        <input type="number" id="input-min-profit" value="2" step="0.1" oninput="recalculateModel()">
                    </div>`;
                break;
            case 'coupon':
                html = `
                    <div class="form-group">
                        <label>券后实收单价 (元)</label>
                        <input type="number" id="input-real-sale" style="border-color:var(--primary); font-weight:bold;" step="0.1" min="0" oninput="recalculateModel()">
                    </div>
                    <div class="form-group">
                        <label>目标单件净利润 (元)</label>
                        <input type="number" id="input-coupon-profit" value="4" step="0.1" oninput="recalculateModel()">
                    </div>
                    <div class="helper-text">按券后实收 + 目标净利润，反推前端标价与可承受广告费上限</div>`;
                break;
        }
        container.innerHTML = html;
        recalculateModel();
    }

    // 核心测算公式（统一成本模型，四种模式共用底层公式）
    // 口径（对齐拼多多官方）：平台技术服务费与多多进宝佣金均按「券后实收」计扣；
    // 交易额(单件) = 券后实收 = 标价 - 优惠券；实际投产比 = 交易额/成交花费；结算投产比按退货率折算。
    function recalculateModel() {
        const c = state.cost;
        const r = c.returnRate;
        // 分摊运费：(发货运费 + 退货运费*退货率) / (1 - r)
        const shipAvg = (c.shipBase + c.shipReturn * r) / (1 - r || 0.0001);
        state.res.totalFixedCost = c.goods + c.pack + shipAvg;
        let S = 0, Ad = 0, targetProfit = 0, minProfit = 0, realSale = 0;
        const platformRate = c.platformRate;
        const ddjbRate = c.ddjbRate;
        const coupon = c.coupon;
        const promo = c.promo;
        const t = platformRate + ddjbRate;      // 总扣点
        const fixedCost = state.res.totalFixedCost;
        const den1 = 1 - t;                     // 券后实收可支配系数

        switch(state.currentMode) {
            case 'profit':
                S = parseFloat(document.getElementById('input-price').value) || 0;
                Ad = parseFloat(document.getElementById('input-ad').value) || 0;
                realSale = S - coupon;
                break;
            case 'price':
                // 反推标价：净利润 = 券后实收×(1-扣点) - 固定成本 - 活动 - 广告
                // 券后实收 = (固定成本 + 活动 + 广告 + 目标利润) / (1 - 扣点)；标价 = 券后实收 + 优惠券
                targetProfit = parseFloat(document.getElementById('input-target-profit').value) || 0;
                Ad = parseFloat(document.getElementById('input-ad-budget').value) || 0;
                realSale = den1 > 0 ? (fixedCost + promo + Ad + targetProfit) / den1 : 0;
                S = realSale + coupon;
                break;
            case 'ad':
                S = parseFloat(document.getElementById('input-fixed-price').value) || 0;
                minProfit = parseFloat(document.getElementById('input-min-profit').value) || 0;
                realSale = S - coupon;
                // 广告费上限 = 券后实收×(1-扣点) - 固定成本 - 活动 - 保底利润
                Ad = realSale * den1 - fixedCost - promo - minProfit;
                break;
            case 'coupon':
                // 券后定价：已知券后实收 + 目标净利润 → 反推可承受广告费上限与前端标价
                realSale = parseFloat(document.getElementById('input-real-sale').value) || 0;
                targetProfit = parseFloat(document.getElementById('input-coupon-profit').value) || 0;
                Ad = realSale * den1 - fixedCost - promo - targetProfit;
                S = realSale + coupon;
                break;
        }

        state.res.price = S;
        state.res.realSale = realSale;
        state.cost.ad = Ad;

        // 平台佣金、多多进宝佣金（按券后实收计扣）
        const commFee = realSale * platformRate;
        const ddjbFee = realSale * ddjbRate;
        state.res.commission = commFee;
        state.res.ddjbFee = ddjbFee;

        // ========== ROI计算（口径：交易额 = 券后实收） ==========
        const grossProfit = realSale - commFee - ddjbFee - fixedCost - promo;
        state.res.grossProfit = grossProfit;
        const netProfit = grossProfit - Ad;
        state.res.netProfit = netProfit;

        let saleROI = Ad > 0 ? realSale / Ad : 0;
        let netROI = Ad > 0 && grossProfit > 0 ? grossProfit / Ad : 0;
        state.res.saleROI = saleROI;
        state.res.netROI = netROI;

        // 结算投产比（官方口径：结算交易额/成交花费，退款按退货率折算）
        const settleROI = saleROI * (1 - r);
        state.res.settleROI = settleROI;

        // 双保本价（标价 = 券后实收 + 优惠券）
        const denBreak = 1 - t || 0.0001;
        state.res.breakEvenNoAd = (fixedCost + promo) / denBreak + coupon;
        state.res.breakEvenAd = (fixedCost + promo + Ad) / denBreak + coupon;

        updateRender(S, fixedCost, commFee, ddjbFee, Ad, grossProfit, netProfit, saleROI, netROI, c.goods + c.pack, shipAvg);
    }

    // 经营状态诊断横幅
    function updateProfitBanner(netProfit, saleROI, netROI, realSale) {
        const banner = document.getElementById('profitBanner');
        const text = document.getElementById('profitBannerText');
        if (!banner || !text) return;
        const eps = 0.005; // 容差
        let cls, msg;
        if (realSale <= 0) {
            cls = 'profit-warn'; msg = '请先在左侧/当前模式填写售价等参数，开始测算';
        } else if (netProfit > eps) {
            cls = 'profit-ok';
            msg = `单件盈利 ¥${netProfit.toFixed(2)}：当前方案可投放${netROI >= 1 ? '，广告投放不亏本' : '，但广告会侵蚀利润'}`;
        } else if (netProfit >= -eps) {
            cls = 'profit-warn';
            msg = '单件处于保本附近，建议优化成本或定价，预留 3%-5% 安全边际';
        } else {
            cls = 'profit-bad';
            msg = `单件亏损 ¥${Math.abs(netProfit).toFixed(2)}：售价过低或广告费过高，需调整定价/降低成本`;
        }
        banner.className = 'profit-banner ' + cls;
        text.textContent = msg;
    }

    // 页面UI渲染更新
    function updateRender(sale, totalFixed, commission, ddjb, ad, grossProfit, netProfit, saleROI, netROI, costGoodsPack, costShipAvg) {
        document.getElementById('res-price').innerText = sale > 0 ? sale.toFixed(2) : '-';
        const realSaleEl = document.getElementById('res-real-sale');
        realSaleEl.innerText = state.res.realSale > 0 ? state.res.realSale.toFixed(2) : '-';

        const grossEl = document.getElementById('res-gross-profit');
        grossEl.innerText = grossProfit.toFixed(2);
        grossEl.className = 'result-value ' + (grossProfit >= 0 ? 'val-green' : 'val-red');

        const profitEl = document.getElementById('res-profit');
        profitEl.innerText = netProfit.toFixed(2);
        profitEl.className = 'result-value ' + (netProfit >= 0 ? 'val-green' : 'val-red');

        // 净利润率（按券后实收）
        const realSale = state.res.realSale;
        const margin = realSale > 0 ? (netProfit / realSale * 100) : 0;
        const marginEl = document.getElementById('res-margin');
        marginEl.innerText = margin.toFixed(2) + '%';
        marginEl.className = 'result-value ' + (margin >= 0 ? 'val-green' : 'val-red');

        // 经营状态诊断横幅
        updateProfitBanner(netProfit, state.res.saleROI, state.res.netROI, state.res.realSale);

        // 【大框】销售额广告ROI（实际投产比）
        document.getElementById('res-sale-roi').innerText = (isFinite(saleROI) && saleROI > 0) ? saleROI.toFixed(2) : '-';
        // 【小框】毛利净投产ROI
        document.getElementById('res-net-roi').innerText = (isFinite(netROI) && netROI > 0) ? netROI.toFixed(2) : '-';
        // 结算投产比（含退款）
        const settleEl = document.getElementById('res-settle-roi');
        const settleROI = state.res.settleROI;
        settleEl.innerText = (isFinite(settleROI) && settleROI > 0) ? settleROI.toFixed(2) : '-';

        document.getElementById('res-breakeven-noad').innerText = state.res.breakEvenNoAd.toFixed(2);
        document.getElementById('res-breakeven-ad').innerText = state.res.breakEvenAd.toFixed(2);

        // 成本可视化柱状图
        if(sale > 0) {
            const pGoodsPack = (costGoodsPack / sale) * 100;
            const pShip = (costShipAvg / sale) * 100;
            const pComm = (commission / sale) * 100;
            const pDdjb = (ddjb / sale) * 100;
            const pCouponPromo = ((state.cost.coupon + state.cost.promo) / sale) * 100;
            const pAd = (ad / sale) * 100;
            const pProfit = Math.max(0, (netProfit / sale) * 100);
            const totalP = pGoodsPack + pShip + pComm + pDdjb + pCouponPromo + pAd + pProfit;
            const bar = document.getElementById('costBar');
            if(totalP > 0) {
                bar.innerHTML = `
                    <div class="bar-segment" style="width:${(pGoodsPack/totalP)*100}%; background:#ff7875;"></div>
                    <div class="bar-segment" style="width:${(pShip/totalP)*100}%; background:#69c0ff;"></div>
                    <div class="bar-segment" style="width:${(pComm/totalP)*100}%; background:#ffd666;"></div>
                    <div class="bar-segment" style="width:${(pDdjb/totalP)*100}%; background:#b37f60;"></div>
                    <div class="bar-segment" style="width:${(pCouponPromo/totalP)*100}%; background:#b379e6;"></div>
                    <div class="bar-segment" style="width:${(pAd/totalP)*100}%; background:#595959;"></div>
                    <div class="bar-segment" style="width:${(pProfit/totalP)*100}%; background:#00b578;"></div>
                `;
            } else bar.innerHTML = '';
        }
    }

    // 弹出完整成本明细弹窗
    function showCostDetail() {
        const c = state.cost;
        const r = c.returnRate;
        const shipAvg = (c.shipBase + c.shipReturn * r) / (1 - r || 0.0001);
        const res = state.res;
        const html = `
            <div class="detail-item"><span>商品货款成本</span><span>${c.goods.toFixed(2)} 元</span></div>
            <div class="detail-item"><span>单件包材费用</span><span>${c.pack.toFixed(2)} 元</span></div>
            <div class="detail-item"><span>分摊快递运费(含退货损耗)</span><span>${shipAvg.toFixed(2)} 元</span></div>
            <div class="detail-item"><span>商品硬成本合计</span><span>${res.totalFixedCost.toFixed(2)} 元</span></div>
            <div class="detail-item"><span>平台技术服务费</span><span>${res.commission.toFixed(2)} 元</span></div>
            <div class="detail-item"><span>多多进宝分销佣金</span><span>${res.ddjbFee.toFixed(2)} 元</span></div>
            <div class="detail-item"><span>单件优惠券抵扣</span><span>${c.coupon.toFixed(2)} 元</span></div>
            <div class="detail-item"><span>活动满减分摊成本</span><span>${c.promo.toFixed(2)} 元</span></div>
            <div class="detail-item" style="margin-top:8px;font-weight:bold;color:#ff9f1c;">
                <span>单件毛利（未扣广告）</span>
                <span style="color:${res.grossProfit>=0?'#00b578':'#f53f3f'}">${res.grossProfit.toFixed(2)} 元</span>
            </div>
            <div class="detail-item"><span>单件广告推广费</span><span>${c.ad.toFixed(2)} 元</span></div>
            <div class="detail-item" style="margin-top:10px;font-weight:bold;color:var(--primary);border-top:1px solid #ddd;padding-top:8px;">
                <span>单件最终净利润</span>
                <span style="color:${res.netProfit>=0?'#00b578':'#f53f3f'}">${res.netProfit.toFixed(2)} 元</span>
            </div>
            <!-- 弹窗调换ROI顺序 -->
            <div class="detail-item">
                <span>销售额广告ROI（推广前台展示ROI）</span>
                <span>${res.saleROI.toFixed(2)}</span>
            </div>
            <div class="detail-item">
                <span>毛利净投产ROI（广告保本核心）</span>
                <span style="color:${res.netROI>=1?'#00b578':'#f53f3f'}">${res.netROI.toFixed(2)}</span>
            </div>
        `;
        document.getElementById('detailContent').innerHTML = html;
        document.getElementById('detailMask').classList.add('show');
    }
    function hideCostDetail() {
        document.getElementById('detailMask').classList.remove('show');
    }

    // ==========================================
    // v1.1 新增功能逻辑 (联动 CoreEngine)
    // ==========================================

    // 1. 全站推广反推售价（已含优惠券/活动/退货损耗，与主引擎口径一致）
    //    交易额口径 = 券后实收 realSale；广告费 = 交易额 / ROI
    //    由 净利润 = realSale - 标价*扣点 - 有效成本 - 活动 - 广告费 反推标价：
    //    标价 S = [目标利润 + 有效成本 + 活动 + 优惠券*(1 - 1/ROI)] / (1 - 扣点 - 1/ROI)
    function calcV11_RoiPricing() {
        const coreData = getCoreData();
        const roi = parseFloat(document.getElementById('v11-target-roi').value);
        const targetProfit = parseFloat(document.getElementById('v11-target-profit').value) || 0;
        const fixedCost = coreData.effectiveCostPerUnit;
        const t = coreData.platformFee + coreData.ddjbRate;   // 总扣点
        const coupon = coreData.coupon;
        const promo = coreData.promo;

        if (!roi || roi <= 0) {
            document.getElementById('v11-res-price').innerText = '-';
            document.getElementById('v11-res-ad').innerText = '-';
            document.getElementById('v11-ad-ratio').innerText = '-';
            return;
        }

        const adRatio = 1 / roi;
        const denominator = 1 - t - adRatio;

        let price = 0, ad = 0;
        if (denominator > 0) {
            // 券后实收 = (固定成本 + 活动 + 目标利润) / (1 - 扣点 - 1/ROI)；标价 = 券后实收 + 优惠券；广告费 = 券后实收/ROI
            const realSale = (fixedCost + promo + targetProfit) / denominator;
            price = realSale + coupon;
            ad = realSale * adRatio;
        }

        document.getElementById('v11-res-price').innerText = (denominator > 0 && price > 0) ? '¥' + price.toFixed(2) : '费率过高无解';
        document.getElementById('v11-res-ad').innerText = (denominator > 0 && ad > 0) ? ad.toFixed(2) : '-';
        document.getElementById('v11-ad-ratio').innerText = (adRatio * 100).toFixed(2);
    }

    // 2. 保本投产比测算（已含优惠券/活动/退货损耗）
    //    保本即利润=0，全部可支配额(券后实收-标价扣点-有效成本-活动)都用于广告
    //    保本ROI = 券后实收 / 广告费
    function calcV11_Breakeven() {
        const coreData = getCoreData();
        const price = parseFloat(document.getElementById('v11-breakeven-price').value);
        if (!price || price <= 0) {
            document.getElementById('v11-res-breakeven').innerText = '-';
            return;
        }
        
        const t = coreData.platformFee + coreData.ddjbRate;
        const realSale = price - coreData.coupon;
        // 保本即利润=0，可支配额(扣点按券后实收)全用于广告
        const moneyForAd = realSale * (1 - t) - coreData.effectiveCostPerUnit - coreData.promo;
        
        let breakevenRoi = 0;
        if (moneyForAd > 0) {
            breakevenRoi = realSale / moneyForAd;
        }
        
        document.getElementById('v11-res-breakeven').innerText = breakevenRoi > 0 ? breakevenRoi.toFixed(2) : '当前售价已亏损';
    }

    // 3. 批量盈亏模拟
    function calcV11_Batch() {
        const coreData = getCoreData();
        const vol = parseFloat(document.getElementById('v11-sales-vol').value);
        const actualRoi = parseFloat(document.getElementById('v11-actual-roi').value);
        
        // 【修复点】安全获取售价：优先取主引擎的标价，如果没有则取保本模块的售价
        // 使用传统的 if/else 检查代替可选链，确保兼容性
        let priceInput = document.getElementById('input-price');
        let price = 0;
        
        if (priceInput) {
            price = parseFloat(priceInput.value) || 0;
        }
        
        // 如果主引擎没有价格输入框（比如在其它Tab），尝试从保本模块获取
        if (price <= 0) {
            let breakevenInput = document.getElementById('v11-breakeven-price');
            if (breakevenInput) {
                price = parseFloat(breakevenInput.value) || 0;
            }
        }
        
        if (!vol || !actualRoi || actualRoi <= 0 || price <= 0) {
            document.getElementById('v11-res-profit').innerText = '-';
            return;
        }
        
        // 交易额口径 = 券后实收（标价 - 优惠券）
        const realSale = price - coreData.coupon;
        const totalSales = realSale * vol;
        // 总广告费 = 总交易额 / 实际投产比
        const totalAdCost = totalSales / actualRoi;
        // 总有效成本 (已含退货损耗分摊)
        const totalEffectiveCost = coreData.effectiveCostPerUnit * vol;
        // 总平台扣点 + DDJB（按券后实收计扣，与官方口径一致）
        const totalCommission = realSale * vol * (coreData.platformFee + coreData.ddjbRate);
        // 总活动分摊成本（优惠券已包含在交易额口径中，不再重复扣除）
        const totalPromoCost = coreData.promo * vol;
        
        const totalProfit = totalSales - totalEffectiveCost - totalCommission - totalPromoCost - totalAdCost;
        
        const profitEl = document.getElementById('v11-res-profit');
        profitEl.innerText = '¥' + totalProfit.toFixed(2);
        profitEl.style.color = totalProfit >= 0 ? '#10b981' : '#e02e24';
    }

    // ==========================================
    // v2.1 数据互推引擎 (Mutual Derivation)
    // 共用成本模型，口径与拼多多推广后台一致：
    //   交易额(单件) = 券后实收 = 标价 - 优惠券
    //   实际投产比 = 交易额 ÷ 成交花费(广告费)
    //   结算投产比 = (交易额 - 退款交易额) ÷ 成交花费 ≈ 实际投产比 × (1 - 退货率)
    // ==========================================

    function _settleRoi(roi) {
        const r = (parseFloat(document.getElementById('returnRate').value) || 0) / 100;
        return roi * (1 - r);
    }

    // 互推① 已知目标投产比 + 目标利润 → 求 建议标价 + 广告费
    //   广告费 = 券后实收 / ROI；净利润 = 券后实收×(1-扣点) - 有效成本 - 活动 - 广告费
    //   券后实收 = (有效成本 + 活动 + 目标利润) / (1 - 总扣点 - 1/ROI)；标价 = 券后实收 + 优惠券
    function calcMutual1() {
        const core = getCoreData();
        const roi = parseFloat(document.getElementById('mt1-roi').value);
        const profit = parseFloat(document.getElementById('mt1-profit').value) || 0;
        const fixedCost = core.effectiveCostPerUnit;
        const t = core.platformFee + core.ddjbRate;   // 总扣点
        const coupon = core.coupon;
        const promo = core.promo;
        const adRatio = 1 / roi;
        const set = (id, v) => document.getElementById(id).innerText = v;

        if (!roi || roi <= 0) {
            set('mt1-res-price','-'); set('mt1-res-real','-'); set('mt1-res-ad','-'); set('mt1-res-settle','-');
            return;
        }
        const denom = 1 - t - adRatio;
        if (denom <= 0) {
            set('mt1-res-price','费率过高无解'); set('mt1-res-real','-'); set('mt1-res-ad','-'); set('mt1-res-settle','-');
            return;
        }
        const realSale = (fixedCost + promo + profit) / denom;
        const price = realSale + coupon;
        const ad = realSale * adRatio;
        set('mt1-res-price', price > 0 ? '¥' + price.toFixed(2) : '无解');
        set('mt1-res-real', realSale.toFixed(2));
        set('mt1-res-ad', ad.toFixed(2));
        set('mt1-res-settle', _settleRoi(roi).toFixed(2));
    }

    // 互推② 已知标价 + 目标利润 → 求 所需实际投产比 + 广告费上限
    //   广告费 = 券后实收×(1-扣点) - 有效成本 - 活动 - 目标利润
    //   所需投产比 = 券后实收 ÷ 广告费
    function calcMutual2() {
        const core = getCoreData();
        const price = parseFloat(document.getElementById('mt2-price').value);
        const profit = parseFloat(document.getElementById('mt2-profit').value) || 0;
        const set = (id, v) => document.getElementById(id).innerText = v;

        if (!price || price <= 0) {
            set('mt2-res-roi','-'); set('mt2-res-ad','-'); set('mt2-res-settle','-');
            return;
        }
        const t = core.platformFee + core.ddjbRate;
        const realSale = price - core.coupon;
        const ad = realSale * (1 - t) - core.effectiveCostPerUnit - core.promo - profit;
        if (ad <= 0) {
            set('mt2-res-roi','无需广告已达标');
            set('mt2-res-ad','0.00');
            set('mt2-res-settle','—');
            return;
        }
        const roi = realSale / ad;
        set('mt2-res-roi', roi.toFixed(2));
        set('mt2-res-ad', ad.toFixed(2));
        set('mt2-res-settle', _settleRoi(roi).toFixed(2));
    }

    // 互推③ 已知标价 + 广告费 → 求 实际投产比 + 净利润
    //   净利润 = 券后实收×(1-扣点) - 有效成本 - 活动 - 广告费
    function calcMutual3() {
        const core = getCoreData();
        const price = parseFloat(document.getElementById('mt3-price').value);
        const ad = parseFloat(document.getElementById('mt3-ad').value) || 0;
        const set = (id, v) => document.getElementById(id).innerText = v;

        if (!price || price <= 0) {
            set('mt3-res-roi','-'); set('mt3-res-profit','-'); set('mt3-res-margin','-'); set('mt3-res-settle','-');
            return;
        }
        const t = core.platformFee + core.ddjbRate;
        const realSale = price - core.coupon;
        const profit = realSale * (1 - t) - core.effectiveCostPerUnit - core.promo - ad;
        const roi = ad > 0 ? realSale / ad : 0;
        const margin = realSale > 0 ? (profit / realSale * 100) : 0;
        set('mt3-res-roi', ad > 0 ? roi.toFixed(2) : '未投广告');
        set('mt3-res-profit', profit.toFixed(2));
        set('mt3-res-margin', margin.toFixed(2) + '%');
        set('mt3-res-settle', _settleRoi(roi).toFixed(2));
    }
</script>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?b13928754415687409d6984031f5a352";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7324867359677819"
     crossorigin="anonymous"></script>
<!-- tool -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-7324867359677819"
     data-ad-slot="2419546678"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</body>
</html>