<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="uni-flex uni-row" style="align-items: center; background-color: #fff; margin-left: 20rpx; margin-right: 20rpx; border-radius: 8rpx; height: 30px">
          <view class="uni-center" style="width: 25%"> 来源库位 </view>
          <!-- style="width: 75%;padding: 8rpx" -->
          <view class="">
            <!-- <input v-model="fromLocationCode" placeholder="请扫描来源库位" :focus="locationOnFocus"
							placeholder-style="font-size:12px" style="padding: 5px;" @confirm="scanLocation" /> -->

            <view v-if="allowModifyLocation">
              <uni-combox :candidates="fromLocationList" v-model="fromLocationCode" placeholder="请扫描来源库位" @confirm="handleConfirm" style="height: 30rpx; border: 1px solid #fff"></uni-combox>
            </view>
            <view v-else>
              <text style="padding: 5px">
                {{ fromLocationCode }}
              </text>
            </view>
          </view>
        </view>
        <view class="">
          <view class="">
            <win-com-scan ref="comscan" :placeholder="title" @getResult="getScanResult" :isShowHistory="isShowHistory" :clearResult="true" :headerType="headerType"></win-com-scan>
          </view>
        </view>
      </view>
    </u-popup>
    <balance-select ref="balanceSelectRef" @onSelectItem="selectBalanceItem"></balance-select>
    <!-- 模拟扫描功能 -->
    <win-com-scan v-show="false" ref="comscansimulate" @getResult="getScanResult" :headerType="headerType" :isShowHistory="false" :clearResult="true"></win-com-scan>
  </view>
  <com-message ref="comMessageRef" />
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue'
import winComScan from '@/mycomponents/scan/winComScan.vue'
import balanceSelect from '@/mycomponents/balance/balanceSelect.vue'
import { getBalanceByManagementPrecisionByPacking } from '@/common/balance.js'

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

import { getListLocationAreaTypeDesc, checkDirectoryItemExist, getDirectoryItemArray, getLocationAreaTypeName, getInventoryStatusDesc } from '@/common/directory.js'

const { proxy } = getCurrentInstance()
const props = defineProps({
  title: {
    type: String,
    default: '箱标签'
  },
  isShowHistory: {
    type: Boolean,
    default: true
  },
  allowNullBalance: {
    type: Boolean,
    default: false
  },
  // 不提示库存错误
  noShowBalanceMessage: {
    type: Boolean,
    default: false
  },
  //
  isCount: {
    type: Boolean,
    default: false
  },
  // 是否允许修改库位
  allowModifyLocation: {
    type: Boolean,
    default: true
  },
  headerType: {
    type: String,
    default: 'HPQ,HMQ'
  },
  queryBalance: {
    type: Boolean,
    default: true
  },
  balanceFromInventoryStatuses: {
    // 是否传fromInventoryStatuses
    type: Boolean,
    default: true
  }
})
const scanResult = ref({})
const show = ref(false)
const scanList = ref([])
const expand = ref(false)
const showScanResult = ref({})
const expendIcon = ref('arrow-down')
const fromLocationCode = ref('')
const fromLocation = ref('')
const fromLocationList = ref([])
const fromLocationAreaTypeList = ref([])
const locationOnFocus = ref(false)
const businessType = ref({})
const inventoryStatus = ref([])
const managementPrecision = ref('')
const fromInventoryStatuses = ref('')
const isCheck = ref(false)
const balanceSelectRef = ref()
const comscan = ref()
const comMessageRef = ref()
const location = ref()

const handleConfirm = () => {
  emit('confirm', fromLocationCode.value)
}
// 直接扫描
const openScanPopupForType = (fromLocationCodeParams, businessTypeParams) => {
  businessType.value = businessTypeParams
  fromLocationCode.value = fromLocationCodeParams
  if (fromLocationCodeParams != '') {
    packGetFocus()
  } else {
    locationGetFocus()
  }
  fromInventoryStatuses.value = getDirectoryItemArray(businessType.value.outInventoryStatuses)
  inventoryStatus.value = getDirectoryItemArray(businessType.value.outInventoryStatuses) // 出库库存状态
  fromLocationAreaTypeList.value = getDirectoryItemArray(businessType.value.outAreaTypes) // 出库库区
  if (!show.value) {
    setTimeout((res) => {
      show.value = true
    }, 500)
  }
}

// 在任务中扫描
const openScanPopupForJob = (fromLocationCodePrams, fromLocationListPrams, jobContent) => {
  fromLocationCode.value = fromLocationCodePrams
  fromLocationList.value = fromLocationListPrams
  if (fromLocationCodePrams != '') {
    packGetFocus()
  } else if (fromLocationList.value.length == 0) {
    locationGetFocus()
  } else {
    fromLocationCode.value = fromLocationList.value[0]
  }
  setTimeout((res) => {
    show.value = true
  }, 500)
  fromInventoryStatuses.value = getDirectoryItemArray(jobContent.outInventoryStatuses)
  inventoryStatus.value = getDirectoryItemArray(jobContent.outInventoryStatuses) // 出库库存状态; //出库库存状态
  fromLocationAreaTypeList.value = getDirectoryItemArray(jobContent.fromAreaTypes) // 出库库存状态
}
// 模拟扫描
const openScanPopupForJobSimulate = (fromLocationCodeParams, fromLocationListParams, jobContent, item) => {
  fromLocationCode.value = fromLocationCodeParams
  fromLocationList.value = fromLocationListParams
  if (fromLocationListParams != '') {
    // this.packGetFocus();
    if (comscansimulate.value != undefined) {
      comscansimulate.value.getfocus()
    }
  } else if (fromLocationList.value.length == 0) {
    // this.locationGetFocus();
    alert('没有来源库位：List')
  } else {
    fromLocationCode.value = fromLocationList.value[0]
  }
  fromInventoryStatuses.value = getDirectoryItemArray(jobContent.outInventoryStatuses)
  inventoryStatus.value = getDirectoryItemArray(jobContent.outInventoryStatuses) // 出库库存状态; 		//出库库存状态
  fromLocationAreaTypeList.value = getDirectoryItemArray(jobContent.fromAreaTypes) // 出库库存状态
  const timer = setTimeout((res) => {
    if (timer) {
      clearTimeout(timer)
    }
    comscansimulate.value.setItemCodeSimulate(item.copyContent)
    comscansimulate.value.clickScanMsg()
  }, 500)
}
const closeScanPopup = (content) => {
  show.value = false
  emit('close', '')
}
const scanLocation = (scanResult) => {
  const isCheck = false
  if (fromLocationCode.value == '') {
    showErrorMessage('来源库位不能为空', (callback) => {
      locationGetFocus()
    })
    return
  }

  if (fromLocationList.value.length > 0) {
    if (!isInLocationList(fromLocationCode.value)) {
      showErrorMessage(`扫描库位【${fromLocationCode.value}】不在任务来源库位中`, (callback) => {
        locationGetFocus()
      })
      return
    }
  }
  proxy.$modal.loading('扫描中...')
  getBasicLocationByCode(fromLocationCode.value)
    .then((res) => {
      uni.hideLoading()
      if (res.data.total > 0) {
        const result = res.data.list[0]
        if (result.code != fromLocationCode.value) {
          showErrorMessage(`未查询到库位[${fromLocationCode.value}]`)
          return
        }
        const type = result.areaType
        const { available } = result
        if (available == 'TRUE') {
          if (checkDirectoryItemExist(fromLocationAreaTypeList.value, type)) {
            location.value = result
            // this.packGetFocus();
            checkPackage(scanResult)
          } else {
            uni.hideLoading()
            const hint = getListLocationAreaTypeDesc(fromLocationAreaTypeList.value)
            showErrorMessage(`扫描库位[${fromLocationCode.value}]是[${getLocationAreaTypeName(result.areaType)}],需要的库区是[${hint}]`)
          }
        } else {
          uni.hideLoading()
          showErrorMessage(`扫描库位[${fromLocationCode.value}]不可用`, (res) => {
            locationGetFocus()
          })
        }
      } else {
        uni.hideLoading()
        showErrorMessage(`未查询到库位[${fromLocationCode.value}]`, (res) => {
          locationGetFocus()
        })
      }
    })
    .catch((error) => {
      debugger
      uni.hideLoading()
      showErrorMessage(error.msg, (res) => {
        locationGetFocus()
      })
    })
}
const getScanResult = (result) => {
  // if (this.fromLocationCode == '' || this.fromLocationCode == null) {
  // 	this.showMessage('请先扫描来源库位', callback => {
  // 		this.locationGetFocus();
  // 	})
  // 	return;
  // } else
  scanLocation(result)
  // debugger
  // if(this.isCheck){
  // 	this.checkPackage(result);
  // }
}
const checkPackage = (result) => {
  if (result.label != null) {
    scanResult.value = result
    // uni.showLoading({
    // 	title: '查询中...',
    // 	mask: true
    // })
    if (props.queryBalance == true) {
      getBalanceByManagementPrecisionByPacking(result.label, fromLocationCode.value, props.balanceFromInventoryStatuses ? fromInventoryStatuses.value : undefined, (res) => {
        uni.hideLoading()
        if (res.success) {
          managementPrecision.value = res.managementPrecision
          afterQueryBalance(res.data.list)
        } else {
          showErrorMessage(res.message, (res) => {
            packGetFocus()
          })
        }
        // uni.hideLoading();
      })
    } else {
      uni.hideLoading()
      packCallBack(null)
    }
  }
}
const afterQueryBalance = (datas) => {
  if (props.allowNullBalance) {
    allowNoneBalance(datas)
  } else if (props.noShowBalanceMessage) {
    if (props.isCount) {
      countCallBack(datas)
    } else if (Array.isArray(datas)) {
      countCallBack(datas[0])
    } else {
      countCallBack(datas)
    }
  } else {
    mustHavaBalance(datas)
  }
  uni.hideLoading()
}
// 允许无库存
const allowNoneBalance = (datas) => {
  if (datas.length == 0) {
    packCallBack(null)
  } else {
    showErrorMessage(`在来源库位[${fromLocationCode.value}],已经查找到该包装的库存记录,请重新扫描`, (res) => {
      packGetFocus()
    })
  }
}
// 必须有库存

const mustHavaBalance = (datas) => {
  if (datas.length == 0) {
    showErrorMessage(`${getQueryCondition()}<br>未查找到库存记录`, (res) => {
      packGetFocus()
    })
  } else if (datas.length == 1) {
    const balance = datas[0]
    packCallBack(balance)

    // 因为盘点时有负库存，暂时去掉判断  2023年12月28日

    // if (balance.qty > 0) {
    // 	this.packCallBack(balance);
    // } else {
    // 	this.showErrorMessage(this.getQueryCondition() + '<br>查找到库存记录数量为[' + balance.qty + "],<br>不可以进行操作",
    // 		res => {
    // 			this.packGetFocus();
    // 		})
    // }
  } else {
    showBalanceSelect(datas)
  }
}
const showBalanceSelect = (items) => {
  balanceSelectRef.value.openPopup(items)
}
const selectBalanceItem = (balance) => {
  packCallBack(balance)
  // 因为盘点时有负库存，暂时去掉判断  2023年12月28日
  // if (balance.qty > 0) {
  // 	this.packCallBack(balance);
  // } else {
  // 	this.showErrorMessage(this.getQueryCondition() + '<br>查找到库存记录数量为[' + balance.qty + "],不可以进行操作",
  // 		res => {
  // 			this.packGetFocus();
  // 		})
  // }
}

// 盘点回调

const countCallBack = (datas) => {
  if (comscan.value) {
    comscan.value.clear()
  }
  // 返回标签信息、库存信息和管理模式
  const data = {
    label: scanResult.value.label,
    package: scanResult.value.package,
    balance: datas,
    fromLocationCode: fromLocationCode.value
  }
  packGetFocus()
  emit('getResult', data)
  emit('getCountScanResult', data)
}

const packCallBack = (item) => {
  if (comscan.value) {
    comscan.value.clear()
  }
  // 返回标签信息、库存信息和管理模式
  const data = {
    label: scanResult.value.label,
    package: scanResult.value.package,
    balance: item,
    fromLocationCode: fromLocationCode.value
  }
  packGetFocus()
  emit('getResult', data)
}
const packGetFocus = () => {
  if (comscan.value != undefined) {
    comscan.value.getfocus()
  }
}
const packLoseFocus = () => {
  if (comscan.value != undefined) {
    comscan.value.losefocus()
  }
}
const locationGetFocus = () => {
  fromLocationCode.value = ''
  locationOnFocus.value = true
}
const getQueryCondition = () => {
  let condition = '按照以下条件:<br>'
  const { label } = scanResult.value
  const status = getInventoryStatusDesc(inventoryStatus.value)
  switch (managementPrecision.value) {
    case 'BY_PACKAGING':
      condition = `${condition}物料号=[${label.itemCode}]<br>箱码=[${label.packingNumber}]<br>批次=[${label.batch}]<br>库位=[${fromLocationCode.value}]`

      break
    case 'BY_BATCH':
      condition = `${condition}物料号=[${label.itemCode}]<br>批次=[${label.batch}]<br>库位=[${fromLocationCode.value}]`
      break
    case 'BY_QUANTITY':
      condition = `${condition}物料号=[${label.itemCode}]<br>库位=[${fromLocationCode.value}]`
      break
    case 'BY_UNIQUEID':
      condition = `${condition}物料号=[${label.itemCode}]`
      break
  }
  if (inventoryStatus.value.length > 0) {
    condition = `${condition}<br>库存状态=[${status}]`
  }
  return condition
}
const showMessage = (message, callback) => {
  setTimeout((r) => {
    packLoseFocus()
    comMessageRef.value.showMessage(`${message}，请重新扫描`, callback)
  })
}
const showErrorMessage = (message, callback) => {
  setTimeout((r) => {
    packLoseFocus()
    comMessageRef.value.showErrorMessage(`${message}，请重新扫描`, callback)
  })
}
const isInLocationList = (location) => {
  let item = fromLocationList.value.find((res) => res == location)

  if ((item = undefined)) {
    return false
  }
  return true
}
const addLocationCode = (code) => {
  if (!isInLocationList(code)) {
    fromLocationList.value.push(code)
  }
}
// 传递给父类
const emit = defineEmits(['close', 'getCountScanResult', 'getResult', 'confirm'])
defineExpose({ openScanPopupForType, openScanPopupForJob, packGetFocus, packLoseFocus, closeScanPopup })
</script>

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