<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="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%; font-size: 35rpx"> 来源库位 </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; font-size: 40rpx">
                {{ fromLocationCode }}
              </text>
            </view>
          </view>
        </view>
        <view class="">
          <view class="">
            <win-com-scan ref="comscanRef" :placeholder="title" @getResult="getScanResult" :isShowHistory="isShowHistory" :clearResult="true" :headerType="headerType"></win-com-scan>
          </view>
        </view>
      </view>
    </u-popup>
    <balance-select ref="balanceSelect" @onSelectItem="selectBalanceItem"></balance-select>
    <!-- 模拟扫描功能 -->
  </view>
  <comMessage ref="comMessageRef"></comMessage>
</template>

<script setup>
import winComScan from '@/mycomponents/scan/winComScan.vue'
import balanceSelect from '@/mycomponents/balance/balanceSelect.vue'
import { getBalanceByManagementPrecisionByPacking } from '@/common/balance.js'

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

import { getListLocationAreaTypeDesc, checkDirectoryItemExist, getDirectoryItemArray, getLocationAreaTypeName, getInventoryStatusDesc, getListItemTypeDesc, getItemTypeInfo } from '@/common/directory.js'
import {getLabelInfo} from '@/common/label.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: {
    type: Boolean,
    default: true
  },
  bussinessCode: {
    type: String,
    default: ''
  },
  allowModifyLocation: {
    type: Boolean,
    default: true
  }
});

const businessType = ref({});
const fromInventoryStatuses = ref([]);
const fromLocationAreaTypeList = ref([]);
const itemTypesList = ref([]);
const fromLocationCode = ref('');
const fromLocationList = ref([]);
const inventoryStatus = ref([]);
const resultData = ref({});
const show = ref(false)

const comMessageRef = ref(null);
const comscanRef = ref(null);

const openScanPopup = (businessTypeValue) => {
  businessType.value = businessTypeValue;
  fromInventoryStatuses.value = getDirectoryItemArray(businessTypeValue.outInventoryStatuses);
  fromLocationAreaTypeList.value = getDirectoryItemArray(businessTypeValue.outAreaTypes);
  itemTypesList.value = getDirectoryItemArray(businessTypeValue.itemTypes);
  show.value = true
  setTimeout(() => {
    packGetFocus();
  }, 500);
};

const openScanPopupForJob = (fromLocationCodeValue, fromLocationListValue, jobContent) => {
  fromLocationCode.value = fromLocationCodeValue;
  fromLocationList.value = fromLocationListValue;
  fromInventoryStatuses.value = getDirectoryItemArray(jobContent.outInventoryStatuses);
  inventoryStatus.value = getDirectoryItemArray(jobContent.outInventoryStatuses);
  fromLocationAreaTypeList.value = getDirectoryItemArray(jobContent.fromAreaTypes);
  show.value = true
  setTimeout(() => {
    if (fromLocationCode.value !== '') {
      packGetFocus();
    } else {
      if (fromLocationList.value.length === 0) {
        // locationGetFocus();
      } else {
        fromLocationCode.value = fromLocationList.value[0];
        packGetFocus();
      }
    }
  }, 500);
};

const openScanPopupForJobSimulate = (fromLocationCodeValue, fromLocationListValue, jobContent, scanMessage) => {
  fromLocationCode.value = fromLocationCodeValue;
  fromLocationList.value = fromLocationListValue;
  if (!fromLocationCodeValue) {
    if (fromLocationList.value.length === 0) {
      alert('没有来源库位：List');
    } else {
      fromLocationCode.value = fromLocationList.value[0];
    }
  }
  fromInventoryStatuses.value = getDirectoryItemArray(jobContent.outInventoryStatuses);
  inventoryStatus.value = getDirectoryItemArray(jobContent.outInventoryStatuses);
  fromLocationAreaTypeList.value = getDirectoryItemArray(jobContent.fromAreaTypes);
  getLabelInfo(scanMessage, props.headerType, (callback) => {
    if (callback.success) {
      getScanResult(callback);
    } else {
      showErrorMessage(callback.message, () => {});
    }
  });
};

const handleConfirm = () => {
  emit('confirm', fromLocationCode.value);
};

const getScanResult = (result) => {
  if (fromLocationCode.value === '') {
    showErrorMessage('请选择来源库位', () => {});
    return;
  }
  resultData.value = result;
  if (!result.package) {
    showErrorMessage(`${result.label.code}包装信息为空`);
    return;
  }
  getItemCodeType(result.package.itemCode, () => {
    queryBalance(resultData.value);
  });
};

const queryBalance = (result) => {
  const params = {
    locationCode: fromLocationCode.value,
    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 {
        show.value = true
      }
    })
    .catch((error) => {
      uni.hideLoading();
      showErrorMessage(error);
    });
};

const getItemCodeType = (itemCode, callBack) => {
  uni.showLoading({
    title: '加载中',
    mask: true
  });
  getBasicItemByCode(itemCode)
    .then((res) => {
      if (res.data != null && res.data.list.length > 0) {
        const result = res.data.list[0];
        const status = result.available;
        const { type } = result;
        if (status === 'TRUE') {
          if (checkDirectoryItemExist(itemTypesList.value, type)) {
            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) => {
  packLoseFocus();
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
      if (comscanRef.value) {
        comscanRef.value.getfocus();
      }
    }
  });
};

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

const closeScanPopup = () => {
  packLoseFocus();
  show.value = false
  emit('onCloseScanPopup');
};

const getfocus = () => {
  if (comscanRef.value) {
    comscanRef.value.getfocus();
  }
};

const packGetFocus = () => {
  if (comscanRef.value) {
    comscanRef.value.getfocus();
  }
};

const packLoseFocus = () => {
  if (comscanRef.value) {
    comscanRef.value.losefocus();
  }
};

const emit = defineEmits(['confirm', 'getBalance', 'onCloseScanPopup']);
</script>

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