<template>
  <u-popup v-model="show" mode="bottom">
    <view class="popup_box">
      <view class="pop_title uni-flex space-between">
        <view class="" style="font-size: 35rpx"> 扫描{{ title }} </view>
        <view>
          <image class="icons_scan_close" src="/static/icons/icons_scan_close.svg" @click="closeScanPopup()"> </image>
        </view>
      </view>
      <view class="">
        <view class="">
          <win-com-scan ref="scan" headerType="HCQ" @getResult="getScanResult" :placeholder="title" :clearResult="true" :boxFocus="true" :isShowHistory="isShowHistory"> </win-com-scan>
        </view>
      </view>
    </view>
  </u-popup>
  <com-message ref="comMessageRef" />
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue'
import { getContainerByNumber } from '@/api/request2.js'
import winComScan from '@/mycomponents/scan/winComScan.vue'

const { proxy } = getCurrentInstance()
const props = defineProps({
  title: {
    type: String,
    default: '器具'
  },
  isShowHistory: {
    type: Boolean,
    default: false
  }
})
const code = ref('')
const containerInfo = ref({})
const show = ref(false)
const scan = ref()
const comMessageRef = ref()
const openScanPopup = () => {
  setTimeout((res) => {
    show.value = true
  }, 500)
}
const closeScanPopup = () => {
  losefocus()
  show.value = false
}
const scanClick = () => {
  scan.value.clickScanMsg()
}
const cancelClick = () => {
  scan.value.clearScanValue()
}

const getScanResult = (result) => {
  proxy.$modal.loading('扫描中...')
  const { label } = result
  code.value = label.container
  getContainerByNumber(code.value)
    .then((res) => {
      uni.hideLoading()
      if (res.data.list.length > 0) {
        containerInfo.value = res.data.list[0]
        if (containerInfo.value.containerStatus == 'USED') {
          callBack()
        } else {
          showErrorMessage(`器具[${code.value}]状态是[${containerInfo.value.status}],不可以绑定`)
        }
      } else {
        showErrorMessage(`未查找到器具[${code.value}]`)
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showErrorMessage(error)
    })
}
const callBack = () => {
  closeScanPopup()
  emit('getContainer', containerInfo.value)
}
const getfocus = () => {
  if(scan.value) {
    scan.value.getfocus()
  }
}
const losefocus = () => {
  if (scan.value) {
    scan.value.losefocus()
  }
}
const showErrorMessage = (message) => {
  setTimeout((r) => {
    losefocus()
    comMessageRef.value.showErrorMessage(message, (res) => {
      code.value = ''
      getfocus()
    })
  })
}
// 传递给父类
const emit = defineEmits(['getContainer'])
defineExpose({
  openScanPopup
})
</script>

<style></style>
