<template>
	<up-popup :show="state.show" @close="close" @open="open">
		<view class="input-box" v-if="screeningTypes('warehouseStr')">
			<view class="input-item">
				<up-input :placeholder="t('public.xzck')" border="none" clearable inputAlign="left"
					v-model="state.scanFrame.warehouseStr" confirmType="next" :disabled="true">
					<template #prefix>
						<view class="item-title" style="margin-right: 16rpx;">{{ t('public.ckmc') }}</view>
					</template>
					<template #suffix>
						<up-icon name="search" color="#6c6c6c" size="24" @click="warehouseShowFun"></up-icon>
					</template>
				</up-input>
			</view>
		</view>
		<view class="input-box" v-if="screeningTypes('locationStr')">
			<view class="input-item">
				<up-input :placeholder="state.NoLocationListText" border="none" clearable inputAlign="left"
					v-model="state.scanFrame.locationStr" confirmType="next" @change="locationChange">
					<template #prefix>
						<view class="item-title" style="margin-right: 16rpx;">{{ t('public.cwmc') }}</view>
					</template>
					<template #suffix>
						<up-icon name="search" color="#6c6c6c" size="24" @click="locationStrShowFun"></up-icon>
					</template>
				</up-input>
			</view>
		</view>
		<view class="input-box" v-if="screeningTypes('articlesStr')">
			<view class="input-item">
				<up-input :placeholder="t('public.qsrwlbmmessage')" border="none" clearable inputAlign="right"
					v-model="state.scanFrame.articlesStr" confirmType="next">
					<template #prefix>
						<view class="item-title">{{ t('public.wlbm') }}</view>
					</template>
				</up-input>
			</view>
		</view>
		<view class="input-box" v-if="screeningTypes('quantityStr')">
			<view class="input-item">
				<up-input :placeholder="t('public.qsrsl')" border="none" clearable inputAlign="right" :disabled="props.qtyState"
					v-model="state.scanFrame.quantityStr" @change="quantityStrChangeFun">
					<template #prefix>
						<view class="item-title">{{ t('public.qty') }}</view>
					</template>
				</up-input>
			</view>
		</view>
		<view class="input-box" v-if="screeningTypes('batchNumberStr')">
			<view class="input-item">
				<up-input :placeholder="state.batchNumberStrPdr" border="none" clearable inputAlign="right"
					v-model="state.scanFrame.batchNumberStr" confirmType="next" :disabled="state.batchNumberStrState">
					<template #prefix>
						<view class="item-title">{{ t('public.mmsph') }}</view>
					</template>
				</up-input>
			</view>
		</view>
		<view class="btnListSc">
			<up-button type="primary" :plain="true" :text="t('index.qx')" @click="() => {state.show = false}"></up-button>
			<up-button type="primary" :text="t('index.qd')" style="margin-left: 36rpx;" @click="confirmationFun"></up-button>
		</view>
		<warehouse :show="state.warehouse" @warehouseClose="warehouseClosefun" @warehouseData="warehouseDataFun" />
		<location :show="state.location"
			:warehouseId="Object.keys(state.warehouseData).length ? state.warehouseData.FNUMBER : null"
			@locationClose="locationClosefun" @locationData="locationDataFun" />
	</up-popup>
</template>

<script lang="ts" setup>
	import { reactive, nextTick, onMounted, ref, computed, defineEmits, watch, defineExpose, defineProps } from 'vue';
	import { onLoad, onShow, onReachBottom, } from '@dcloudio/uni-app'
	import warehouse from '../warehouse/warehouse.vue'
	import location from '../warehouse/location.vue'
	import i18n from '../../locale/index'
	import { useI18n } from 'vue-i18n'
	import { fStockFlexDetailList } from '../../common/request/api/api';
	const getI18n = useI18n()
	const { t, locale } = getI18n
	const eimts = defineEmits(['scanFrameDataFeedback', 'confirmation', 'fast', 'err', 'boxShow'])
	const props = defineProps({
		types: {
			type: Array,
			default: () => {
				return ['warehouseStr', 'locationStr', 'articlesStr', 'quantityStr', 'batchNumberStr']
			}
		},
		qtyState: {
			type: Boolean,
			default: () => {
				return false
			}
		}
	})
	const state = reactive({
		show: false,
		warehouse: false,
		location: false,
		NoLocationList: true,
		NoLocationListText: '',
		batchNumberStrPdr: t('index.qsrph'),
		warehouseData: {},
		locationData: {},
		quantityStrState: false,
		batchNumberStrState: false,
		scanFrame: {
			warehouseStr: '',
			locationStr: '',
			articlesStr: '',
			barCodeStr: '',
			quantityStr: '',
			batchNumberStr: '',
			sequenceStr: '',
		},
		componentsData: {},
		receiveBillScanData: {}
	})

	/**
	 * 数据逻辑
	 */
	const screeningTypes = (str : string) => {
		if (props.types.indexOf(str) !== -1) return true
		else return false
	}
	watch(() => state.scanFrame, () => {
		console.log('目标已出发');
		eimts('scanFrameDataFeedback', state.scanFrame)
	}, { deep: true })
	//来自默认值的数据
	const getComponentsData = (obj : any) => {
		state.componentsData = obj
		state.scanFrame.warehouseStr = obj.warehouseStr
		state.scanFrame.locationStr = obj.locationStr
		state.scanFrame.quantityStr = props.qtyState ? 1 : obj.quantityStr
		state.scanFrame.batchNumberStr = obj.batchNumberStr
		state.warehouseData = obj.warehouseData
		state.locationData = obj.locationData
		if (state.warehouseData.FIsOpenLocation) {
			state.NoLocationList = true
			state.NoLocationListText = t('index.ksmcw')
		} else {
			state.NoLocationList = false
			state.NoLocationListText = t('index.cwwqy')
		}
	}
	//来自接口的数据
	const getreceiveBillScanData = (row : any) => {
		state.receiveBillScanData = row
		dataValidation()
	}
	//数据擦除
	const dataErase = () => {
		if (state.componentsData.warehouseStr == '') state.scanFrame.warehouseStr = ''
		if (state.componentsData.locationStr == '') state.scanFrame.locationStr = ''
		if (state.componentsData.quantityStr == '') state.scanFrame.quantityStr = ''
		if (state.componentsData.batchNumberStr == '') state.scanFrame.batchNumberStr = ''
		if (Object.keys(state.componentsData.warehouseData).length === 0) {
			state.scanFrame.warehouseStr = ''
			state.scanFrame.locationStr = ''
			state.NoLocationList = true
			state.NoLocationListText = t('index.ksmcw')
			state.warehouseData = {}
			state.locationData = {}
		}
	}
	//首次数据校验&修正
	const dataValidation = () => {
		//批号校验
		if (state.receiveBillScanData.FIsBatchManage === 'True') {
			if (state.scanFrame.batchNumberStr !== '' && state.scanFrame.batchNumberStr !== state.receiveBillScanData.FLot_Text) {
				state.show = true
				uni.showModal({
					title: t('index.ts'), content: '与默认批号不同，是否替换新的批号', cancelText: '取消', confirmText: '替换',
					success(res) {
						if (res.confirm) {
							state.scanFrame.batchNumberStr = state.receiveBillScanData.FLot_Text
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			} else if (state.scanFrame.batchNumberStr == '') {
				state.scanFrame.batchNumberStr = state.receiveBillScanData.FLot_Text
			}
		} else {
			state.scanFrame.batchNumberStr = '',
				state.batchNumberStrState = true
			state.batchNumberStrPdr = '批号未启用'
		}


		//仓库校验
		if (Object.keys(state.warehouseData).length !== 0 && Object.keys(state.receiveBillScanData.StockId).length !== 0) {
			console.log('断点1');
			if (state.receiveBillScanData.StockId.Number !== state.warehouseData.FNUMBER) {
				// uni.showModal({
				// 	title: t('index.ts'), content: t('index.ymrckbt'), cancelText: t('index.qx'), confirmText: t('index.qd'),
				// 	success(res) {
				// 		if (res.confirm) {
				// 			state.scanFrame.warehouseStr = formatLangTextValue(state.receiveBillScanData.StockId.Name)
				// 			state.warehouseData = state.receiveBillScanData.StockId
				// 		} else if (res.cancel) {
				// 			console.log('用户点击取消');
				// 		}
				// 	}
				// });
			}
		} else if (Object.keys(state.warehouseData).length == 0 && Object.keys(state.receiveBillScanData.StockId).length !== 0) {
			console.log('断点2');
			state.scanFrame.warehouseStr = formatLangTextValue(state.receiveBillScanData.StockId.Name)
			state.warehouseData = {
				FIsOpenLocation: state.receiveBillScanData.StockId.IsOpenLocation,
				FNAME: formatLangTextValue(state.receiveBillScanData.StockId.Name),
				FNUMBER: state.receiveBillScanData.StockId.Number,
				FSTOCKID: state.receiveBillScanData.StockId.Id,
			}
			if (state.warehouseData.FIsOpenLocation) {
				state.NoLocationList = true
				state.NoLocationListText = t('index.ksmcw')
			} else {
				state.NoLocationList = false
				state.NoLocationListText = t('index.cwwqy')
			}
		}
		//数量校验
		if (state.scanFrame.quantityStr !== '' && Number(state.scanFrame.quantityStr) > state.receiveBillScanData.UnScanQty) {
			state.show = true
			state.quantityStrState = true
		} else if (state.scanFrame.quantityStr == '') {
			state.scanFrame.quantityStr = props.qtyState ? 1 : state.receiveBillScanData.UnScanQty
		}
		state.scanFrame.articlesStr = state.receiveBillScanData.MaterialNumber
		state.scanFrame.barCodeStr = state.receiveBillScanData.queryString

		//如果开启了异常弹出，则自动返回数据
		if (!state.receiveBillScanData.scanFrameShowSate && !state.show) {
			if (dataVerifyFun()) {
				eimts('fast', { ...state.scanFrame, warehouseData: state.warehouseData, locationData: state.locationData, id: state.receiveBillScanData.Id })
				dataErase()
			}
		}
	}
	//手动确认返回数据
	const confirmationFun = () => {
		if (dataVerifyFun()) {
			eimts('confirmation', { ...state.scanFrame, warehouseData: state.warehouseData, locationData: state.locationData || {}, id: state.receiveBillScanData.Id })
			dataErase()
			state.show = false
			eimts('boxShow',state.show)
		}
	}

	//反馈数据校验
	const dataVerifyFun = () => {
		// if (state.quantityStrState) {
		// 	uni.$u.toast('请检查您的数量')
		// 	eimts('err')
		// 	return false
		// }
		if (state.receiveBillScanData.stashVerify) {
			if (state.scanFrame.warehouseStr == '') {
				uni.$u.toast(t('index.gmkxyzdck'))
				eimts('err')
				return false
			}
			if (state.scanFrame.warehouseStr !== '' && state.NoLocationList && state.scanFrame.locationStr === '') {
				uni.$u.toast('仓位为空,不能提交')
				eimts('err')
				return false
			}
		}
		if (state.receiveBillScanData.FIsBatchManage === 'True' && (state.scanFrame.batchNumberStr === '' || state.scanFrame.batchNumberStr === ' ')) {
			uni.$u.toast(t('index.phbnwk'))
			eimts('err')
			return false
		}
		return true
	}
	//数量输入校验
	const quantityStrChangeFun = (e : any) => {
		console.log(state.receiveBillScanData);
		if (e !== '' && Number(e) !== 0) {
			if (Number(e) <= state.receiveBillScanData.UnScanQty) {
				state.quantityStrState = false
			} else {
				if (state.receiveBillScanData.quantityStateSup && state.receiveBillScanData.quantityStateSup === '0') {
					state.quantityStrState = false
				} else {
					state.quantityStrState = true
					uni.$u.toast(t('index.slbndy') + state.receiveBillScanData.UnScanQty)
					state.scanFrame.quantityStr = state.receiveBillScanData.UnScanQty
				}

			}
		} else {
			uni.$u.toast(t('index.slbnwk'))
		}
	}
	/**
	 * 弹窗逻辑
	 */
	const close = () => {
		state.show = false
		console.log('===================<><><><><><>=====================',state.show);
		eimts('boxShow',state.show)
	}
	const open = () => { 
		eimts('boxShow',state.show)
	} //待使用
	const stateShow = (val : boolean) => { state.show = val }

	/**
	 * 仓库逻辑
	 */
	const warehouseClosefun = () => {
		state.warehouse = false
	}
	const warehouseShowFun = () => {
		state.warehouse = true
	}
	const warehouseDataFun = (item : any) => {
		state.warehouseData = item
		console.log(item);
		state.scanFrame.warehouseStr = item.FNAME
		state.warehouse = false
		state.locationData = {}
		state.scanFrame.locationStr = ""
		if (state.warehouseData.FIsOpenLocation) {
			state.NoLocationList = true
			state.NoLocationListText = t('index.ksmcw')
		} else {
			state.NoLocationList = false
			state.NoLocationListText = t('index.cwwqy')
			state.scanFrame.locationStr = ''
			state.locationData = {}
		}
	}

	/**
	 * 仓位逻辑
	 */
	const debounceTimer = ref()
	const locationChange = (e : any) => {
		if (debounceTimer.value !== null) clearTimeout(debounceTimer.value)
		debounceTimer.value = setTimeout(() => {
			state.scanFrame.locationStr = e
			if (state.scanFrame.locationStr !== '' && state.scanFrame.warehouseStr !== '') {
				fnDataList()
			}
		}, 500)
	}
	const fnDataList = () => {
		let param = {
			Number: state.warehouseData.FNUMBER,
			queryString: state.scanFrame.locationStr,
			IsSortBySeq: true
		};
		fStockFlexDetailList(param).then(res => {
			uni.hideLoading();
			if (res.code == 200) {
				if (res.data.list.length) {
					state.locationData = res.data.list[0]
					state.scanFrame.locationStr = res.data.list[0].FFlexValueName
				} else {
					uni.$u.toast('未找到该仓位')
				}
			}
		});
	}
	const locationClosefun = () => {
		state.location = false
	}
	const locationStrShowFun = () => {
		if (Object.keys(state.warehouseData).length) {
			if (state.warehouseData.FIsOpenLocation) {
				state.location = true
			} else {
				uni.$u.toast(t('index.cwwqy'))
			}
		} else {
			uni.$u.toast(t('public.qxzck'))
		}
	}
	const locationDataFun = (item : any) => {
		state.locationData = item
		state.scanFrame.locationStr = item.FFlexValueName
		state.location = false
	}

	const toPages = (url : string, data : any = {}) => {
		uni.$u.route({
			url: url,
			params: data
		})
	}
	const formatLangTextValue = (val : any) => {
		let lang_Id = uni.getStorageSync('locale')
		let item = val.find(p => p.Key == (lang_Id == 'cn' ? 2052 : 1033));
		if (item != null) {
			return item.Value;
		}
		return val[0].Value;
	}
	defineExpose({
		stateShow,
		getComponentsData,
		getreceiveBillScanData,
		state,
	})
</script>

<style scoped lang="scss">
	:deep(.u-input) {
		background-color: #ffffff !important;
	}

	:deep(.u-popup__content) {
		border-top-left-radius: 16rpx;
		border-top-right-radius: 16rpx;
		box-sizing: border-box;
		padding: 16rpx;
		background-color: #F5F5F5;
	}

	.popupText {
		text-align: center;
	}

	.btnListSc {
		display: flex;
		margin: 16rpx 0;
	}

	.warningsText {
		font-size: 24rpx;
		text-align: right;
		margin-right: 8rpx;
		color: red;
	}

	.input-box {
		background-color: white;
		box-sizing: border-box;
		padding: 0 16rpx;
		border-radius: 16rpx;
		margin: 16rpx 0;

		.u-textarea {
			padding: 0 !important;
			font-size: 24rpx !important;
			color: #999999 !important;
		}

		.input-item {
			box-sizing: border-box;
			padding: 16rpx 0;
			color: #222222;
			font-size: 28rpx;
			font-weight: 400;

			.item-title {
				//font-weight: 500;
				font-size: 28rpx;
				color: #333333;
			}

			.item-text {
				font-weight: 400;
				font-size: 27rpx;
				color: #999999;
			}
		}
	}
</style>