<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.materialName}}
                            </view>
                            <view>
                                {{item.specificationNumber}}
                            </view>
                            <view>
                                {{item.proposedPosition}}
                            </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(1)' 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" :loading="manualStorageLoading">
                <uni-icons type="upload-filled"></uni-icons>
                一键入库</button>
        </view>
        <view class="button-container" v-if="type==2">
            <button class="btn" type="default" @click='startScan(2)' 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" :loading="reportLoad">
                <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,
        arrToId,
        arrToKey
    } from "js-fast-way";
    import mainApi from '~api/storage.js';


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

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

    onLoad((options) => {
        type.value = options.type
        codeIds.value = ''
        storageIds.value = ''
        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(type.value)
            }
        }
    }


    //开始扫描
    const isShowStartBtn = ref(true)
    const scanLoad = ref(false)
    const isScan = ref(false)
    const startScan = (type) => {
        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, type)
            }
        })
    }

    //扫描结果处理
    const codeIds = ref('')
    const scanDatas = ref([])
    const startScanData = async (data, type) => {
        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
        if (epcs.length === 1) {
            codeIds.value = epcs[0]

        } else {
            codeIds.value = epcs.join(',')
        }

        getResult(type,codeIds.value)

    }
    const storageIds = ref('')
    //获取扫描结果
    const getResult = async (type,ids) => {
        console.log('发请求', type);
        console.log(ids, 'ids');

        const {
            response,
            error,
            code,
            data
        } = await mainApi.getSelectRfidListById({
            rids:ids,
            state: type
        });

        //处理数据
        if (!error && code === 200) {
            console.log(listArr.value, ' listArr.value');
            listArr.value = getArrValue(data);
            storageIds.value = arrToId(listArr.value)
        } else {
            listArr.value = [];
            storageIds.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([])

    //一键入库
    const manualStorageLoading = ref(false)
    const toStorageClick = async () => {
        if (!isShowStartBtn.value) {
            uni.showToast({
                title: '请先停止扫描',
                icon: 'none',
                duration: 3000
            })
            return;
        }


        if (storageIds.value.length < 1) {
            return;
        }
          manualStorageLoading.value = true;
        const {
            error,
            code,
            msg,
            response
        } = await mainApi.update({
            id: storageIds.value,
            sampleStatus: 2,
        });

        manualStorageLoading.value = false;
        if (!error && code === 200) {
            uni.showToast({
                title: '操作成功',
                duration: 2000,
                mask: true
            });
            getResult(storageIds.value,1).then();
        } else {
            uni.showToast({
                title: '操作失败',
                duration: 2000,
                mask: true
            });
        }
    }
    const clearItem = (item, index) => {
        listArr.value.splice(index, 1);
       storageIds.value = arrToId(listArr.value)
    }


    //一键检测
    const reportLoad = ref(false)
    const toReport = async () => {
        if (!isShowStartBtn.value) {
            uni.showToast({
                title: '请先停止扫描',
                icon: 'none',
                duration: 3000
            })
            return;
        }

        if (storageIds.value.length < 1) {
            return;
        }
         reportLoad.value = true;
        const {
            error,
            code,
            msg,
            response
        } = await mainApi.update({
            id: storageIds.value,
            sampleStatus: 4,
            expCount: 0
        });

        reportLoad.value = false;
        if (!error && code === 200) {
            uni.showToast({
                title: '操作成功',
                duration: 2000,
                mask: true
            });
            getResult(2,storageIds.value).then();
        } else {
            uni.showToast({
                title: '操作失败',
                duration: 2000,
                mask: true
            });
        }
    }
</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;
        /* 右对齐 */
        z-index: 100;
    }

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

    }
</style>
