<template>
    <view class="container">
        <!-- 库位列表 -->
        <scroll-view scroll-y class="location-list" :style="{ height: scrollHeight + 'px' }">
            <view v-for="(item, index) in filteredLocations" :key="index" class="location-item"
                hover-class="location-item-hover" @click="selectLocation(item)">
                <text>{{ item.code }}</text>
            </view>
        </scroll-view>

        <!-- 底部搜索框 -->
        <view class="fixed-bottom pad-20" style="background: #ffffff;">
            <u-search v-model="searchText" placeholder="请输入库位条码" :show-action="false" :clearabled="true"
                @change="onSearch" height="40" :disabled="true" @click="searchText = ''">
            </u-search>
            <u-icon name="scan" size="28" color="#19be6b" @click="openScan"></u-icon>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 搜索文本
const searchText = ref('')

// 库位列表数据
const locations = ref([
    { code: 'k001-0121' },
    { code: 'k001-0113' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
    { code: 'k001-0111' },
])

// 滚动区域高度
const scrollHeight = ref(0)

// 过滤后的库位列表
const filteredLocations = computed(() => {
    if (!searchText.value) return locations.value
    return locations.value.filter(item =>
        item.code.toLowerCase().includes(searchText.value.toLowerCase())
    )
})

// 搜索处理
const onSearch = () => {
    // 实现搜索逻辑
}

// 打开扫码
const openScan = () => {
    // #ifdef APP-PLUS || MP-WEIXIN
    uni.scanCode({
        success: (res) => {
            searchText.value = res.result
            onSearch()
        },
        fail: (err) => {
            uni.showToast({
                title: '扫码失败',
                icon: 'error'
            })
        }
    })
    // #endif

    // #ifdef H5
    uni.showToast({
        title: 'H5环境不支持扫码',
        icon: 'none'
    })
    // #endif
}

// 选择库位
const selectLocation = (item) => {
    // 获取页面实例
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    // 也可以使用事件总线或页面参数的方式传值
    uni.$emit('updateLocation', item.code)
    
    // 返回上一页
    uni.navigateBack()
}

// 计算滚动区域高度
onMounted(() => {
    const systemInfo = uni.getSystemInfoSync()
    // 减去标题栏高度和搜索框高度
    scrollHeight.value = systemInfo.windowHeight - 44 - 60
})
</script>

<style scoped>
.container {
    position: relative;
}

.location-list {
    padding: 12px 0 60px;
}

.location-item {
    background-color: #fff;
    padding: 15px;
    margin-bottom: 1px;
    font-size: 14px;
}
</style>