<template>
    <ui-window v-if="show" @ok="onOk" @no="onNo" :showCloseIcon="false" :showCancelButton="false">
        <template v-slot:content>
            <div class="wrapper">
                <ui-input type="password" placeholder="请输入浏览密码" maxlength="4" v-model.trim="password" width="100%" @input="onPasswordChange" @keyup.enter="onOk" />
                <span class="error">{{ error }}</span>
            </div>
        </template>
    </ui-window>
</template>
<script setup>
import { ref, watch, computed, onMounted, defineProps } from 'vue'
import { useStore } from 'vuex'
import { getApp, getNum } from '@/app'
import { Dialog } from '@/global_components/'

const show = ref(false)
const store = useStore()
const metadata = computed(() => store.getters['scene/metadata'])
const error = ref('')
const password = ref('')
const onOk = () => {
    let app = getApp()

    error.value = ''

    if (!password.value) {
        return (error.value = '请输入密码')
    }

    app.remote_viewer
        .check_key({
            num: getNum(),
            password: password.value,
        })
        .then(response => {
            if (response.success) {
                show.value = false
                app.Scene.unlock()
            } else {
                error.value = '密码错误'
            }
        })
        .catch(error => {
            Dialog.toast('操作失败，请稍后再试')
        })
}
const onNo = () => {
    show.value = false
}
const onPasswordChange = e => {
    password.value = e.target.value.replace(/[^\w]/g, '').replace(/_/g, '')
}
watch(metadata, () => {
    if (metadata.value) {
        if (metadata.value.controls.showLock) {
            show.value = true
        } else {
            getApp().Scene.unlock()
        }
    }
})
</script>
<style lang="scss" scoped>
.wrapper {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.error {
    height: 18px;
    margin-top: 10px;
    color: red;
    text-align: left;
    width: 100%;
    padding-left: 10px;
}
</style>
