<template>
    <!-- 图纸展示 -->
    <div class="content">
        <el-image class="image-full" :src="imageData.base64" :fit="fit">
            <template #error>
                <div class="error-slot">
                    {{ imageData.errMsg }}
                </div>
            </template>
        </el-image>
    </div>
</template>
<script setup>
// 导入
import store from '@/store'
import { requestImageDetail } from '@/api/kateWork.js'
import { isSingleCharacter, isNumber } from '@/utils/stringUtils';
import { onBeforeUnmount, onMounted, reactive } from 'vue';
// 声明变量
const USER_NAME = store.getters.getUserName
const STAND_ID = store.getters.getStandId
const fit = 'contain'
let imageData = reactive({
    url: '',
    base64: '',
    name: '',
    errMsg: ''
})
let inputStr = ''
let imageRequest = reactive({
    imageId: '',
    userName: USER_NAME,
    standId: STAND_ID
})
// 声明系统方法
onMounted(() => {
    document.addEventListener('keydown', handleKeyDown)
})
onBeforeUnmount(() => {
    document.removeEventListener('keydown', handleKeyDown)
})
// 声明自定义方法
const handleKeyDown = (event) => {
    if (event.key.toLowerCase() === 'enter') {
        solveInput()
    } else {
        if (event.key.toLowerCase() === 'backspace') {
            inputStr = inputStr.substring(0, inputStr.length - 1)
        } else if (isSingleCharacter(event.key) || isNumber(event.key)) {
            inputStr += event.key
        }
    }
}
// 处理输入
const solveInput = () => {
    // 空输入
    if (inputStr === '') {
        closePreview('空输入。')
    }
    // 解析
    imageRequest.imageId = inputStr
    // 查询图纸
    findImage()
}
// 查询图纸
const findImage = () => {
    if (imageRequest.imageId === '') {
        closePreview('请求缺少图纸编号。')
    }
    requestImageDetail(imageRequest).then(res => {
        const response = res.data
        if (response.code === 0) {
            const results = response.data
            if (results === undefined || results.length !== 1) {
                closePreview('无图纸或图纸歧义。')
                return
            }
            const image = results[0]
            openPreview(image)
        } else {
            closePreview(response.message)
        }
    }).catch(err => {
        console.log(err)
        closePreview("查询图纸失败，请检查。")
    }).finally(() => {
        inputStr = ''
    })
}
// 打开图纸
const openPreview = (image) => {
    imageData.url = image.imageIp + image.imagePath + image.imageName
    imageData.base64 = 'data:image/png;base64,' + image.imageDetail
    imageData.name = image.imageName
    imageData.errMsg = ''
}
// 关闭图纸
const closePreview = (errMsg) => {
    imageData.url = ''
    imageData.base64 = ''
    imageData.name = ''
    imageData.errMsg = errMsg
}
</script>
<style scoped>
.content {
    width: 100%;
    height: 100%;
}

.image-full {
    width: 100%;
    height: 100%;
}

.image-full .error-slot {
    color: red;
    font-size: 50px;
    font-weight: bold;
}
</style>