<template>
	<view class="container">
                <scroll-view scroll-y="true" class="scroll-list"
				>
					<uni-list>
								<uni-list-item border v-for="(item, index) in listArr">
									<template v-slot:header>
										<view class="slot-box">
											<image class="slot-image" src="/static/girder.png" mode="widthFix" style="width: 50px; height: 50px;"></image>
										</view>
									</template>
									<template v-slot:body>
										<view class="ml-6" style="font-size: 14px;">
										    <view class="name">
										      {{item}}
										    </view>
										    <view>
										        {{item}}
										    </view>
										    <view>
										        {{item}}
										    </view>
										</view>
									</template>
									<template v-slot:footer>
										<uni-icons type="close" color="#999" size="20" style="position: absolute; right: 20px;" @click="clearItem(item,index)"></uni-icons>
									</template>
								</uni-list-item>
							</uni-list>
				</scroll-view>
              <view class="button-container" v-if="type==1">

                   <button class="btn"  type="default" @click='startScan' v-if="isShowStartBtn" :loading="scanLoad">
                       <uni-icons type="scan"></uni-icons>

                       开始扫描

                   </button>
                    <button class="btn"  type="default" @click='stopScan' v-if="!isShowStartBtn">
                        <uni-icons type="circle-filled"></uni-icons>

                        停止扫描</button>
                    <button class="btn"  type="default" @click="toStorageClick">
                          <uni-icons type="upload-filled"></uni-icons>
                        一键入库</button>
              </view>
              <view class="button-container"  v-if="type==2">
                   <button class="btn"  type="default" @click='startScan' v-if="isShowStartBtn" :loading="scanLoad">
                        <uni-icons type="scan"></uni-icons>
                       开始扫描</button>
                    <button class="btn"  type="default" @click='stopScan' v-if="!isShowStartBtn">
                         <uni-icons type="circle-filled"></uni-icons>
                        停止扫描</button>
                    <button class="btn"  type="default" @click="toReport">
                         <uni-icons type="upload"></uni-icons>
                        一键生成报告</button>
             </view>
	</view>
</template>

<script setup>
    import {
        onMounted,
        ref,
        watch
    } from "vue";
import {onLoad, onReady, onUnload} from '@dcloudio/uni-app'
import {getArrValue} from "js-fast-way";


// 获取 module
const rfidModule = uni.requireNativePlugin("DeviceModule_RFID");

//渲染完成
onReady(() => {
    // #ifdef APP-PLUS
    rfidModuleInit()
    // #endif
})

onLoad((options)=>{
    type.value=options.type
    if(options.type==1){
        title.value='样品入库'
    }else{
        title.value='样品检测'
    }
    uni.setNavigationBarTitle({
        title:title.value
    })
})
const title=ref('')
const type=ref('1')
// //按键操作
const isRfidInit = ref(true)
const rfidModuleInit = () => {
    isRfidInit.value = true
    uni.showLoading({
    	title: 'RFID模块加载中...',
        mask: true,
    });
    /**
        手机按键监听事件，可在此编写一些逻辑，如使用按键触发扫描，更多详细信息请查阅uni官方文档
        需要注意：退出界面必须移除监听，否则再进入页面重复注册监听会出现多次触发、回调失效的问题
    */
    plus.key.addEventListener('keydown', keyListener);
    //初始化
    setTimeout(() => {
        // 使用模块前必须先初始化RDIF模块
        let { code } = rfidModule.init();
        if (code === 0) {
            uni.hideLoading();
        } else if (code === -1) {
            uni.hideLoading();
            uni.showToast({
                title: 'RFID模块加载失败',
                icon: 'error',
                duration: 3000
            })
        } else {
            uni.hideLoading();
        }
        isRfidInit.value = false
    }, 400);
}

//按键操作
const keyListener = ({keyCode}) => {
    if (keyCode === 293 || keyCode === 312) {
        if (isScan.value) {
            stopScan()
        } else {
            startScan()
        }
    }
}

//开始扫描
const isScan = ref(false)
const startScan = () => {
 isShowStartBtn.value=false
    if (isRfidInit.value) return
    isScan.value = true
    rfidModule.startScan((res) => {
        if (res.code === 0) {
            uni.showToast({
                icon: "success",
                title: '开启扫描成功'
            })
        } else if (res.code === 1) {
            startScanData(res.data)
        }
    })
}

//扫描结果处理
const scanDatas = ref([])
const startScanData = async (data) => {
    const arr = getArrValue(data)
    let epcs = scanDatas.value
    for (let i = 0; i < arr.length; i++) {
        const epc = arr[i].epc
        if (epcs.indexOf(epc) === -1) {
            epcs.push(epc)
        }
    }
    scanDatas.value = epcs
    console.log(scanDatas.value,'scanDatas.value');
    listArr.value=scanDatas.value
}

//停止扫描
const stopScan = () => {
    const { code } = rfidModule.stopScan()
    if (code === 0) {
        isScan.value = false
        uni.showToast({
            icon: "success",
            title: '关闭扫描成功'
        })
         isShowStartBtn.value=true
    } else {
        uni.showToast({
            icon: "error",
            title: res.message
        })
    }
}

//页面卸载
onUnload(()=>{
    // #ifdef APP-PLUS
    plus.key.removeEventListener('keydown', keyListener)
    // 使用完毕必须释放RDIF模块
    rfidModule.free();
    // #endif
})
const listArr=ref([
    {name:' 水泥（42.5级散装）',num:'SN20015678',postion:'路基、路面、桥梁、隧道'},
    {name:' 水泥（42.5级散装）',num:'SN20015678',postion:'路基、路面、桥梁、隧道'},

])
//开始扫描
const isShowStartBtn=ref(true)
const scanLoad=ref(false)

const toStorageClick=()=>{
    if(!isShowStartBtn.value){
        uni.showToast({
           title: '请先停止扫描',
           icon: 'none',
           duration: 3000
        })
    }
}
const clearItem=(item,index)=>{
    listArr.value.splice(index,1)
}
//一键入库
const storageLoad=ref(false)
//一键生成报告
const toReport=()=>{
    if(!isShowStartBtn.value){
        uni.showToast({
           title: '请先停止扫描',
           icon: 'none',
           duration: 3000
        })
    }
}
</script>

<style lang="scss" scoped>

.name{
    font-weight: bold;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 使容器高度为视口高度 */
}

.scroll-list {
  flex: 1; /* 占据剩余空间 */
  overflow-y: auto; /* 纵向滚动 */


}
.button-container {
    display: flex;
    justify-content: space-around; /* 两个按钮均匀分布 */
    padding: 10px;
    background-color: #fff; /* 背景色 */
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
    position: fixed; /* 固定在底部 */
    bottom: 0; /* 靠近底部 */
    left: 0; /* 左对齐 */
    right: 0; /* 右对齐 */
}

.btn {
  flex: 1; /* 每个按钮占据相同的空间 */
  margin: 0 5px; /* 按钮之间的间距 */
  border: none;
  border-radius: 5px;
  cursor: pointer;
  color: black;

}
</style>
