<template>
    <cwg-popup :title="t('Shop.Index.Transaction')" :visible="props.visible" :showFooters="false"
        @update:visible="$emit('update:visible', $event)">
        <view class="card-list">
            <view class="card" @click="handleWebClick">
                <view class="card-icon">
                    <cwg-icon name="cwg-mt" :size="48" color="#fff" />
                </view>
                <view class="card-content">
                    <text class="card-title">{{ webTitle }}</text>
                    <text class="card-desc">{{ t('Downloadpage.item40') }}</text>
                </view>
                <view class="card-arrow">
                    <cwg-icon name="cwg-arrow" :size="24" color="#141d22" />
                </view>
            </view>
            <view class="card" @click="handleDownloadClick">
                <view class="card-icon">
                    <cwg-icon name="cwg-mt" :size="48" color="#fff" />
                </view>
                <view class="card-content">
                    <text class="card-title">{{ downloadItem.name }}</text>
                    <text class="card-desc">{{ downloadItem.description }}</text>
                </view>
                <view class="card-arrow">
                    <cwg-icon name="cwg-arrow" :size="24" color="#141d22" />
                </view>
            </view>
            <view @click="handleClick" class="card">
                <view class="card-content">
                    <text class="card-title" v-t="'vu.item13'"></text>
                </view>
                <view class="card-arrow">
                    <cwg-icon name="cwg-arrow" :size="24" color="#141d22" />
                </view>
            </view>
        </view>
    </cwg-popup>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { TerminalMap } from '../composables/TerminalMap'
import config from '@/config';
const { t, locale } = useI18n()
import useRouter from "@/hooks/useRouter";
const router = useRouter();
const props = defineProps({
    visible: { type: Boolean, default: false },
    mtType: { type: String, default: 'MT4', validator: val => ['MT4', 'MT5'].includes(val) }
})
const emit = defineEmits(['update:visible'])
const handleClick = () => {
    router.push("/pages/common/download")
}
// ---------- 平台相关 ----------
const platform = ref('')
const baseUrl = ref('')
const domain = ref('')

// 获取当前运行平台
const getPlatform = () => {
    // #ifdef APP-PLUS
    const sys = uni.getSystemInfoSync()
    return sys.platform === 'android' ? 'android' : 'ios'
    // #endif
    // #ifdef H5
    const ua = navigator.userAgent.toLowerCase()
    if (ua.includes('windows')) return 'windows'
    if (ua.includes('mac')) return 'mac'
    if (ua.includes('android')) return 'android'
    if (ua.includes('iphone') || ua.includes('ipad')) return 'ios'
    return 'windows'
    // #endif
}

// 初始化环境变量（域名、基础URL）
const initEnv = () => {
    baseUrl.value = config.Host80
    domain.value = config.ho
}

// 替换 URL 中的占位符
const resolveUrl = (urlTemplate) => {
    if (!urlTemplate) return ''
    let url = urlTemplate
    if (url.includes('{myLink}')) {
        url = url.replace(/{myLink}/g, baseUrl.value)
    }
    if (url.includes('{domain}')) {
        url = url.replace(/{domain}/g, domain.value)
    }
    return url
}

// 获取当前 MT 版本的数据
const mtData = computed(() => TerminalMap[props.mtType] || {})

// Web 端标题（根据版本显示不同标题）
const webTitle = computed(() => {
    return props.mtType === 'MT4' ? t('Downloadpage.item38') : t('Downloadpage.item39')
})

// 根据当前 MT 版本和平台，获取对应的下载端信息
const downloadItem = computed(() => {
    const data = mtData.value
    if (!data) return null

    let item = null
    if (platform.value === 'windows' || platform.value === 'mac') {
        const list = data.desktop?.[platform.value] || []
        item = list[0]
    } else if (platform.value === 'android' || platform.value === 'ios') {
        const list = data.mobile?.[platform.value] || []
        item = list[0]
    }

    if (!item) return null

    // 构造显示名称和描述（国际化）
    let name = ''
    let description = ''
    if (item.name) {
        name = item.name
        description = item.descriptionKey ? t(item.descriptionKey) : (item.description || '')
    } else if (item.nameKey) {
        name = t(item.nameKey)
        description = item.descriptionKey ? t(item.descriptionKey) : ''
    }

    // 图标路径处理
    let icon = item.icon || ''
    if (platform.value === 'android' && !icon) icon = 'android-os-3-72.png'
    if (platform.value === 'ios' && !icon) icon = 'apple-os-3-72.png'
    if (platform.value === 'windows' && !icon) icon = 'windows-os-1-48.png'
    if (platform.value === 'mac' && !icon) icon = 'apple-os-1-48.png'

    return {
        url: resolveUrl(item.url),
        filename: item.filename,
        name,
        description,
        icon
    }
})

// 获取 Web 端链接（根据当前 MT 版本和语言）
const webUrl = computed(() => {
    const data = mtData.value
    if (!data || !data.web) return ''
    let url = data.web.url
    // 替换动态变量
    url = resolveUrl(url)
    // 替换语言占位符（{lang}）
    url = url.replace(/{lang}/g, locale.value)
    return url
})

// 处理 Web 端点击
const handleWebClick = () => {
    if (!webUrl.value) {
        uni.showToast({ title: t('Downloadpage.invalidLink') || '链接无效', icon: 'none' })
        return
    }
    // #ifdef APP-PLUS
    plus.runtime.openURL(webUrl.value, (err) => {
        uni.showToast({ title: t('Downloadpage.openFailed') || '打开失败，请重试', icon: 'none' })
    })
    // #endif
    // #ifdef H5
    window.location.href = webUrl.value
    // #endif
}

// 处理下载端点击
const handleDownloadClick = () => {
    if (!downloadItem.value || !downloadItem.value.url) {
        uni.showToast({ title: t('Downloadpage.unsupported') || '暂不支持当前平台下载', icon: 'none' })
        return
    }

    const url = downloadItem.value.url
    // #ifdef APP-PLUS
    plus.runtime.openURL(url, (err) => {
        uni.showToast({ title: t('Downloadpage.openFailed') || '打开失败，请重试', icon: 'none' })
    })
    // #endif
    // #ifdef H5
    if (url.match(/\.(exe|dmg|pkg|apk|zip)$/i)) {
        const a = document.createElement('a')
        a.href = url
        a.download = downloadItem.value.filename || ''
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
    } else {
        window.open(url, '_blank')
    }
    // #endif
}

// 初始化
onMounted(() => {
    platform.value = getPlatform()
    initEnv()
})
</script>

<style scoped lang="scss">
@import "@/uni.scss";

@media (min-width: 768px) {
    :deep(.cwg-dialog) {
        background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
        border-radius: px2rpx(8);
        width: px2rpx(600) !important;
    }
}

.card-list {
    display: flex;
    flex-direction: column;
    gap: px2rpx(12);
}

.card {
    display: flex;
    align-items: center;
    background-color: rgba(108, 133, 149, 0.08);
    border-radius: px2rpx(12);
    padding: px2rpx(14) px2rpx(12);
    border: 1px solid rgba(108, 133, 149, 0);
    transition: background-color 0.2s;

    &:hover {
        border: 1px solid rgba(108, 133, 149, 0.2);
    }
}

.card-icon {
    width: px2rpx(54);
    height: px2rpx(54);
    background-color: #141D22;
    border-radius: px2rpx(12);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: px2rpx(12);
    flex-shrink: 0;

    .icon-image {
        width: px2rpx(32);
        height: px2rpx(32);
    }
}

.card-content {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.card-title {
    font-size: px2rpx(14);
    font-weight: 600;
    line-height: 1.4;
    color: #fff;
}

.card-desc {
    font-size: px2rpx(14);
    color: #A0B0C0;
    margin-top: 8rpx;
}

.card-arrow {
    width: px2rpx(24);
    height: px2rpx(24);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 16rpx;
    flex-shrink: 0;
    color: #fff;
}
</style>