<template>
    <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
        <cwg-header :title="currentTitleText" />
        <view id="News_Content" class="news-content">
            <!-- 观点分析 / 新闻资讯 / 公告 / 新闻资讯（通讯） -->
            <view class="content crm-border-radius" v-if="[1, 2, 3, 5].includes(type)">
                <view class="img" v-if="imgContentIf">
                    <image :src="imgContent" mode="widthFix" @click="previewImage(imgContent)" />
                </view>
                <cwg-rich-text :nodes="Content" />
            </view>

            <!-- 视频评论（WebTV 视频） -->
            <view class="content crm-border-radius" v-if="type === 4">
                <text class="con-title">{{ info.title }}</text>
                <view class="con-time" style="display: flex; justify-content: space-between;">
                    <text>{{ info.createTime }}</text>
                    <image src="/static/acc_logo.png" style="height: 80rpx;" mode="heightFix" />
                </view>
                <view class="my_video" style="width: 100%">
                    <video :id="`dplayer-${title}`" :src="info.url" controls class="video-player" />
                </view>
                <text class="con-des">{{ info.description }}</text>
            </view>

            <!-- 视频评论（另一种） -->
            <view class="content crm-border-radius" v-if="type === 6">
                <text class="con-title">{{ info.title }}</text>
                <text class="con-time">{{ info.subTitle }}</text>
                <view class="my_video" style="width: 100%">
                    <video :id="`dplayer-${type}`" :src="imgContent" controls class="video-player" />
                </view>
                <view class="rich-text-wrapper">
                    <cwg-rich-text :nodes="info.content" />
                </view>
            </view>

            <!-- 公告详情 -->
            <view class="content crm-border-radius" v-if="type === 7">
                <text class="con-title">{{ info.subject }}</text>
                <view class="rich-text-wrapper">
                    <cwg-rich-text :nodes="info.content1" />
                </view>
            </view>

            <!-- 交易观点 / 财经日历（内嵌网页） -->
            <view class="content crm-border-radius" v-if="[8, 9].includes(title)">
                <web-view :src="imgContent" class="webview" />
            </view>

            <!-- 电子书 -->
            <view class="content crm-border-radius" v-if="type === 10">
                <view class="ebookBox">
                    <image :src="imgUrl + info.coverImage" mode="widthFix" class="ebook-cover" />
                    <view>
                        <text class="news-title">{{ info.title }}</text>
                        <view class="rich-text-wrapper">
                            <cwg-rich-text :nodes="info.content" />
                        </view>
                        <view class="news-status">
                            <cwg-link type="html" title="blockchain.item12" :url="imgUrl + info.bookUrl"
                                target="_blank" />
                        </view>
                    </view>
                </view>
            </view>

            <!-- 视频评论（iframe 嵌入） -->
            <view class="content crm-border-radius" v-if="type === 11">
                <view style="display: flex; justify-content: end; margin-bottom: 30rpx;">
                    <image src="/static/acc_logo.png" style="height: 80rpx;" mode="heightFix" />
                </view>
                <view style="width: 80%; margin: auto;">
                    <web-view v-if="isZh" src="https://videos.tradingcentral.cn/players/H5QuTuut-iodula4l.html" />
                    <web-view v-else src="https://videos.tradingcentral.cn/players/SHILp3nA-iodula4l.html" />
                </view>
            </view>
        </view>
    </cwg-page-wrapper>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { newsApi } from '@/service/news'
import Config from '@/config/index'
import { adaptCWGEmailForUniApp } from '@/utils/emailAdapter.js';

const { t } = useI18n()
const { Code, Host80, Host05 } = Config

// 路由参数
const type = ref(null)
const id = ref(null)
const currentTitleText = computed(() => {
    const map = {
        1: t('News.ViewAnalysis'),
        2: t('News.NewsInformation'),
        3: t('News.Announcement'),
        4: t('News.VideoCommentary'),
        5: t('News.NewsInformation'),
        6: t('News.VideoCommentary'),
        7: t('News.Notice'),
        8: t('News.TradeIdeas'),
        9: t('News.FinancialCalendar'),
        10: t('News.Ebook'),
        11: t('News.VideoCommentary')
    }
    return map[type.value] || ''
})
// 数据
const Content = ref('')
const imgContent = ref('')
const imgContentIf = ref(false)
const info = ref({})
const imgUrl = Host80

// 语言判断
const isZh = computed(() => ['cn', 'zh', 'zhHant'].includes(locale.value));

// 图片预览
const previewImage = (url) => {
    uni.previewImage({
        urls: [url]
    })
}

// 获取详情（根据 title 调用不同接口）
const getNewsSingle = async () => {
    if (!type.value) return

    switch (type.value) {
        case 1: // 观点分析
            const analysisRes = await newsApi.newsAnalysisSingle({ id: id.value })
            if (analysisRes.code === Code.StatusOK && analysisRes.data) {
                imgContent.value = analysisRes.data.media
                Content.value = analysisRes.data.content
                imgContentIf.value = !!analysisRes.data.media
            } else {
                uni.showToast({ title: analysisRes.msg, icon: 'none' })
            }
            break
        case 3: // 公告
            const infoRes = await newsApi.newsInformationSingle({ id: id.value })
            if (infoRes.code === Code.StatusOK && infoRes.data) {
                imgContent.value = Host80 + infoRes.data.coverImage
                Content.value = infoRes.data.content
                imgContentIf.value = !!infoRes.data.coverImage
            } else {
                uni.showToast({ title: infoRes.msg, icon: 'none' })
            }
            break

        case 7: // 通知
            const noticeRes = await newsApi.newsNoticeSingle({ id: id.value })
            if (noticeRes.code === Code.StatusOK && noticeRes.data) {
                info.value = { ...noticeRes.data, content1: adaptCWGEmailForUniApp(noticeRes.data.content) }
                uni.$emit('open-notice')
            } else {
                uni.showToast({ title: noticeRes.msg, icon: 'none' })
            }
            break

        case 4: // WebTV 视频
            const webTvRes = await newsApi.newsWebTvSearchSingle({ id: id.value })
            if (webTvRes.code === Code.StatusOK && webTvRes.data) {
                info.value = webTvRes.data
                // 视频通过 video 组件自动播放，无需手动初始化 DPlayer
            } else {
                uni.showToast({ title: webTvRes.msg, icon: 'none' })
            }
            break

        case 5: // 新闻通讯
            const newsletterRes = await newsApi.newsInformationNewsletterSingle({ id: id.value })
            if (newsletterRes.code === Code.StatusOK && newsletterRes.data) {
                imgContent.value = Host05 + newsletterRes.data.coverImage
                Content.value = newsletterRes.data.content
                imgContentIf.value = !!newsletterRes.data.coverImage
            } else {
                uni.showToast({ title: newsletterRes.msg, icon: 'none' })
            }
            break

        case 6: // 视频评论
            const videoRes = await newsApi.newsVideoSingle({ id: id.value })
            if (videoRes.code === Code.StatusOK && videoRes.data) {
                info.value = videoRes.data
                imgContent.value = videoRes.data.videoUrl.includes('http')
                    ? videoRes.data.videoUrl
                    : Host80 + videoRes.data.videoUrl
            } else {
                uni.showToast({ title: videoRes.msg, icon: 'none' })
            }
            break

        case 8: // 交易观点
            const shakeRes = await newsApi.handShakeGet({})
            if (shakeRes.code === Code.StatusOK) {
                imgContent.value = shakeRes.msg
            } else {
                uni.showToast({ title: shakeRes.msg, icon: 'none' })
            }
            break

        case 9: // 财经日历
            const calRes = await newsApi.handFinancialCalendar({})
            if (calRes.code === Code.StatusOK) {
                imgContent.value = calRes.msg
            } else {
                uni.showToast({ title: calRes.msg, icon: 'none' })
            }
            break

        case 10: // 电子书
            const ebookRes = await newsApi.newsEbookSingle({ id: id.value })
            if (ebookRes.code === Code.StatusOK && ebookRes.data) {
                info.value = ebookRes.data
            } else {
                uni.showToast({ title: ebookRes.msg, icon: 'none' })
            }
            break

        default:
            break
    }
}


// 页面生命周期：获取路由参数
onLoad((options) => {
    type.value = Number(options.type)
    id.value = options.id
    getNewsSingle()
})

// 如果需要在页面卸载时做一些清理（原组件无，可留空）
onUnmounted(() => {
    // 清理可能的视频播放器
})
</script>

<style lang="scss" scoped>
@import "@/uni.scss";
#News_Content {
    height: 100%;

    .crm-title-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: px2rpx(10);
        box-sizing: border-box;
        background-color: #fff;
        border-bottom: 1px solid #eee;

        .tit {
            font-size: px2rpx(16);
            font-weight: bold;
        }

        .btn {
            display: flex;
            align-items: center;

            .icon-back {
                font-size: px2rpx(18);
                margin-right: px2rpx(4);
            }
        }
    }

    .content {
        width: 100%;
        height: calc(100% - 50rpx);
        background-color: #fff;
        overflow: hidden;
        text-align: left;
        padding: px2rpx(10);
        box-sizing: border-box;
        line-height: 1.8;
        display: flex;
        flex-direction: column;
        justify-content: center;


        .img {
            margin-bottom: px2rpx(10);

            image {
                width: 100%;
            }
        }

        .con-title {
            font-size: px2rpx(18);
            font-weight: bold;
            margin: px2rpx(10) 0;
            text-align: center;
        }

        .con-time {
            margin-bottom: px2rpx(10);
            font-size: px2rpx(12);
            color: #999;
        }

        .con-des {
            margin: px2rpx(10) 0;
            font-size: px2rpx(14);
        }

        .video-player {
            width: 100%;
            height: px2rpx(400);
        }

        .webview {
            width: 100%;
            height: 100%;
            min-height: px2rpx(1200);
        }

        .ebookBox {
            display: flex;
            flex-direction: column;

            @media (min-width: 768px) {
                flex-direction: row;
                align-items: center;
            }

            .ebook-cover {
                width: 100%;
                max-width: px2rpx(360);
                height: auto;
                margin-right: 0;
                margin-bottom: px2rpx(15);

                @media (min-width: 768px) {
                    margin-right: 25rpx;
                    margin-bottom: 0;
                }
            }

            .news-title {
                color: #EB3F57;
                font-size: px2rpx(44);
                font-weight: bold;
                margin-bottom: px2rpx(10);
            }

            .news-status {
                margin-top: px2rpx(10);

                a {
                    display: inline-block;
                    background-color: #EB3F57;
                    color: #fff;
                    padding: px2rpx(4) px2rpx(30);
                    border-radius: px2rpx(8);
                    font-weight: bold;
                }
            }
        }
    }
}

// 富文本表格样式（保留）
:deep(.con-des) {
    table {
        border-collapse: collapse !important;
        width: 100% !important;
        margin: px2rpx(10) 0 !important;
    }

    th,
    td {
        border: 1px solid #dcdfe6 !important;
        padding: px2rpx(8) !important;
        text-align: left !important;
    }

    th {
        background-color: #f5f7fa !important;
    }
}


.rich-text-wrapper {
    width: 100%;
    overflow-x: auto; // 允许横向滚动
    -webkit-overflow-scrolling: touch; // 在 iOS 上提供惯性滚动
}

// 可选：让 rich-text 内的内容不换行（但不一定需要）
.rich-text-wrapper rich-text {
    display: block;
    width: 100%;
}
</style>

<style>
/* 覆盖 rich-text 内所有段落样式 */
uni-rich-text p {
    margin: px2rpx(12) 0 !important;
    font-size: px2rpx(14) !important;
    /* 对应 14px */
    line-height: 1.6 !important;
    color: #333;
}

/* 覆盖 span 样式，移除固定字体和大小 */
uni-rich-text span {
    font-size: px2rpx(14) !important;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !important;
}

/* 图片自适应 */
uni-rich-text img {
    max-width: 100% !important;
    height: auto;
}
</style>
