<template>
  <view>
    <u-popup v-model="show" mode="bottom" :mask-close-able="false">
      <view class="popup_box">
        <view class="pop_title uni-flex space-between">
          <view class="" style="font-size: 35rpx"> 扫描{{ title }} </view>

          <view class="">
            <image class="fr icons_scan_close" src="/static/icons/icons_scan_close.svg" @click="closeScanPopup()"></image>
          </view>
        </view>
        <view class="">
          <view class="">
            <win-com-scan ref="comscan" :placeholder="title" @getResult="getScanResult" :headerType="headerType" :isShowHistory="isShowHistory" :clearResult="true"></win-com-scan>
          </view>
        </view>
      </view>
    </u-popup>
    <!-- 模拟扫描功能 -->
    <win-com-scan v-show="false" ref="comscansimulate" @getResult="getScanResult" :headerType="headerType" :isShowHistory="false" :clearResult="true"></win-com-scan>
    <com-message ref="comMessageRef" />
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue'
import winComScan from '@/mycomponents/scan/winComScan.vue'
import { getBalanceByFilter } from '@/api/request2.js'
import {
  getInventoryStatusDesc,
  getDirectoryItemArray,
  getLocationAreaTypeName
} from '@/common/directory.js';
const props = defineProps({
  title: {
    type: String,
    default: '箱标签'
  },
  isShowHistory: {
    type: Boolean,
    default: true
  },
  headerType: {
    type: String,
    default: 'HPQ,HMQ'
  }
})
const show = ref(false)
const comscansimulate = ref()
const comscan = ref()
const comMessageRef = ref()
const businessType = ref(null)
const scanResult = ref({})
const simulateScan = (item) => {
  comscansimulate.value.setItemCodeSimulate(item.copyContent)
  comscansimulate.value.clickScanMsg()
}
const openScanPopup = () => {
  show.value = true
  setTimeout((res) => {
    getfocus()
  }, 200)
}

const closeScanPopup = () => {
  losefocus()
  show.value = false
  emit('close', '')
}
const openScanPopupByBusinessType = (businessTypeParams) => {
  show.value = false
  setTimeout((res) => {
    getfocus()
    businessType.value = businessTypeParams
  }, 500)
}
const scanClick = () => {
  if (comscan.value) {
    comscan.value.clickScanMsg()
  }
}

const cancelClick = () => {
  if (comscan.value) {
    comscan.value.clearScanValue()
  }
}

const getScanResult = (result) => {
  if (result.success) {
    scanResult.value = result
    getBalance(result, (res) => {
      result.balance = res
      emit('getResult', result)
    })
  } else {
    showMessage(result.message)
  }
}
const getParams = (label)=> {
  let filters = [{
    column: "itemCode",
    action: "==",
    value: label.itemCode
  }, {
    column: "batch",
    action: "==",
    value: label.batch
  }];
  if (businessType.value.outInventoryStatuses != null) {
    filters.push({
      column: "inventoryStatus",
      action: "in",
      value: businessType.value.outInventoryStatuses
    })
  }
  if (businessType.value.outAreaTypes != null){
    filters.push({
      column: "areaType",
      action: "in",
      value: businessType.value.outAreaTypes
    })
  }
  if (businessType.value.outAreaCodes != null){
    filters.push({
      column: "areaCode",
      action: "in",
      value: businessType.value.outAreaCodes
    })
  }
  return filters;
}
const getQueryCondition = ()=> {
  let condition = '按照以下条件:\n';
  let label = scanResult.value.label;
  let status = getInventoryStatusDesc(getDirectoryItemArray(businessType.value.outInventoryStatuses));
  let areaType = getLocationAreaTypeName(businessType.value.outAreaTypes)
  condition = condition + '物料号=[' + label.itemCode
      + ']\n箱码=[' + label.packingNumber +
      ']\n批次=[' +
      label.batch +
      ']'

  if (status) {
    condition = condition + '\n库存状态=[' + status + ']'
  }

  if (areaType) {
    condition = condition + '\n库区类型=[' + areaType + ']'
  }
  if (businessType.value.outAreaCodes) {
    condition = condition + '\n库区代码=[' + businessType.value.outAreaCodes + ']'
  }
  return condition;
}
const getBalance = (result, callback) => {
  let filters = []
  const { label } = result
  const packageInfo = result.package
  let comfilters = getParams(label);
  if (packageInfo.parentNumber) {
    const packingNumber = `${packageInfo.parentNumber},${label.packingNumber}`
    filters.push({
      column: 'packingNumber',
      action: 'in',
      value: packingNumber
    })
  } else {
    filters.push({
      column: 'packingNumber',
      action: '==',
      value: label.packingNumber
    })
  }
  filters = filters.concat(comfilters);
  filters.push({
    column: 'itemCode',
    action: '==',
    value: label.itemCode
  })
  const params = {
    filters,
    pageNo: 1,
    pageSize: 100
  }
  getBalanceByFilter(params)
    .then((res) => {
      if (res.data.list.length > 0) {
        res.data.list.forEach(r => {
          if (packageInfo.parentNumber) {
            r.parentPackingNumber = packageInfo.parentNumber
          } else {
            r.parentPackingNumber = packageInfo.number
          }
        })
        callback(res.data.list)
      } else {
        //如果扫描的是托标签，按托标签没查找到库存再按托标签下的子标签查询库存
        if (packageInfo.subList.length > 0) {
          let packparams = '';
          packageInfo.subList.forEach(pack => {
            packparams = packparams + pack.number + ','
          })
          packparams = packparams.trimEnd(',');
          filters = [];
          filters.push({
            column: "packingNumber",
            action: "in",
            value: packparams
          })
          filters = filters.concat(comfilters);
          params.filters = filters;
          getBalanceByFilter(params).then(res1 => {
            if (res1.data.list.length == 0) {
              showErrorMessage(getQueryCondition()+'\n未查找到该包装的库存余额')
            } else {
              res1.data.list.forEach(r => r.parentPackingNumber = packageInfo.number)
              callback(res1.data.list)
            }
          }).catch(err => {
            this.showErrorMessage(err.message);
          })
        } else {
          showErrorMessage(getQueryCondition()+'\n未查找到该包装的库存余额')
        }
      }
    })
    .catch((err) => {
      showErrorMessage(err.message)
    })
}
const getfocus = () => {
  if (comscan.value) {
    comscan.value.getfocus()
  }
}

const losefocus = () => {
  if (comscan.value) {
    comscan.value.losefocus()
  }
}

const showMessage = (message) => {
  comMessageRef.value.showMessage(message)
}
const showErrorMessage = (message) => {
  losefocus()
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
      getfocus()
    }
  })
}
// 传递给父类
const emit = defineEmits(['getResult'])
</script>

<style lang="scss">
.scroll-view {
  overflow-y: scroll;
  height: auto;
  max-height: 300rpx;
}
</style>
