<script setup lang="ts">
import type { IExportJson } from '@/components/mt-edit/components/types'
import { useGenThumbnail } from '@/components/mt-edit/composables/thumbnail'
import { MtEdit } from '@/export'
import { useRouter } from 'vue-router'
import { addCanvas, audit } from '@/api/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDataStore } from '@/stores/menuList'

const router = useRouter()
const useData = useDataStore()
const onPreviewClick = (exportJson: IExportJson) => {
    sessionStorage.setItem('exportJson', JSON.stringify(exportJson))
    const routeUrl = router.resolve({
        name: 'preview'
    })
    window.open(routeUrl.href, '_blank')
}
const onSaveClick = (e: IExportJson) => {
    console.log(e, '这是要保存的数据')
}

const onSaveAll = (data: any) => {
    let params = { fileContent: '', id: useData.pid, name: useData.name }
    addCanvas(data).then((res: any) => {
        if (res.code == 'A0000') {
            ElMessage({
                message: '保存成功',
                type: 'success'
            })
            // 获取截图参数
            useGenThumbnail().then(item => {
                params.fileContent = item ?? ''
                audit(params).then(() => {
                    if (res.code == 'A0000') {
                        //
                    }
                })
            })
            ElMessageBox.confirm('是否关闭页面?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    try {
                        // 尝试关闭窗口
                        window.close()
                        // 检查是否关闭成功（某些情况下窗口可能未关闭）
                        setTimeout(() => {
                            if (!window.closed) {
                                // 如果未成功关闭，使用替代方案
                                window.location.href = 'about:blank'
                            }
                        }, 1000)
                    } catch (error) {
                        // 出现异常时使用替代方案
                        window.location.href = 'about:blank'
                    }
                })
                .catch(() => {})
        }
    })
}

const onReturnClick = () => {
    router.go(-1)
}
const onThumbnailClick = () => {
    useGenThumbnail()
}
</script>

<template>
    <div class="w-1/1 h-100vh" v-loading="useData.loading">
        <mt-edit
            :use-thumbnail="true"
            @on-preview-click="onPreviewClick"
            @on-return-click="onReturnClick"
            @on-save-click="onSaveClick"
            @on-thumbnail-click="onThumbnailClick"
            @on-save-all="onSaveAll"
        ></mt-edit>
    </div>
</template>

<style scoped></style>
