<?php
/**
 * 发帖弹窗组件（共享 partial） v2
 * 依赖变量：$loginUser, $groups, $maxChars, $maxImages, $maxLinks
 * 提交目标：index/forum/postForum
 */
$currentUser = isset($loginUser) ? $loginUser : null;
$mc = isset($maxChars) ? (int)$maxChars : 300;
$mi = isset($maxImages) ? (int)$maxImages : 6;
$ml = isset($maxLinks) ? (int)$maxLinks : 3;
$userName = !empty($currentUser['username']) ? $currentUser['username'] : (isset($_COOKIE['zhicms_comment_name']) ? $_COOKIE['zhicms_comment_name'] : '');
$userMail = !empty($currentUser['mail']) ? $currentUser['mail'] : (isset($_COOKIE['zhicms_comment_mail']) ? $_COOKIE['zhicms_comment_mail'] : '');
$initial = mb_substr($userName ?: '访', 0, 1, 'UTF-8');
?>

<!-- 发帖触发条 -->
<div class="post-trigger">
    <span class="pt-avatar"><?php echo htmlspecialchars($initial, ENT_QUOTES, 'UTF-8'); ?></span>
    <div class="pt-input" onclick="openPostModal()">
        <i class="far fa-edit"></i> 说点什么，分享好物...
    </div>
    <button type="button" class="pt-btn" onclick="openPostModal()">
        <i class="fas fa-plus"></i> 发帖
    </button>
</div>

<!-- 发帖弹窗 -->
<div class="post-mask d-none" id="postMask">
    <div class="post-modal" id="postModal">
        <div class="pm-header">
            <h5><i class="fas fa-edit"></i> 发布到微社区</h5>
            <button type="button" class="pm-close" onclick="closePostModal()" aria-label="关闭">&times;</button>
        </div>
        <div class="pm-body">
            <?php if (empty($currentUser)): ?>
            <div class="pm-visitor">
                <input type="text" id="postPoster" placeholder="昵称 *" value="<?php echo htmlspecialchars($userName, ENT_QUOTES, 'UTF-8'); ?>" maxlength="30">
                <input type="email" id="postMail" placeholder="邮箱（选填，用于接收回复）" value="<?php echo htmlspecialchars($userMail, ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <?php endif; ?>

            <div class="pm-content-box">
                <textarea id="postContent" placeholder="说点什么吧，<?php echo $mc; ?> 字以内..." maxlength="<?php echo $mc; ?>"></textarea>
                <div class="pm-counter" id="pmCounterBox">
                    <span id="charCounter"><?php echo $mc; ?></span> / <?php echo $mc; ?>
                </div>
            </div>

            <div class="pm-toolbar">
                <div class="pm-tools-left">
                    <label class="pm-tool" title="图片（最多 <?php echo $mi; ?> 张）">
                        <i class="far fa-image"></i>
                        <span class="pm-count" id="imageCount">0/<?php echo $mi; ?></span>
                        <input type="file" id="postImageInput" accept="image/jpeg,image/png,image/gif,image/webp" multiple class="d-none">
                    </label>
                    <button type="button" class="pm-tool" id="postLinkBtn" title="商品链接（最多 <?php echo $ml; ?> 个）">
                        <i class="fas fa-link"></i>
                        <span class="pm-count" id="linkCount">0/<?php echo $ml; ?></span>
                    </button>
                </div>
                <select id="postGid" class="pm-group-select">
                    <option value="0">选择小组 *</option>
                    <?php if (!empty($groups)): ?>
                    <?php foreach ($groups as $g): ?>
                    <option value="<?php echo (int)$g['id']; ?>"><?php echo htmlspecialchars($g['groupname'], ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </select>
            </div>

            <div class="pm-images" id="postImagesPreview"></div>

            <div class="pm-link-box d-none" id="postLinkBox">
                <input type="url" id="postLinkInput" placeholder="粘贴淘宝/京东/拼多多/唯品会商品链接">
                <button type="button" class="pm-parse-btn" onclick="parseProductLink()">解析</button>
                <button type="button" class="pm-cancel-btn" onclick="cancelLinkParse()">取消</button>
            </div>
            <div class="pm-link-result" id="postLinkResult"></div>

            <div class="pm-goods-list" id="postGoodsPreview"></div>
        </div>
        <div class="pm-footer">
            <button type="button" class="pm-btn-cancel" onclick="closePostModal()">取消</button>
            <button type="button" class="pm-btn-submit" onclick="submitPostForm()">
                <i class="fas fa-paper-plane"></i> 立即发布
            </button>
        </div>
    </div>
</div>

<style>
/* 触发条 */
.post-trigger {
    display: flex; align-items: center; gap: 12px;
    background: #fff; border-radius: 10px; padding: 12px 16px;
    margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}
.pt-avatar {
    display: inline-flex; align-items: center; justify-content: center;
    width: 40px; height: 40px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: #fff; border-radius: 50%;
    font-size: 18px; font-weight: 600; flex-shrink: 0;
}
.pt-input {
    flex: 1; padding: 9px 16px;
    background: #f5f7fa; border-radius: 22px;
    color: #999; font-size: 14px;
    cursor: pointer; transition: all 0.2s;
}
.pt-input:hover { background: #eef1f6; color: #555; }
.pt-input i { margin-right: 6px; }
.pt-btn {
    background: linear-gradient(135deg, #1890ff, #096dd9);
    color: #fff; border: none;
    padding: 8px 18px; border-radius: 20px;
    font-size: 13px; font-weight: 500; cursor: pointer;
    transition: all 0.2s; white-space: nowrap;
}
.pt-btn:hover { transform: translateY(-1px); box-shadow: 0 4px 10px rgba(24,144,255,0.3); }
.pt-btn i { margin-right: 4px; }

/* 弹窗遮罩 */
.post-mask {
    position: fixed; top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 9999;
    display: flex; align-items: flex-start; justify-content: center;
    padding: 5vh 16px 16px;
    overflow-y: auto;
    animation: pmFadeIn 0.2s ease;
}
@keyframes pmFadeIn { from { opacity: 0; } to { opacity: 1; } }

/* 弹窗主体 */
.post-modal {
    background: #fff; border-radius: 14px;
    width: 100%; max-width: 640px;
    box-shadow: 0 10px 50px rgba(0,0,0,0.2);
    animation: pmSlideDown 0.25s ease;
    margin-bottom: 5vh;
}
@keyframes pmSlideDown {
    from { transform: translateY(-30px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.pm-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
}
.pm-header h5 {
    margin: 0; font-size: 16px; color: #333;
    font-weight: 600; display: flex; align-items: center; gap: 8px;
}
.pm-header h5 i { color: #1890ff; }
.pm-close {
    background: transparent; border: none;
    font-size: 26px; line-height: 1; color: #999;
    cursor: pointer;
    width: 32px; height: 32px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    transition: all 0.2s;
}
.pm-close:hover { background: #f5f5f5; color: #333; }

.pm-body { padding: 16px 20px; }

.pm-visitor {
    display: flex; gap: 8px; margin-bottom: 12px;
}
.pm-visitor input {
    flex: 1; padding: 9px 12px;
    border: 1px solid #ddd; border-radius: 6px;
    font-size: 13px;
}
.pm-visitor input:focus {
    border-color: #1890ff; outline: none;
    box-shadow: 0 0 0 2px rgba(24,144,255,0.1);
}

.pm-content-box { position: relative; }
.pm-content-box textarea {
    width: 100%; padding: 12px;
    border: 1px solid #ddd; border-radius: 8px;
    font-size: 14px; line-height: 1.6;
    min-height: 120px; resize: vertical;
    font-family: inherit;
    box-sizing: border-box;
}
.pm-content-box textarea:focus {
    border-color: #1890ff; outline: none;
    box-shadow: 0 0 0 2px rgba(24,144,255,0.1);
}
.pm-counter {
    position: absolute; bottom: 8px; right: 12px;
    font-size: 12px; color: #999;
    background: rgba(255,255,255,0.9);
    padding: 2px 8px; border-radius: 10px;
    transition: color 0.2s;
}
.pm-counter.warn { color: #fa8c16; }
.pm-counter.danger { color: #f5222d; font-weight: 600; }

.pm-toolbar {
    display: flex; align-items: center; justify-content: space-between;
    margin-top: 14px; padding-top: 12px;
    border-top: 1px dashed #f0f0f0;
    flex-wrap: wrap; gap: 8px;
}
.pm-tools-left { display: flex; gap: 8px; }
.pm-tool {
    position: relative;
    display: inline-flex; align-items: center; gap: 6px;
    background: #f5f7fa; border: 1px solid #eaecef;
    padding: 7px 14px; border-radius: 20px;
    cursor: pointer; color: #555; font-size: 14px;
    transition: all 0.2s;
}
.pm-tool:hover {
    background: #e6f7ff; border-color: #91d5ff; color: #1890ff;
}
.pm-tool i { font-size: 16px; }
.pm-count {
    font-size: 11px; padding: 1px 6px;
    background: #fff; border: 1px solid #ddd;
    border-radius: 8px; color: #666;
    font-weight: 600;
}
.pm-group-select {
    padding: 7px 12px; border: 1px solid #ddd;
    border-radius: 6px; font-size: 13px;
    background: #fff; min-width: 140px;
    cursor: pointer;
}
.pm-group-select:focus {
    border-color: #1890ff; outline: none;
    box-shadow: 0 0 0 2px rgba(24,144,255,0.1);
}

/* 图片预览九宫格 */
.pm-images {
    display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
    margin-top: 12px;
}
.pm-images:empty { display: none; }
.pm-images .img-item {
    position: relative; padding-top: 100%;
    border-radius: 8px; overflow: hidden;
    background: #f5f5f5;
}
.pm-images .img-item img {
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%; object-fit: cover;
}
.pm-images .img-item .remove {
    position: absolute; top: 4px; right: 4px;
    width: 22px; height: 22px;
    background: rgba(0,0,0,0.6); color: #fff;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 14px; line-height: 1;
}
.pm-images .img-item .remove:hover { background: rgba(0,0,0,0.85); }

/* 链接解析输入框 */
.pm-link-box {
    display: flex; gap: 8px; margin-top: 12px;
    padding: 12px; background: #f5f7fa;
    border-radius: 8px;
}
.pm-link-box input {
    flex: 1; padding: 8px 12px;
    border: 1px solid #ddd; border-radius: 6px;
    font-size: 13px;
}
.pm-link-box input:focus {
    border-color: #1890ff; outline: none;
    box-shadow: 0 0 0 2px rgba(24,144,255,0.1);
}
.pm-parse-btn {
    background: #1890ff; color: #fff;
    border: none; padding: 8px 16px;
    border-radius: 6px; font-size: 13px;
    cursor: pointer; white-space: nowrap;
}
.pm-parse-btn:hover { background: #096dd9; }
.pm-cancel-btn {
    background: transparent; color: #999;
    border: 1px solid #ddd; padding: 8px 12px;
    border-radius: 6px; font-size: 13px;
    cursor: pointer;
}
.pm-cancel-btn:hover { color: #666; }
.pm-link-result {
    margin-top: 8px; font-size: 13px; color: #666;
    padding: 0 4px;
}
.pm-link-result.success { color: #52c41a; }
.pm-link-result.error { color: #f5222d; }

/* 商品卡片预览列表 */
.pm-goods-list {
    margin-top: 12px;
    display: flex; flex-direction: column; gap: 8px;
}
.pm-goods-list:empty { display: none; }
.pm-goods-card {
    display: flex; gap: 10px;
    padding: 10px;
    border: 1px solid #eaecef; border-radius: 8px;
    background: #fafbff;
    position: relative;
    transition: all 0.2s;
}
.pm-goods-card:hover { border-color: #91d5ff; background: #f0f7ff; }
.pm-goods-card .goods-pic {
    width: 70px; height: 70px;
    border-radius: 6px; object-fit: cover;
    flex-shrink: 0;
}
.pm-goods-card .goods-info { flex: 1; min-width: 0; }
.pm-goods-card .goods-title {
    font-size: 13px; color: #333; line-height: 1.4;
    max-height: 36px; overflow: hidden; margin-bottom: 6px;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
.pm-goods-card .goods-price {
    display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap;
}
.pm-goods-card .act-price {
    color: #f5222d; font-size: 15px; font-weight: 700;
}
.pm-goods-card .orig-price {
    color: #999; text-decoration: line-through; font-size: 12px;
}
.pm-goods-card .goods-platform {
    padding: 2px 6px; background: #e6f7ff; color: #1890ff;
    border-radius: 3px; font-size: 11px;
}
.pm-goods-card .goods-coupon {
    padding: 2px 6px; background: #fff1f0; color: #f5222d;
    border-radius: 3px; font-size: 11px;
}
.pm-goods-card .goods-remove {
    position: absolute; top: 6px; right: 6px;
    width: 22px; height: 22px;
    background: rgba(245,34,45,0.9); color: #fff;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 14px; line-height: 1;
    transition: all 0.2s;
}
.pm-goods-card .goods-remove:hover { background: #f5222d; transform: scale(1.1); }

/* 弹窗底部 */
.pm-footer {
    display: flex; justify-content: flex-end; gap: 8px;
    padding: 14px 20px;
    border-top: 1px solid #f0f0f0;
    background: #fafafa;
    border-radius: 0 0 14px 14px;
}
.pm-btn-cancel {
    background: #fff; color: #666;
    border: 1px solid #ddd;
    padding: 8px 18px; border-radius: 6px;
    font-size: 13px; cursor: pointer;
    transition: all 0.2s;
}
.pm-btn-cancel:hover { background: #f5f5f5; }
.pm-btn-submit {
    background: linear-gradient(135deg, #1890ff, #096dd9);
    color: #fff; border: none;
    padding: 8px 22px; border-radius: 6px;
    font-size: 13px; font-weight: 500; cursor: pointer;
    transition: all 0.2s;
}
.pm-btn-submit:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 10px rgba(24,144,255,0.3);
}
.pm-btn-submit i { margin-right: 4px; }

@media (max-width: 600px) {
    .post-modal { max-width: 100%; border-radius: 10px; }
    .pm-toolbar { flex-direction: column; align-items: stretch; }
    .pm-group-select { width: 100%; }
    .pm-tools-left { justify-content: space-around; }
    .pm-body { padding: 14px; }
    .pm-footer { padding: 12px 14px; }
    .pt-btn { padding: 8px 12px; }
}
</style>

<script>
window.__postConfig = {
    maxChars: <?php echo $mc; ?>,
    maxImages: <?php echo $mi; ?>,
    maxLinks: <?php echo $ml; ?>,
    isLogin: <?php echo !empty($currentUser) ? 'true' : 'false'; ?>
};
window.__postImages = [];
window.__postGoodsData = []; // 多个商品卡片

// 打开/关闭弹窗
function openPostModal() {
    document.getElementById('postMask').style.display = 'flex';
    document.body.style.overflow = 'hidden';
    setTimeout(function() {
        var t = document.getElementById('postContent');
        if (t) t.focus();
    }, 150);
}

function closePostModal() {
    document.getElementById('postMask').style.display = 'none';
    document.body.style.overflow = '';
}

// 点击遮罩关闭
document.getElementById('postMask').addEventListener('click', function(e) {
    if (e.target === this) closePostModal();
});
// ESC 关闭
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        var mask = document.getElementById('postMask');
        if (mask && mask.style.display !== 'none') closePostModal();
    }
});

// 字数计数
document.getElementById('postContent').addEventListener('input', function() {
    var max = window.__postConfig.maxChars;
    var len = Array.from(this.value).length;
    var counter = document.getElementById('charCounter');
    var box = document.getElementById('pmCounterBox');
    counter.textContent = (max - len);
    box.className = 'pm-counter';
    if (len > max * 0.9) box.classList.add('warn');
    if (len >= max) box.classList.add('danger');
});

// 图片上传
document.getElementById('postImageInput').addEventListener('change', function(e) {
    var files = e.target.files;
    if (!files || files.length === 0) return;
    var remaining = window.__postConfig.maxImages - window.__postImages.length;
    if (remaining <= 0) {
        alert('最多上传 ' + window.__postConfig.maxImages + ' 张图片');
        e.target.value = '';
        return;
    }
    var toUpload = Array.from(files).slice(0, remaining);
    toUpload.forEach(function(file) {
        if (!file.type.startsWith('image/')) return;
        if (file.size > 5 * 1024 * 1024) { alert(file.name + ' 超过 5MB'); return; }
        var formData = new FormData();
        formData.append('file', file);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'index.php?r=index/forum/uploadImage', true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    try {
                        var r = JSON.parse(xhr.responseText);
                        if (r.status === 'y') {
                            window.__postImages.push(r.url);
                            renderPostImages();
                        } else {
                            alert(r.info);
                        }
                    } catch (err) { alert('上传失败'); }
                }
            }
        };
        xhr.send(formData);
    });
    e.target.value = '';
});

function renderPostImages() {
    var box = document.getElementById('postImagesPreview');
    var html = '';
    window.__postImages.forEach(function(url, idx) {
        html += '<div class="img-item"><img src="' + url + '" alt=""><span class="remove" onclick="removePostImage(' + idx + ')">×</span></div>';
    });
    box.innerHTML = html;
    document.getElementById('imageCount').textContent = window.__postImages.length + '/' + window.__postConfig.maxImages;
}

function removePostImage(idx) {
    window.__postImages.splice(idx, 1);
    renderPostImages();
}

// 商品链接解析（支持多个）
document.getElementById('postLinkBtn').addEventListener('click', function() {
    if (window.__postGoodsData.length >= window.__postConfig.maxLinks) {
        alert('最多添加 ' + window.__postConfig.maxLinks + ' 个商品链接');
        return;
    }
    var box = document.getElementById('postLinkBox');
    box.style.display = box.style.display === 'none' ? 'flex' : 'none';
    if (box.style.display === 'flex') {
        document.getElementById('postLinkInput').focus();
    }
});

function parseProductLink() {
    var url = document.getElementById('postLinkInput').value.trim();
    if (!url) { alert('请输入链接'); return; }
    if (window.__postGoodsData.length >= window.__postConfig.maxLinks) {
        alert('最多添加 ' + window.__postConfig.maxLinks + ' 个商品链接');
        return;
    }
    var result = document.getElementById('postLinkResult');
    result.className = 'pm-link-result';
    result.textContent = '解析中...';

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=index/forum/parseLink', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var r = JSON.parse(xhr.responseText);
                    if (r.status === 'y' && r.card) {
                        window.__postGoodsData.push(r.card);
                        renderGoodsPreview();
                        result.className = 'pm-link-result success';
                        result.textContent = '✓ ' + (r.card.platformName || '商品') + ' 已添加';
                        document.getElementById('postLinkInput').value = '';
                        if (window.__postGoodsData.length >= window.__postConfig.maxLinks) {
                            document.getElementById('postLinkBox').style.display = 'none';
                        }
                        document.getElementById('linkCount').textContent = window.__postGoodsData.length + '/' + window.__postConfig.maxLinks;
                    } else {
                        result.className = 'pm-link-result error';
                        result.textContent = '✗ ' + (r.info || '解析失败');
                    }
                } catch (err) {
                    result.className = 'pm-link-result error';
                    result.textContent = '✗ 响应异常';
                }
            }
        }
    };
    xhr.send('url=' + encodeURIComponent(url));
}

function cancelLinkParse() {
    document.getElementById('postLinkBox').style.display = 'none';
    document.getElementById('postLinkInput').value = '';
    document.getElementById('postLinkResult').textContent = '';
}

function renderGoodsPreview() {
    var box = document.getElementById('postGoodsPreview');
    var html = '';
    window.__postGoodsData.forEach(function(card, idx) {
        var platformName = card.platformName || ({tb:'淘宝', jd:'京东', pdd:'拼多多', vip:'唯品会'}[card.platform] || card.platform);
        html += '<div class="pm-goods-card">';
        if (card.pic) {
            html += '<img class="goods-pic" src="' + card.pic + '" alt="">';
        }
        html += '<div class="goods-info">';
        html += '<div class="goods-title">' + (card.title || '商品') + '</div>';
        html += '<div class="goods-price">';
        html += '<span class="goods-platform">' + platformName + '</span>';
        if (card.actPrice > 0) {
            html += '<span class="act-price">¥' + Number(card.actPrice).toFixed(2) + '</span>';
        }
        if (card.origPrice > 0 && card.origPrice > card.actPrice) {
            html += '<span class="orig-price">¥' + Number(card.origPrice).toFixed(2) + '</span>';
        }
        if (card.coupon > 0) {
            html += '<span class="goods-coupon">券' + card.coupon + '元</span>';
        }
        html += '</div>';
        if (card.sales > 0) {
            html += '<small style="color:#999;font-size:11px;">月销 ' + card.sales + '</small>';
        }
        html += '</div>';
        html += '<span class="goods-remove" onclick="removeGoodsCard(' + idx + ')">×</span>';
        html += '</div>';
    });
    box.innerHTML = html;
}

function removeGoodsCard(idx) {
    window.__postGoodsData.splice(idx, 1);
    renderGoodsPreview();
    document.getElementById('linkCount').textContent = window.__postGoodsData.length + '/' + window.__postConfig.maxLinks;
    // 重新显示链接输入框（如果之前隐藏）
    if (window.__postGoodsData.length < window.__postConfig.maxLinks) {
        document.getElementById('postLinkBox').style.display = 'flex';
    }
}

// 提交发帖
function submitPostForm() {
    var content = document.getElementById('postContent').value.trim();
    if (!content) { alert('请填写内容'); return; }
    var gid = parseInt(document.getElementById('postGid').value) || 0;
    if (gid <= 0) { alert('请选择小组'); return; }

    var poster = '';
    var mail = '';
    if (!window.__postConfig.isLogin) {
        poster = document.getElementById('postPoster').value.trim();
        if (!poster) { alert('请填写昵称'); return; }
        mail = document.getElementById('postMail').value.trim();
    }

    var images = window.__postImages.length > 0 ? JSON.stringify(window.__postImages) : '';
    var goodsData = window.__postGoodsData.length > 0 ? JSON.stringify(window.__postGoodsData) : '';

    var formData = new URLSearchParams();
    formData.append('gid', gid);
    formData.append('content', content);
    if (images) formData.append('images', images);
    if (goodsData) formData.append('goods_data', goodsData);
    if (!window.__postConfig.isLogin) {
        formData.append('poster', poster);
        formData.append('mail', mail);
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=index/forum/postForum', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var r = JSON.parse(xhr.responseText);
                    if (r.status === 'y') {
                        closePostModal();
                        window.location.href = r.url;
                    } else {
                        alert(r.info);
                    }
                } catch (err) { alert('提交失败'); }
            }
        }
    };
    xhr.send(formData);
}
</script>
