<template>
	<view>
		<u-popup v-model="show" @change="change" :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>
		<comMessage ref="comMessage" @afterClose="getfocus"></comMessage>
	</view>
</template>

<script setup>
	import winComScan from '@/mycomponents/scan/winComScan.vue'
	import {
		getBalanceByFilter
	} from '@/api/request2.js';

import { ref, onMounted } from 'vue';

const props = defineProps({
  title: {
    type: String,
    default: '箱标签'
  },
  isShowHistory: {
    type: Boolean,
    default: true
  },
  headerType: {
    type: String,
    default: 'HPQ,HMQ'
  }
});

const show = ref(false);
const businessType = ref(null);

const comscansimulate = ref(null);
const comscan = ref(null);
const comMessage = ref(null);

const simulateScan = (item) => {
  comscansimulate.value.setItemCodeSimulate(item.copyContent);
  comscansimulate.value.clickScanMsg();
};

const openScanPopup = () => {
  show.value = true
  setTimeout(() => {
    getfocus();
  }, 500);
};

const openScanPopupByBusinessType = (businessType) => {
  show.value = true
  setTimeout(() => {
    getfocus();
    businessType.value = businessType;
  }, 500);
};

const closeScanPopup = () => {
  losefocus();
  show.value = false
  emit("close", '');
};

const scanClick = () => {
  if (comscan.value) {
    comscan.value.clickScanMsg();
  }
};

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

const getScanResult = (result) => {
  if (result.success) {
    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) {
    filters.push({ column: "inventoryStatus", action: "in", value: businessType.value.outInventoryStatuses });
  }

  if (businessType.value?.outAreaTypes) {
    filters.push({ column: "areaType", action: "in", value: businessType.value.outAreaTypes });
  }

  if (businessType.value?.outAreaCodes) {
    filters.push({ column: "areaCode", action: "in", value: businessType.value.outAreaCodes });
  }

  return filters;
};

const getBalance = (result, callback) => {
  let filters = [];
  let packageInfo = result.package;
  let comfilters = getParams(packageInfo);
  let balance = { parentBalance: {}, childBalance: [] };

  let parentPackingNumber = packageInfo.parentNumber;
  let childPackingNumber = packageInfo.number;

  if (parentPackingNumber) {
    let packingNumber = parentPackingNumber + "," + childPackingNumber;
    filters.push({ column: "packingNumber", action: "in", value: packingNumber });
  } else {
    filters.push({ column: "packingNumber", action: "==", value: childPackingNumber });
  }

  filters = filters.concat(comfilters);
  const params = { filters, pageNo: 1, pageSize: 100 };

  getBalanceByFilter(params).then((res) => {
    res.data.list.forEach((r) => {
      if (packageInfo.parentNumber) {
        r.parentPackingNumber = parentPackingNumber;
      } else {
        r.parentPackingNumber = childPackingNumber;
      }
    });

    if (packageInfo.subList.length > 0) {
      let packparams = packageInfo.subList.map((pack) => pack.number).join(',');
      filters = [{ column: "packingNumber", action: "in", value: packparams }];
      filters = filters.concat(comfilters);
      params.filters = filters;

      getBalanceByFilter(params).then((res1) => {
        if (res1.data.list.length === 0) {
          showErrorMessage('未查找到该包装的库存余额', () => packGetFocus());
        } else {
          res1.data.list.forEach((r) => r.parentPackingNumber = childPackingNumber);
          balance.parentBalance = res.data.list.filter((r) => r.packingNumber === childPackingNumber);
          balance.childBalance = res1.data.list;
          callback(balance);
        }
      }).catch((err) => {
        showErrorMessage(err.message);
      });
    } else {
      balance.childBalance = res.data.list.filter((r) => r.packingNumber === childPackingNumber);
      balance.parentBalance = res.data.list.filter((r) => r.packingNumber === parentPackingNumber);
      callback(balance);
    }
  }).catch((err) => {
    showErrorMessage(err.message);
  });
};

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

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

const showMessage = (message) => {
  comMessage.value.showMessage(message);
};

const change = (e) => {
  show.value = e.show;
};

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

const emit = defineEmits(['close', 'getResult']);
</script>

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