<template>
    <view class="container">
        <view class="main-content">
            <view class="input-group">
                <u-input :customStyle="customStyle" :placeholder-style="placeholderStyle" v-model="form.isbn"
                    placeholder="扫描/输入ISBN" border="surround" />
                <u-button :customStyle="customStyle" type="info" color="#a4adb3" @click="handleBarcode(form.isbn)"
                    text="确定" />
            </view>
        </view>

        <view class="fixed-bottom">
            <u-button size="large" type="success" @click="scanCode" text="扫码" class="scan-button" />
        </view>
    </view>
</template>

<script setup>
import {
    reactive,
    ref,
    onUnmounted
} from 'vue';
import {
    onLoad,
    onShow
} from '@dcloudio/uni-app'

const placeholderStyle = "font-size:32rpx"
const customStyle = reactive({
    height: '90rpx'
})

const form = ref({
    "isbn": ""
})

function scanCode() {
    uni.scanCode({
        success: (res) => {
            form.value.isbn = res.result;
            handleBarcode(res.result)
        },
        fail: (err) => {
            uni.$u.toast('扫码失败')
        }
    });
}

//isbn正则校验是否符合
function checkIsbn(isbn) {
    const isbn13Regex = /^(?:97[89]-?\d{1,5}-?\d{1,7}-?\d{1,6}-?\d)$/;
    if (isbn13Regex.test(isbn)) {
        return true;
    }
    return false;
}

function handleBarcode(code) {
    if (!code) return uni.$u.toast('请输入ISBN')

    // 验证ISBN格式
    if (!checkIsbn(code)) {
        return uni.$u.ttsModule.speak('不是正确的ISBN码')
    }

    // 这里可以添加ISBN查询逻辑
    uni.$u.http.post('/activation/bookActivationInfo/queryBookBasicByIsbn/' + code).then(res => {
        if (res.code == 200) {
            // 处理查询成功的逻辑
            uni.navigateTo({
                url: '/pages/index/wms/code-storage-add?isbn=' + code
            })
            form.value.isbn = ""
            // 传递书籍信息到下一页
            uni.setStorageSync('bookInfo', res.data)
        } else {
            uni.$u.toast('未找到该书籍')
        }
    })
}

// #ifdef APP-PLUS
const { unregister } = uni.$u.useEventListener((e) => {
    form.value.isbn = e.barcode
    handleBarcode(e.barcode)
});
// #endif

onUnmounted(() => {
    // #ifdef APP-PLUS
    unregister();
    // #endif
});
</script>

<style lang="scss" scoped>
.main-content {
    padding: 20px;
    gap: 20px;
}

.input-group {
    display: flex;
    gap: 10px;
    margin-bottom: 30rpx;

    :deep(.u-button) {
        width: 160rpx
    }

    .u-input {
        background-color: #fff;
    }
}

.scan-button {
    width: 100%;
}
</style>