<template>
    <mobile-sub-layout :title="t('mail.title2')" :bgColor="themeStore.theme.bgColor">
        <view class="mail-header flex flex-column justify-center"
            :style="{ borderColor: themeStore.theme.mail.subTitle }">
            <view class="w-full mail-header-title" :style="{ color: themeStore.theme.mail.light }">{{ mailData.title }}
            </view>
            <view class="mail-header-subtitle" :style="{ color: themeStore.theme.mail.subTitle }">
                {{ mailData.createTime }}</view>
        </view>
        <view class="mail-content" :style="{ color: themeStore.theme.mail.light }">
            <!-- {{ mailData.content }} -->
            <rich-text :nodes="mailData.content" @itemclick="onItemClick" @click="handleClick" />
            <!-- <uv-parse :content="mailData.content" @linktap="onLinkTap" @imgtap="onImageTap"></uv-parse> -->
        </view>
        <view v-if="mailData.attaches" class="amount-tip" :style="{ color: themeStore.theme.mail.sendTip }">{{
        $t('mail.tipPre') }}<text style="margin: 0 8rpx;">{{ mailData.attaches.amount
                }}</text>{{ $t('mail.tipEnd') }}</view>
        <view v-if="mailData.attaches" class="attaches relative flex-center flex-column"
            :style="{ background: `top / cover no-repeat ${themeStore.theme.mail.receiveBg}` }">
            <theme-image src="@/static/mail/image_mail_jb.png" class="coin-img"></theme-image>
            <view class="mail-amount" :style="{ color: themeStore.theme.mail.amount }">{{ mailData.attaches?.amount }}
            </view>
            <theme-image v-if="mailData.attachesStatus === 1" src="@/static/mail/icon_getjb.png"
                class="coin-checked"></theme-image>
        </view>

        <empty-hold height="157rpx" />
        <view class="bottom-box safe-area" v-if="mailStore.mailList.length > 0">
            <view class="bottom-block flex-center">
                <view class="deleted-read btn-text flex-center" :style="{ color: themeStore.theme.mail.light }"
                    @click="deleteAll">{{ $t('mail.button.delete') }}</view>
                <view v-if="mailData.attaches && mailData.attachesStatus === 0" class="receive-all btn-text flex-center"
                    :style="{ color: themeStore.theme.account.confirmBtnTextColor }" @click="receiveAll">
                    {{ $t('mail.button.receive') }}
                </view>
            </view>
        </view>
        <!-- <uni-popup-dialog ref="popupDialog" type="warn" mode="base" :title="$t('mail.modal.title')"
            :content="$t('mail.modal.content')" :confirmText="$t('mail.modal.confirm')"
            :cancelText="$t('mail.modal.cancel')" @confirm="handleConfirm"></uni-popup-dialog> -->
        <Congratulation ref="congratulationRef" :prizeAmount="mailData.attaches?.amount || 0" />
    </mobile-sub-layout>
</template>
<script setup>
import { requestMailDel, requestMailRead, requestMailReceive } from '@/api/mail';
import { useMailStore } from '@/store/useMailStore';
import { useThemeStore } from '@/store/useThemeStore';
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';
import Toast from '@/module/toast/toast.js'
import { useI18n } from 'vue-i18n'
import Congratulation from '@/components/popup/Congratulation.vue';
import { openUrl } from '@/module/utils/openUrl'
// import UvParse from '@/uni_modules/uv-parse/components/uv-parse/uv-parse.vue'
// import htmlParser from '@/module/utils/htmlparser'

const { t } = useI18n()
const mailStore = useMailStore();
const mailId = ref('');
const congratulationRef = ref(null);
const mailData = computed(() => {
    const mail = mailStore.mailList.find((item) => item.id == mailId.value);
    if (mail) {
        if (mail.attaches && /^{.*}$/.test(mail.attaches)) {
            mail.attaches = JSON.parse(mail.attaches);
        }
        return mail
    }
    return {}
})
const onItemClick = (e) => {
    console.log("onItemClick:", e);
    const { href } = e.detail.node.attrs;
    if (href) {
        openUrl(href);
    }
}
const extractDataHref = (htmlString) => {
    if(!htmlString) return [];
    const regex = /data-href=["'](.*?)["']/g;
    const matches = [];
    let match;
    
    while ((match = regex.exec(htmlString)) !== null) {
        matches.push(match[1]); // 提取引号内的内容
    }
    
    return matches;
}
const handleClick = () => {
    const matches = extractDataHref(mailData.value?.content);
    console.log("matches:", matches);
    
    if(matches.length) {
        openUrl(decodeURIComponent(matches[0]));
    }
}
const onImageTap = (e) => {
    console.log("Image tap", e);
}
const onLinkTap = (e) => {
    console.log("Link tap", e);
}

const themeStore = useThemeStore();


const receiveAll = () => {
    requestMailReceive({ mailId: mailId.value }).then((res) => {
        if (res.totalData?.success) {
            // Toast.showSuccess()
            congratulationRef.value.open()
            mailStore.getMailList()
        } else {
            Toast.show(res.totalData?.msg ?? 'receive error', 'none')
        }
    }).catch(err => {
        Toast.show(err?.msg ?? 'receive error', 'none')
    })
}
const handleConfirm = () => {
    requestMailDel({ mailId: mailId.value }).then((res) => {
        console.log(res);

        if (res.totalData?.success) {
            Toast.showSuccess()
            uni.navigateBack()
        } else {
            Toast.show(res?.msg ?? 'delete error', 'none')
        }
    }).catch(err => {
        Toast.show(err?.message ?? 'delete error', 'none')
    })
}
const deleteAll = () => {
    // popupDialog.value.open();
    // return;
    uni.showModal({
        title: t('mail.modal.title'),
        content: t('mail.modal.content'),
        confirmText: t('mail.modal.confirm'),
        cancelText: t('mail.modal.cancel'),
        confirmColor: themeStore.theme.mail.popConfirm,
        success(res) {
            if (res.confirm) {
                requestMailDel({ mailId: mailId.value }).then((res) => {
                    console.log(res);

                    if (res.totalData?.success) {
                        Toast.showSuccess()
                        uni.navigateBack()
                    } else {
                        Toast.show(res.totalData?.msg ?? 'delete error', 'none')
                    }
                }).catch(err => {
                    Toast.show(err?.message ?? 'delete error', 'none')
                })
            }
        }
    })
}
const handleReadMail = async () => {
    await requestMailRead({ mailId: mailId.value });
}
onLoad((options) => {
    mailId.value = options.id;
    handleReadMail();
})
</script>
<style lang="scss" scoped>
.mail-header {
    height: 116rpx;
    border-bottom: 1px solid #E5E5E5;
    padding: 0 34rpx;

    .mail-header-title {
        font-family: Roboto;
        font-weight: 400;
        font-size: 30rpx;
    }

    .mail-header-subtitle {
        font-family: Roboto;
        font-weight: 400;
        font-size: 26rpx;
        margin-top: 12rpx;
    }
}

.mail-content {
    padding: 0 34rpx;
    margin-top: 54rpx;
    font-family: Roboto;
    font-weight: 400;
    font-size: 29rpx;
}

.amount-tip {
    margin-top: 30rpx;
    padding: 0 34rpx;
    font-family: Roboto;
    font-weight: 400;
    font-size: 29rpx;
}

.attaches {
    width: 140rpx;
    height: 140rpx;
    margin: 0 auto;
    margin-top: 50rpx;

    .coin-img {
        width: 111rpx;
        height: 76rpx;
    }

    .mail-amount {
        font-family: Roboto;
        font-weight: 400;
        font-size: 29rpx;
    }

    .coin-checked {
        position: absolute;
        top: 2px;
        right: 2px;
        width: 59rpx;
        height: 59rpx;
    }
}

.bottom-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: linear-gradient(0deg, #510206, #600800);
    box-shadow: 0rpx -3rpx 6rpx 1rpx rgba(0, 0, 0, 0.24);

    .bottom-block {
        width: 100%;
        height: 127rpx;
        font-size: 32rpx;

        .deleted-read {
            width: 275rpx;
            height: 73rpx;
            background: linear-gradient(0deg, #5F000B, #79000C);
            box-shadow: 0rpx 3rpx 0rpx 0rpx #420007;
            border-radius: 10rpx;
        }

        .receive-all {
            width: 275rpx;
            height: 73rpx;
            background: linear-gradient(180deg, #FFFBD1, #F6E07B, #C38F38, #E7B540);
            border-radius: 10rpx;
            box-shadow: 0rpx 6rpx 0rpx 0rpx rgba(50, 12, 6, 0.5);
            margin-left: 33rpx;
        }
    }
}
</style>