<template>
  <view>
    <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 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"
                          :isShowHistory="isShowHistory" :clearResult="true" :headerType="headerType"></win-com-scan>
          </view>
        </view>
      </view>
    </u-popup>
    <balance-select ref="balanceSelectRef" @onSelectItem='selectBalanceItem'></balance-select>
  </view>
  <comMessage ref="comMessageRef"></comMessage>
</template>

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

import {
  getBalanceByParams,
  getBasicItemByCode,
  getBalanceByFilter
} from '@/api/request2.js';

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

import { ref, onMounted, watch } from 'vue'

const props = defineProps({
  title: {
    type: String,
    default: '箱标签'
  },
  isShowHistory: {
    type: Boolean,
    default: false
  },
  headerType: {
    type: String,
    default: "HPQ,HMQ"
  },
  balanceFromInventoryStatuses: { // 是否传 fromInventoryStatuses
    type: Boolean,
    default: true
  },
  bussinessCode: {
    type: String,
    default: ''
  },
  verifyCategory: {
    type: Boolean,
    default: false
  },
  isCheckLocationBalance: {
    type: Boolean,
    default: true
  }
})

const scanResult = ref({})
const show = ref(false)
const scanList = ref([])
const expand = ref(false)
const expendIcon = ref('arrow-down')
const fromLocationCode = ref('')
const fromLocation = ref('')
const fromLocationList = ref([])
const fromLocationAreaTypeList = ref([])
const toLocationAreaTypeList = ref([])
const businessType = ref({})
const inventoryStatus = ref([])
const fromInventoryStatuses = ref([])
const itemTypesList = ref([])
const resultData = ref({})

const popup = ref(null)
const comMessageRef = ref(null)
const comscan = ref(null)
const balanceSelectRef = ref(null)

// 方法
const openScanPopup = (businessTypeValue) => {
  businessType.value = businessTypeValue
  fromInventoryStatuses.value = getDirectoryItemArray(businessTypeValue.outInventoryStatuses)
  fromLocationAreaTypeList.value = getDirectoryItemArray(businessTypeValue.outAreaTypes)
  toLocationAreaTypeList.value = getDirectoryItemArray(businessTypeValue.inAreaTypes)
  itemTypesList.value = getDirectoryItemArray(businessTypeValue.itemTypes)
  show.value = true
  setTimeout(() => {
    getfocus()
  }, 500)
}

const getScanResult = (result) => {
  resultData.value = result
  if (!result.package) {
    showErrorMessage(result.label.code + "包装信息为空")
    return
  }
  getItemCodeType(result.package.itemCode, () => {
    if (props.isCheckLocationBalance) {
      queryBalance(resultData.value)
    } else {
      queryBalance(resultData.value)
    }
  })
}

const getToLocationBalance = (result) => {
  uni.showLoading({
    title: '查询中',
    mask: true
  })
  const filters = []
  if (result.package.parentNumber) {
    const packingNumber = result.package.parentNumber + "," + result.package.number
    filters.push({
      column: "packingNumber",
      action: "in",
      value: packingNumber
    })
  } else {
    filters.push({
      column: "packingNumber",
      action: "==",
      value: result.package.number
    })
  }

  filters.push({
    column: "itemCode",
    action: "==",
    value: result.package.itemCode
  })
  filters.push({
    column: "batch",
    action: "==",
    value: result.package.batch
  })
  filters.push({
    column: "areaType",
    action: "in",
    value: toLocationAreaTypeList.value.join(',')
  })

  const params = {
    filters: filters,
    pageNo: 1,
    pageSize: 100,
  }
  getBalanceByFilter(params).then(res => {
    uni.hideLoading()
    if (res.data.list.length > 0) {
      showErrorMessage("包装在库位【" + res.data.list[0].locationCode + "】已有库存余额")
    } else {
      queryBalance(resultData.value)
    }
  }).catch(err => {
    showErrorMessage(err.message)
  })
}

const queryBalance = (result) => {
  const params = {
    itemCode: result.package.itemCode,
    batch: result.label.batch,
    packingNumber: result.label.packingNumber,
    parentPackingNumber: result.package.parentNumber,
    inventoryStatus: fromInventoryStatuses.value,
    areaType: fromLocationAreaTypeList.value,
    bussinessCode: props.bussinessCode
  }
  uni.showLoading({
    title: '查询中',
    mask: true
  })
  getBalanceByParams(params).then(res => {
    uni.hideLoading()
    if (res.data.length === 0) {
      const status = getInventoryStatusDesc(params.inventoryStatus)
      const areaType = getListLocationAreaTypeDesc(params.areaType)
      const hint =
        "按物料号 [" + params.itemCode + "] \n" +
        "包装号 [" + params.packingNumber + "] \n" +
        "批次 [" + params.batch + "] \n" +
        "状态 [" + status + "] \n" +
        "库区 [" + areaType + "] \n" +
        "未查找到库存余额"
      showErrorMessage(hint)
    } else if (res.data.length === 1) {
      result.balance = res.data[0]
      if (result.label.packingNumber !== result.balance.packingNumber) {
        result.balance.lableQty = result.label.qty
      }
      emit('getBalance', result)
    } else {
      balanceSelectRef.value.openPopup(res.data)
    }
  }).catch(error => {
    uni.hideLoading()
    showErrorMessage(error)
  })
}

const getItemCodeType = (itemCode, callBack) => {
  uni.showLoading({
    title: "加载中",
    mask: true
  })
  getBasicItemByCode(itemCode).then(res => {
    if (res.data && res.data.list.length > 0) {
      const result = res.data.list[0]
      const status = result.available
      const type = result.type
      if (status === "TRUE") {
        if (checkDirectoryItemExist(itemTypesList.value, type)) {
          if (props.verifyCategory) {
            if (result.category === 'LCJ' || result.category === 'BJ') {
              callBack()
            } else {
              showErrorMessage("扫描物料的种类不是【量产件】或者【备件】")
            }
          } else {
            callBack()
          }
        } else {
          const hint = getListItemTypeDesc(itemTypesList.value)
          uni.hideLoading()
          showErrorMessage("扫描物料[" + itemCode + "]是[" +
            getItemTypeInfo(type).label + "],需要的物料类型是[" + hint + "]")
        }
      } else {
        uni.hideLoading()
        showErrorMessage('物料【' + itemCode + '】不可用')
      }
    } else {
      uni.hideLoading()
      showErrorMessage('未查找到物料【' + itemCode + '】')
    }
  }).catch(error => {
    uni.hideLoading()
    showErrorMessage(error)
  })
}

const showErrorMessage = (message) => {
  losefocus()
  comMessageRef.value.showErrorMessage(message, res => {
    if (res) {
      if (comscan.value) {
        comscan.value.getfocus()
      }
    }
  })
}

const selectBalanceItem = (item) => {
  resultData.value.balance = item
  emit('getBalance', resultData.value)
}

const closeScanPopup = () => {
  losefocus()
  show.value = false
}

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

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

const emit = defineEmits(['getBalance'])
</script>

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