<script setup lang="ts">
import { nextTick, ref } from 'vue';
import QRCodeScanner from './QRCodeScanner.vue';

// defineProps<{ msg: string }>()

let result = ref('');
let count = ref(1);
let smscontent = ref('');

var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

const decodedCode = function (decodedText: string, decodedResult: any) {
    // console.log(`Scan result ${decodedText}`, decodedResult);
    if (decodedText.includes('1922:')) {
        smsto1922(decodedText);
    } else {
        result.value = `內容:${decodedText}`;
    }
}

function smsto1922(decodedText: string) {
    let contents = decodedText.split('1922:');
    let sms = contents[1];
    result.value = `內容:${sms}`;
    smscontent.value = sms;
    let Btn_Open = document.getElementById("Btn_Open")!;
    Btn_Open.style.display = "inline";
}

function OnclickOpen() {
    let addcount = "";
    if (count.value > 1) {
        addcount = `+${count.value - 1}`;
    }
    if (isAndroid) {
        window.open(`sms:1922?&amp;body=${smscontent.value}${addcount}`, "_self");
    } else if (isiOS) {
        window.open(`sms:1922&body=${smscontent.value}${addcount}`, "_self");
    } else {
        alert(`sms:1922&body=${smscontent.value}${addcount}`);
    }
}

async function onLoad(): Promise<void> {
    // 这里获取DOM的是旧值
    await nextTick()
    // nextTick 后获取DOM的是更新后的值
    let Btn_Open = document.getElementById("Btn_Open")!;
    Btn_Open.style.display = "none";
    if (!isAndroid && !isiOS) {
        let section = document.getElementById("section")!;
        section.style.width = '500px';
    }
}
onLoad();

</script>

<template>
    <div id="section" class="section" style="width: 70%; margin: auto;">
        <QRCodeScanner :qrbox="200" :fps="10" @decodedCode="decodedCode">
        </QRCodeScanner>
    </div>
    <div> {{ result }} </div>
    <div>
        <el-input-number v-model="count" :min="1" size="large" />
    </div>
    <el-button id="Btn_Open" type="success" @click.native="() => { OnclickOpen() }" size="large" round>按我傳送簡訊
    </el-button>
</template>