<script lang="ts" setup>
import { useScanStore } from '@/store'

definePage({
  style: {
    navigationBarTitleText: '扫码录入',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})

const scanStore = useScanStore()
const notifyRef = ref<any>(null)
const flash = ref<'on' | 'off' | 'auto' | 'torch'>('off')

// 扫码
function scanCode(e: any) {
  const { detail } = e
  const codeStr = detail.result
  const codeObj = {
    IMEI: '',
    SN: '',
  }

  if (codeStr) {
    uni.vibrateShort({})
    const codeArr = codeStr.split(' ')
    codeObj.IMEI = codeArr[0].replace('IMEI:', '')
    codeObj.SN = codeArr[1].replace('SN:', '')

    // 储存仓库
    scanStore.addScanCarNumber(codeObj)
    notifyRef.value?.show({ type: 'success', message: `已添加 IMEI：${codeObj.IMEI}，SN：${codeObj.SN}`, duration: 1500 })
  }
}

function handleFlash() {
  uni.vibrateShort({})
  flash.value = flash.value === 'off' ? 'on' : 'off'
}
</script>

<template>
  <camera
    mode="scanCode"
    device-position="back"
    style="width: 100%; height: 100vh"
    :flash="flash"
    @scancode="scanCode"
  >
    <view class="camera_UI">
      <!-- 闪光灯 -->
      <view class="flash_bar">
        <view class="flash" @tap="handleFlash">
          <uv-icon
            :name="flash === 'off' ? 'shanguangdeng-kai' : 'shanguangdeng-guan' "
            custom-prefix="custom-icon"
            size="28"
            color="#ffffff"
          />
        </view>
      </view>
    </view>
    <uv-notify ref="notifyRef" />
  </camera>
</template>

<style lang="scss" scoped>
.camera_UI {
  position: fixed;
  bottom: 250rpx;
  left: 0;
  width: 100%;
  z-index: 999;

  .flash_bar {
    display: flex;
    justify-content: center;
    align-items: center;

    .flash {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      background: #ffffff82;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
