<template>
  <view class="p8">
    <navbar-back title="样品归库"></navbar-back>
    <uni-section type="line" title="库位编码" titleFontSize="15px"> </uni-section>
    <up-input
      v-model="locationCode"
      placeholder="请扫描库位编码"
      prefixIcon="scan"
      fontSize="16"
      prefixIconStyle="font-size: 30px;"
    >
    </up-input>
    <uni-section type="line" title="样品编号" titleFontSize="15px"> </uni-section>
    <up-input
      v-model="sampleCode"
      placeholder="请扫描样品编号"
      prefixIcon="scan"
      fontSize="16"
      prefixIconStyle="font-size: 30px;"
    >
      <template #suffix>
        <view class="fs18 font-bold" style="color: red" v-if="successCount > 0">{{ successCount }}</view>
      </template>
    </up-input>
    <up-button class="mt20" type="primary" style="width: 50%" text="清空" @click="handleReset"></up-button>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, toRefs, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { debounce } from 'lodash'
import nx from '@/nx'

const { scanQRInfo } = toRefs(nx.$store('biz'))
watch(scanQRInfo, newVal => {
  debouncedHandleScan(newVal)
})
const debouncedHandleScan = debounce(val => {
  if (!val) return
  scanQRInfo.value = ''
  if (nx.$router.getCurrentPage().route !== 'pages/sampleWarehouse/returnToStock/index') return
  try {
    if (nx.$helper.isJsonString(val)) {
      const codeObj = JSON.parse(val)
      if (codeObj.code === locationCode.value) {
        return uni.showToast({
          title: '请勿重复扫描',
          icon: 'none'
        })
      }
      locationCode.value = codeObj.code
    } else {
      if (!locationCode.value) {
        uni.showToast({
          title: '请先扫描库位码',
          icon: 'none'
        })
        return
      } else {
        sampleCode.value = val
        // 执行归库
        handleReturnToStock()
      }
    }
  } catch (error) {
    uni.showToast({ title: '扫码内容解析失败', icon: 'none' })
  }
}, 300)
onShow(() => {
  scanQRInfo.value = ''
})
let needPrint = ref(false)

let locationCode = ref('')
let sampleCode = ref('')

function handleReturnToStock() {
  nx.$api.sampleWarehouse
    .execReturnToStock({
      warehouseLocationCode: locationCode.value,
      sampleReturnCode: sampleCode.value
    })
    .then(res => {
      successCount.value++
      if (res.isPrint) {
        uni.showToast({
          title: `归库成功，归库码为【${res.code}】`,
          duration: 3000,
          icon: 'none'
        })
        // 执行打印
      }
    })
}

const successCount = ref(0)
function handleReset() {
  locationCode.value = ''
  sampleCode.value = ''
  successCount.value = 0
}
</script>

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