<!--扫描组件-->
<template>
  <!-- <page-meta root-font-size="18px"></page-meta> -->
  <view>
    <view class="pop_tab">
      <view class="tab_info">
        <view class="conbox">
          <textarea inputmode="none" v-model="scanMsg" trim="all" maxlength="1000" style="margin-left: 5px; width: 90%" :focus="boxfocus" :placeholder="placeholderValue" @focus="getfocus" @blur="losefocus" @input="handelScanMsg" :cursor="cursorIndex"></textarea>
        </view>
        <view class="uni-flex uni-row space-between u-col-center">
          <view class="uni-flex">
            <button class="clean_scan_btn" @click="clearScanValue()">清空</button>
            <button class="scan_btn" @click="clickScanMsg()">扫描</button>
          </view>
        </view>
      </view>

      <view style="width: 100%">
        <view style="width: 100%" v-if="scanList.length > 0 && isShowHistory">
          <view class="uni-flex uni-row space-between u-col-center">
            <view class="" style="padding: 10rpx"> 历史记录 </view>
            <view class="" style="padding-right: 10rpx">
              <u-icon :name="expendIcon" size="35rpx" @click="expands()"></u-icon>
            </view>
          </view>
          <u-line class="line_color" style="padding-top: 10rpx; padding-bottom: 20rpx"></u-line>
          <scroll-view scroll-y="true" class="scroll-view" v-if="expand && scanList.length > 0" style="height: 70px">
            <view class="uni-flex u-col" v-for="(item, index) in scanList" :key="index">
              <view style="width: 100%; max-height: 100px">
                <view class="uni-flex u-row space-between u-col-center" @click="showItem(item)">
                  <view class="text_ellipsis" style="padding: 15rpx">
                    {{ item }}
                  </view>
                  <view class="">
                    <u-icon name="arrow-right"></u-icon>
                  </view>
                </view>
                <u-line class="line_color"></u-line>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
    <com-message ref="comMessageRef" />
  </view>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue'
import { Exception } from 'sass'
import { getLabelInfo } from '../../common/label.js'

import { getMesPackInfo } from '@/api/request2.js'

const { proxy } = getCurrentInstance()

const props = defineProps({
  placeholder: {
    type: String,
    default: '请扫描标签'
  },
  clearResult: {
    type: Boolean,
    default: true
  },
  boxFocus: {
    type: Boolean,
    default: true
  },
  isShowHistory: {
    type: Boolean,
    default: true
  },
  headerType: {
    type: String,
    default: 'HPQ' // HLB   HMQ   HCQ HPQ
  }
})
const scanMsg = ref('')
const boxfocus = ref(false)
const placeholderValue = ref('')
const scanResult = ref({})
const scanList = ref([])
const expand = ref(true)
const expendIcon = ref('arrow-down')
const cursorIndex = ref(0)
const itemCode = ref('')
const comMessageRef = ref()
onMounted(() => {
  boxfocus.value = true
  // uni.hideKeyboard()

  // #ifdef H5
  if (document.querySelector('textarea') != null) {
    document.querySelector('textarea').setAttribute('inputmode', 'none')
  }
  // #endif
  // hide()
  placeholderValue.value = `请扫描${props.placeholder}`
})
watch(
  () => props.placeholder,
  () => {
    placeholderValue.value = `请扫描${placeholder.value}`
  }
)

const hide = () => {
  // #ifdef APP-PLUS
  // 只是解决软键盘的闪现
  const interval = setInterval(function () {
    uni.hideKeyboard() // 隐藏软键盘
    console.log('刷新')
  }, 5)
  setTimeout(() => {
    clearInterval(interval)
    console.log('停止刷新')
  }, 1000)
  // #endif
}

const setItemCodeSimulate = (itemCode, scanMsg) => {
  itemCode.value = itemCode
  scanMsg.value = scanMsg
}

const setItemCode = (itemCodeParams) => {
  itemCode.value = itemCodeParams
}

const getValue = () => {
  return scanMsg.value
}
const setValue = (val) => {
  scanMsg.value = val
}
const clearScanValue = () => {
  scanMsg.value = ''
  getfocus()
}
const clickScanMsg = () => {
  scanMsg.value += '\n'
  handelScanMsg()
}
const handelScanMsg = () => {
  const index = scanMsg.value.indexOf('\n')
  if (index >= 0) {
    setTimeout(() => {
      losefocus()
      // let content = uni.$u.trim(that.scanMsg)
      const content = scanMsg.value.trim()
      // let content = that.scanMsg;
      if (content == '') {
        getfocus()
        comMessageRef.value.showErrorMessage('扫描内容为空,请重新扫描', (res) => {
          if (res) {
            scanMsg.value = ''
            getfocus()
          }
        })
        return
      }

      if (proxy.isShowHistory) {
        scanList.value.unshift(content)
      }
      console.log('扫描长度', content.length)
      getMesPackInfo(itemCode.value)
        .then((res) => {
          try {
            if (res.data.list.length == 0) {
              throw new Error(`没有查找到物料号【${itemCode.value}】对应的mes物料号`)
            }
            const result = res.data.list[0]
            const { partNumber } = result
            const { lengthMat } = result
            const { lengthBc } = result

            let itemCode = content.substr(0, lengthMat)
            const productDate = content.substr(lengthMat, 8)
            const batch = content.substr(lengthMat + 8, 3)
            const order = content.substr(-8)
            if (itemCode != partNumber) {
              clear()
              throw new Error(`解析错误:扫描物料号【${itemCode}】与查询物料号【${partNumber}】不一致`)
            }

            const scanResult = {
              itemCode,
              productDate,
              batch,
              order,
              qty: 1,
              content,
              success: true
            }
            clear()
            emit('getResult', scanResult)
          } catch (error) {
            comMessageRef.value.showErrorMessage(error.message, (res) => {
              if (res) {
                getfocus()
              }
            })
          }
        })
        .catch((error) => {
          comMessageRef.value.showErrorMessage(error, (res) => {
            if (res) {
              scanMsg.value = ''
              getfocus()
            }
          })
        })
    }, 500)
  }
}
const getfocus = () => {
  nextTick((r) => {
    boxfocus.value = true
  })
  hide()
}
const losefocus = () => {
  nextTick((r) => {
    boxfocus.value = false
  })
}
const clear = () => {
  cursorIndex.value = 0
  scanMsg.value = ''
}
const iconClick = (type) => {
  emit('clearResult', scanMsg.value)
}
const expands = () => {
  expand.value = !expand.value
  expendIcon.value = expand.value == true ? 'arrow-down' : 'arrow-up'
}
const scanClick = () => {
  handelScanMsg()
}
const cancelClick = () => {
  clear()
  getfocus()
}
const showItem = (item) => {
  comMessageRef.value.showMessage(item, (res) => {
    if (res) {
    }
  })
}

const scanQRCode = () => {
  uni.scanCode({
    onlyFromCamera: true,
    success: (res) => {
      scanMsg.value = res.result
      emit('getResult', res.result)
      console.log(`扫描二维码成功,结果:${res.result}`)
    },
    fail: (res) => {
      showItem(`扫描出现错误:${res.result}`)
    }
  })
}
// 传递给父类
const emit = defineEmits(['getResult', 'clearResult'])
defineExpose({
  getfocus,
  handelScanMsg,
  clearScanValue,
  clear,
  clickScanMsg,
  losefocus,
  setItemCode
})
</script>

<script module="textarea" lang="renderjs">
export default {
	mounted() {
		document.querySelector('textarea').setAttribute('inputmode', 'none')
	},
}
</script>

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