<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { debounce } from "lodash";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { Message } from '@arco-design/web-vue';

const autoCopy = ref(false);
let unlisten: Function;
const loading = ref(false);
const form = reactive<{
	in: null | string;
	out: null | string;
	}>({
	in: null,
	out: null,
});

const copy = () => {
	invoke("copy", { content: form.out });
	Message.success("复制成功");
}

const changeIn = debounce(async () => {
	loading.value = true;
	form.out = null;
	await invoke("translate_steam", { content: form.in });
    if (autoCopy.value) copy();
	loading.value = false;
}, 500);

const listen_start = async () => {
	unlisten = await listen("translate_steam", (event) => {
		loading.value = false;
		if (!form.out) form.out = "";
		form.out += event.payload;
	});
}

onMounted(() => {
	listen_start();
});

onUnmounted(() => {
	unlisten();
});
</script>

<template lang="pug">
    div.w-full.p-3.h-screen
        div.content
            div.content-item
                div.content-header 中文
                div.content-hr
                div.content-body
                    textarea(v-model="form.in" @input="changeIn").content-body-textarea
            div.content-item
                div.content-header.flex.items-center.justify-between
                    div 英文
                    div.flex.items-center.gap-2
                        div.text-info 自动复制
                        a-switch(v-model:model-value="autoCopy")
                div.content-hr
                div.content-body
                    view(v-if="loading") 加载中...
                    textarea(v-model="form.out" v-else).content-body-textarea
                    a-button.content-body-copy-btn(@click="copy()") 复制
</template>

<style lang="scss" scoped>
@reference "../../style/tailwindcss.css";

.content {
	@apply grid grid-cols-2 gap-3 h-full;
	&-item {
		@apply w-full bg-white rounded-xl overflow-hidden flex flex-col;
	}
	&-header {
		@apply p-3;
	}
	&-hr {
		@apply h-[1px] bg-[#ddd] w-full;
	}
	&-body {
		@apply p-3 flex flex-grow relative;
		&-textarea {
			@apply flex-grow min-h-[150px] p-3;
		}
        &-copy-btn {
            @apply absolute right-[24px] bottom-[24px];
        }
	}
}
</style>
