<template>
    <div class="mobile-policy-document">
        <MobileHeader title="政策文件" :showMenu="false" @back="goBack" />

        <div class="main-content">
            <!-- 页面标题与返回首页（移动端仅展示标题） -->
            <!-- <div class="page-header">
        <h1 class="page-title">政策文件</h1>
      </div> -->

            <!-- 搜索栏 -->
            <div class="search-section">
                <div class="search-box">
                    <div class="search-icon-left">
                        <img
                            src="@/assets/Policy/8.png"
                            alt="搜索"
                            class="search-icon"
                        />
                    </div>
                    <input
                        type="text"
                        placeholder="搜索政策文件..."
                        class="search-input"
                        v-model="searchText"
                        maxlength="100"
                        @input="handleSearchInput"
                        @keyup.enter="handleSearch"
                    />
                </div>
            </div>

            <!-- 分类标签 -->
            <div class="category-tabs">
                <button
                    class="tab-btn"
                    :class="{ active: activeTab === 0 }"
                    @click="setActiveTab(0)"
                >
                    全部政策
                </button>
                <button
                    class="tab-btn"
                    :class="{ active: activeTab === 1 }"
                    @click="setActiveTab(1)"
                >
                    国家法规
                </button>
                <button
                    class="tab-btn"
                    :class="{ active: activeTab === 2 }"
                    @click="setActiveTab(2)"
                >
                    行业法规
                </button>
                <button
                    class="tab-btn"
                    :class="{ active: activeTab === 3 }"
                    @click="setActiveTab(3)"
                >
                    地方法规
                </button>
                <button
                    class="tab-btn"
                    :class="{ active: activeTab === 4 }"
                    @click="setActiveTab(4)"
                >
                    内部条例
                </button>
            </div>

            <!-- 文档列表 -->
            <div
                class="document-list"
                ref="documentList"
                @scroll="handleScroll"
            >
                <div v-if="loading" class="loading">
                    <div class="loading-spinner"></div>
                    <span>加载中...</span>
                </div>

                <div
                    v-if="!loading && policyFiles.length === 0"
                    class="no-data"
                >
                    <span>暂无数据</span>
                </div>

                <div
                    v-for="(file, index) in policyFiles"
                    :key="file.id || index"
                    class="document-item"
                >
                    <div class="doc-icon">
                        <img
                            :src="getFileIcon(file.file_type)"
                            :alt="getFileTypeName(file.file_type)"
                            class="file-icon"
                        />
                    </div>
                    <div class="doc-content">
                        <div class="doc-header">
                            <h3 class="doc-title">{{ file.policy_name }}</h3>
                            <span class="doc-date">{{
                                formatTime(file.publish_time)
                            }}</span>
                        </div>
                        <div class="doc-tags">
                            <span
                                v-for="(tag, tagIndex) in getTags(
                                    file.file_tag
                                )"
                                :key="tagIndex"
                                class="tag tag-blue"
                            >
                                <img
                                    src="@/assets/Policy/10.png"
                                    alt="标签图标"
                                    class="tag-icon"
                                />
                                {{ tag }}
                            </span>
                        </div>
                        <p class="doc-description">{{ file.policy_content }}</p>
                        <div class="doc-footer">
                            <div class="doc-info">
                                <span class="info-item">
                                    <img
                                        src="@/assets/Policy/5.png"
                                        alt="部门"
                                        class="info-icon"
                                    />
                                    {{ file.policy_department }}
                                </span>
                                <span class="info-item">
                                    <img
                                        src="@/assets/Policy/6.png"
                                        alt="次数"
                                        class="info-icon"
                                    />
                                    {{ file.view_count }} 次查看
                                </span>
                            </div>
                            <div class="doc-actions">
                                <button
                                    class="action-btn view-btn"
                                    @click="viewPolicy(file)"
                                >
                                    查看详情 &gt;
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div v-if="hasMore && !loading" class="load-more">
                    <span>上拉加载更多</span>
                </div>
            </div>
        </div>

        <div
            v-if="previewVisible"
            class="preview-modal"
            @click.self="closePreview"
        >
            <div class="preview-content">
                <div class="preview-header">
                    <h3 class="preview-title">{{ previewTitle }}</h3>
                    <button class="close-btn" @click="closePreview">×</button>
                </div>
                <div class="preview-body">
                    <!-- PDF/TXT/其他文件使用自定义渲染器 -->
                    <MobilePdfViewer
                        v-if="previewUrl && isPdfType"
                        :url="previewUrl"
                        class="preview-frame"
                    />
                    <!-- Office文档使用微软在线预览 -->
                    <iframe
                        v-else-if="previewUrl"
                        :src="previewUrl"
                        class="preview-frame"
                        frameborder="0"
                        allowfullscreen
                    ></iframe>
                    <div v-else class="preview-placeholder">暂无可预览内容</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import MobileHeader from "@/components/MobileHeader.vue";
import MobilePdfViewer from "@/components/MobilePdfViewer.vue";
import { apis } from "@/request/apis.js";

const router = useRouter();

// 响应式数据（与PC端保持一致）
const searchText = ref("");
const activeTab = ref(0);
const policyFiles = ref([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const documentList = ref(null);
const previewVisible = ref(false);
const previewFile = ref(null);

let searchTimer = null;
let scrollTimer = null;

const goBack = () => {
    router.go(-1);
};

const setActiveTab = (tabIndex) => {
    activeTab.value = tabIndex;
    page.value = 1;
    policyFiles.value = [];
    hasMore.value = true;
    fetchPolicyFiles();
};

const fetchPolicyFiles = async (isLoadMore = false) => {
    if (loading.value) return;
    loading.value = true;
    try {
        const params = {
            page: page.value,
            pageSize: pageSize.value,
            search: searchText.value,
            policy_type: activeTab.value === 0 ? "" : activeTab.value,
        };
        const response = await apis.getPolicyFile(params);
        if (response && response.data) {
            const newFiles = response.data;
            if (isLoadMore) {
                policyFiles.value = [...policyFiles.value, ...newFiles];
            } else {
                policyFiles.value = newFiles;
            }
            hasMore.value = newFiles.length === pageSize.value;
        }
    } catch (error) {
        console.error("获取政策文件失败:", error);
    } finally {
        loading.value = false;
    }
};

const handleSearchInput = () => {
    if (searchTimer) clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        page.value = 1;
        policyFiles.value = [];
        hasMore.value = true;
        fetchPolicyFiles();
    }, 300);
};

const handleSearch = () => {
    if (searchText.value.trim()) {
        page.value = 1;
        policyFiles.value = [];
        hasMore.value = true;
        fetchPolicyFiles();
    }
};

const viewPolicy = async (file) => {
    console.log("查看政策文件:", file);
    console.log("文件ID:", file.id, "文件所有字段:", Object.keys(file));

    if (!file.policy_file_url) {
        alert("文件链接不存在");
        return;
    }

    // 检查ID是否存在
    if (!file.id) {
        console.error("政策文件ID不存在，跳过次数更新");
    } else {
        // 前端直接更新查看次数显示
        file.view_count = (file.view_count || 0) + 1;

        // 更新查看次数到后端
        try {
            await apis.updatePolicyFileCount({
                policy_file_id: file.id,
                action_type: 1, // 1-查看
            });
            console.log("查看次数更新成功");
        } catch (error) {
            console.error("更新查看次数失败:", error);
            // 如果后端更新失败，回滚前端显示
            file.view_count = (file.view_count || 1) - 1;
        }
    }

    previewFile.value = file;
    previewVisible.value = true;
};

// 图标
import pdfIcon from "@/assets/Policy/2.png";
import wordIcon from "@/assets/Policy/3.png";
import excelIcon from "@/assets/Policy/4.png";

const getFileIcon = (fileType) => {
    const iconMap = {
        0: pdfIcon,
        1: wordIcon,
        2: excelIcon,
        3: pdfIcon,
        4: pdfIcon,
        5: pdfIcon,
    };
    return iconMap[fileType] || pdfIcon;
};

const getFileTypeName = (fileType) => {
    const typeMap = {
        0: "PDF",
        1: "Word",
        2: "Excel",
        3: "PPT",
        4: "TXT",
        5: "其他",
    };
    return typeMap[fileType] || "文件";
};

const previewUrl = computed(() => {
    if (!previewFile.value || !previewFile.value.policy_file_url) return "";
    const fileType = previewFile.value.file_type;
    const url = previewFile.value.policy_file_url;
    if (fileType === 0 || fileType === 4 || fileType === 5) {
        return url;
    }
    if (fileType === 1 || fileType === 2 || fileType === 3) {
        const encodedUrl = encodeURIComponent(url);
        return `https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`;
    }
    return url;
});

const previewTitle = computed(
    () => previewFile.value?.policy_name || "政策文件预览"
);

const isPdfType = computed(() => {
    if (!previewFile.value) return false;
    const fileType = previewFile.value.file_type;
    // 0: PDF, 4: TXT, 5: 其他 (通常也是PDF或图片)
    return fileType === 0 || fileType === 4 || fileType === 5;
});

const closePreview = () => {
    previewVisible.value = false;
    previewFile.value = null;
};

const getTags = (tagString) => {
    if (!tagString) return ["政策文件"];
    return tagString
        .split(",")
        .map((tag) => tag.trim())
        .filter((tag) => tag.length > 0);
};

const formatTime = (timestamp) => {
    if (!timestamp) return "";
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
};

const handleScroll = (event) => {
    if (scrollTimer) clearTimeout(scrollTimer);
    scrollTimer = setTimeout(() => {
        const target = event.target;
        const scrollTop = target.scrollTop;
        const scrollHeight = target.scrollHeight;
        const clientHeight = target.clientHeight;
        if (
            scrollTop + clientHeight >= scrollHeight - 50 &&
            hasMore.value &&
            !loading.value
        ) {
            page.value++;
            fetchPolicyFiles(true);
        }
    }, 100);
};

onMounted(() => {
    fetchPolicyFiles();
});

onUnmounted(() => {
    if (scrollTimer) clearTimeout(scrollTimer);
    if (searchTimer) clearTimeout(searchTimer);
});
</script>

<style lang="less" scoped>
.mobile-policy-document {
    min-height: 100vh;
    background: #ebf3ff;
    font-family: "Alibaba PuHuiTi 3.0", sans-serif;
    display: flex;
    flex-direction: column;
}

.main-content {
    padding: 12px 0 0 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.page-header {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 10px;

    .page-title {
        font-size: 18px;
        font-weight: 900;
        color: #111827;
        margin: 0;
    }
}

.search-section {
    margin-bottom: 10px;
    // padding: 0 14px;
    width: 100%;
    max-width: 450px;

    .search-box {
        position: relative;
        width: 100%;

        .search-icon-left {
            position: absolute;
            left: 12px;
            z-index: 10;
            top: 50%;
            transform: translateY(-50%);

            .search-icon {
                width: 28px;
                height: 28px;
                opacity: 0.6;
            }
        }

        .search-input {
            width: 100%;
            // margin: 0 auto;
            height: 62px;
            padding: 0 14px 0 42px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            font-size: 20px !important;
            background: #fff;
            outline: none;
            transition: all 0.3s ease;
            /* 光标优化 */
            caret-color: #000;
            /* 强制渲染 */
            -webkit-appearance: none;
            appearance: none;
            color: #000 !important;

            &:focus {
                border-color: #3b82f6;
                box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            }

            &::placeholder {
                color: #9ca3af;
            }
        }
    }
}

.category-tabs {
    display: flex;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    gap: 0;
    margin-bottom: 10px;
    border-bottom: 1px solid #e5e7eb;
    width: 100%;
    justify-content: center;

    .tab-btn {
        padding: 10px 12px;
        border: none;
        background: transparent;
        font-size: 18px;
        color: #6b7280;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
        border-bottom: 2px solid transparent;
        white-space: nowrap;

        &:hover {
            color: #2563eb;
        }

        &.active {
            color: #2563eb;
            border-bottom-color: #2563eb;
        }
    }
}

.document-list {
    width: 100%;
    max-width: 450px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    min-height: 300px;
    max-height: calc(100vh - 180px);
    overflow-y: auto;
    // padding: 0 14px;
}

.document-item {
    background: #fff;
    width: 100%;
    border-radius: 12px;
    padding: 14px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    display: flex;
    gap: 12px;
    border: 1px solid #f1f5f9;

    .doc-icon {
        flex-shrink: 0;

        .file-icon {
            width: 22px;
            height: 22px;
            object-fit: contain;
        }
    }

    .doc-content {
        flex: 1;

        .doc-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 6px;

            .doc-title {
                font-size: 16px;
                font-weight: 600;
                color: #1f2937;
                margin: 0;
                line-height: 1.4;
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                line-clamp: 1;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                flex: 1;
                margin-right: 10px;
            }

            .doc-date {
                font-size: 12px;
                color: #6b7280;
                white-space: nowrap;
            }
        }

        .doc-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 6px;
            flex-wrap: wrap;

            .tag {
                padding: 3px 10px;
                font-size: 12px;
                border-radius: 12px;
                font-weight: 500;
                display: flex;
                align-items: center;
                gap: 4px;
                background: #eff6ff;
                color: #2563eb;
                white-space: nowrap;

                .tag-icon {
                    width: 12px;
                    height: 12px;
                    flex-shrink: 0;
                }
            }
        }

        .doc-description {
            font-size: 13px;
            color: #6b7280;
            line-height: 1.5;
            margin: 0 0 6px 0;
            display: -webkit-box;
            line-clamp: 2;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .doc-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .doc-info {
                display: flex;
                gap: 16px;

                .info-item {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    font-size: 12px;
                    color: #6b7280;

                    .info-icon {
                        width: 14px;
                        height: 14px;
                        opacity: 0.6;
                    }
                }
            }

            .doc-actions {
                display: flex;

                .action-btn:first-child {
                    margin-right: 6px;
                }

                .action-btn {
                    padding: 4px 0;
                    border: none;
                    border-radius: 6px;
                    font-size: 13px;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    display: flex;
                    align-items: center;
                    gap: 6px;

                    &.view-btn {
                        color: #3b82f6;
                        background: transparent;
                    }
                }
            }
        }
    }
}

.loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 16px;
    color: #6b7280;
    font-size: 14px;

    .loading-spinner {
        border: 4px solid #f3f3f3;
        border-top: 4px solid #3b82f6;
        border-radius: 50%;
        width: 36px;
        height: 36px;
        animation: spin 1s linear infinite;
        margin-bottom: 12px;
    }
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

.no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px 16px;
    color: #9ca3af;
    font-size: 18px;
    text-align: center;
}

.load-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 16px;
    color: #6b7280;
    font-size: 13px;
    border-top: 1px solid #e5e7eb;
    margin-top: 6px;
}

.document-list::-webkit-scrollbar {
    width: 4px;
}
.document-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}
.document-list::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}
.document-list::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.preview-modal {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.65);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    z-index: 999;
}

.preview-content {
    width: 100%;
    max-width: 640px;
    height: 90vh;
    background: #fff;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 16px;
    background: #f8fafc;
    border-bottom: 1px solid #e5e7eb;
}

.preview-title {
    margin: 0;
    font-size: 16px;
    color: #111827;
    font-weight: 600;
}

.close-btn {
    border: none;
    background: transparent;
    font-size: 24px;
    cursor: pointer;
    color: #6b7280;
    line-height: 1;
    padding: 4px 8px;
}

.preview-body {
    flex: 1;
    background: #111827;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    /* 防止内容溢出 */
    position: relative;
}

.preview-frame {
    width: 100%;
    height: 100%;
    border: none;
}

.preview-placeholder {
    color: #fff;
    font-size: 16px;
}
</style>
