<!--
 * @Author: micky
 * @Date: 2024-10-06 10:32:23
 * @LastEditors: micky
 * @LastEditTime: 2024-10-19 15:28:24
 * @FilePath: \chargingpile-uniapp\src\bundle\pages\charge\scan-module.vue
-->
<template>
    <w-page-common
        :btnText="btnText"
        @submit="submit"
        :needPadding="false"
        :btnDisabled="dataList.length === 0"
    >
        <view class="flex flex-col h-full">
            <w-scan v-model="scanResultCode"></w-scan>
            <view class="mt-3 flex-1 overflow-auto">
                <module-item ref="moduleItemRef" v-model="dataList"></module-item>
            </view>

            <view class="custom-input flex justify-center" @click="toManual">
                <u-icon name="edit-pen" color="#7C7E82" size="24"></u-icon>
                手动输入条码
            </view>
        </view>
    </w-page-common>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, unref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import ModuleItem from './components/module-item.vue'
import { toast } from '@/utils/util'

const moduleItemRef = ref()
const scanResultCode = ref('')
const dataList = ref<AddModuleItem[]>([])
const btnText = computed(() => {
    return `确定录入${dataList.value.length}条数据`
})

const submit = () => {
    const hasEmpty = dataList.value.find(item => {
        return !item.moduleNumber || !item.modulePower
    })
    if (hasEmpty) return toast('请填写完整的信息！')
    uni.$emit('moduleList', unref(dataList))
    uni.navigateBack({
        delta: 1
    })
}

// 手动输入条码
const toManual = () => {
    const params = encodeURIComponent(JSON.stringify(dataList.value))
    uni.navigateTo({
        url: `/bundle/pages/charge/manual-input?params=${params}`
    })
}

// 扫描到条形码了，请求接口详情数据
watch(scanResultCode, val => {
    moduleItemRef.value.addItem(val)
})

onLoad(async options => {
    if ('params' in options) {
        const data = JSON.parse(decodeURIComponent(options.params!))
        await nextTick()
        moduleItemRef.value.setItem(data)
    }
})
</script>
<style scoped lang="scss">
.custom-input {
    @apply fixed left-0 w-full py-1 text-gray2 z-10;
    background-color: $gray-1;
    margin-bottom: 96rpx;
    bottom: Max(env(safe-area-inset-bottom), 24rpx);
}
</style>
