<script lang="ts" setup>
import {appMerchantOrderWriteOffPost} from '@/service'

const {t} = useI18n()

const {barcode, createBarcode} = useScanCode()

function useScanCode() {
  // 扫码框
  const barcode = ref<PlusBarcodeBarcode | null>(null)

  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  // webview容器
  const currentWebview = page.$getAppWebview()
  console.log('webview', currentWebview)

  // 扫码成功回调
  async function handleOnMarked(type: number, result: any) {
    console.log(type, result)

    if (result) {
      const data = result.trim()
      console.log('result', data)
      if (data.includes('DO') || data.includes('DO_')) {
        try {
          await appMerchantOrderWriteOffPost({
            params: {
              orderNo: data,
            }
          })
          await uni.navigateBack()
          await uni.showToast({
            title: t('toast.orderWriteOffSuccess'),
            icon: 'none',
          })
        } catch (e) {
        }
      }
    }
  }

  // 创建窗口和扫码控件
  function createBarcode() {
    // 【步骤2】判断有没有创建过 扫码框，如果没有就执行创建操作
    if (!barcode.value) {
      barcode.value = plus.barcode.create(
          'barcode',
          [plus.barcode.QR], // 只扫二维码
          {
            top: '0px',
            left: '0px',
            width: '100%',
            height: '100%',
            position: 'absolute',
            scanbarColor: '#333',
            frameColor: '#333',
          },
      )

      barcode.value.onmarked = handleOnMarked // 扫码结果回调函数

      const closeView = new plus.nativeObj.View(
          'close',
          {
            top: '60px',
            left: '30px',
            width: '25px',
            height: '25px',
            position: 'absolute',
          },
          [
            {
              tag: 'img',
              id: 'img',
              src: '/static/app/images/13997@2x.png',
              position: {
                top: '0',
                left: '0',
                width: '25px',
                height: '25px',
              },
            },
          ],
      )
      closeView.addEventListener('click', (event: any) => {
        console.log('event', event)
        uni.navigateBack()
      })
      // 【步骤3】将扫码框添加到 webview 里
      currentWebview.append(barcode.value as any)
      currentWebview.append(closeView)
    }

    console.log('barcode', barcode)
    barcode.value?.start()
  }

  return {
    barcode,
    createBarcode,
  }
}

onLoad(() => {
  createBarcode()
})

onUnload(() => {
  barcode.value?.cancel()
  barcode.value?.close()
  barcode.value = null
})
</script>
<template>
  <view></view>
</template>

<style lang="scss" scoped></style>
